text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CountClosedWorkflowExecutionsCommand, CountClosedWorkflowExecutionsCommandInput, CountClosedWorkflowExecutionsCommandOutput, } from "./commands/CountClosedWorkflowExecutionsCommand"; import { CountOpenWorkflowExecutionsCommand, CountOpenWorkflowExecutionsCommandInput, CountOpenWorkflowExecutionsCommandOutput, } from "./commands/CountOpenWorkflowExecutionsCommand"; import { CountPendingActivityTasksCommand, CountPendingActivityTasksCommandInput, CountPendingActivityTasksCommandOutput, } from "./commands/CountPendingActivityTasksCommand"; import { CountPendingDecisionTasksCommand, CountPendingDecisionTasksCommandInput, CountPendingDecisionTasksCommandOutput, } from "./commands/CountPendingDecisionTasksCommand"; import { DeprecateActivityTypeCommand, DeprecateActivityTypeCommandInput, DeprecateActivityTypeCommandOutput, } from "./commands/DeprecateActivityTypeCommand"; import { DeprecateDomainCommand, DeprecateDomainCommandInput, DeprecateDomainCommandOutput, } from "./commands/DeprecateDomainCommand"; import { DeprecateWorkflowTypeCommand, DeprecateWorkflowTypeCommandInput, DeprecateWorkflowTypeCommandOutput, } from "./commands/DeprecateWorkflowTypeCommand"; import { DescribeActivityTypeCommand, DescribeActivityTypeCommandInput, DescribeActivityTypeCommandOutput, } from "./commands/DescribeActivityTypeCommand"; import { DescribeDomainCommand, DescribeDomainCommandInput, DescribeDomainCommandOutput, } from "./commands/DescribeDomainCommand"; import { DescribeWorkflowExecutionCommand, DescribeWorkflowExecutionCommandInput, DescribeWorkflowExecutionCommandOutput, } from "./commands/DescribeWorkflowExecutionCommand"; import { DescribeWorkflowTypeCommand, DescribeWorkflowTypeCommandInput, DescribeWorkflowTypeCommandOutput, } from "./commands/DescribeWorkflowTypeCommand"; import { GetWorkflowExecutionHistoryCommand, GetWorkflowExecutionHistoryCommandInput, GetWorkflowExecutionHistoryCommandOutput, } from "./commands/GetWorkflowExecutionHistoryCommand"; import { ListActivityTypesCommand, ListActivityTypesCommandInput, ListActivityTypesCommandOutput, } from "./commands/ListActivityTypesCommand"; import { ListClosedWorkflowExecutionsCommand, ListClosedWorkflowExecutionsCommandInput, ListClosedWorkflowExecutionsCommandOutput, } from "./commands/ListClosedWorkflowExecutionsCommand"; import { ListDomainsCommand, ListDomainsCommandInput, ListDomainsCommandOutput } from "./commands/ListDomainsCommand"; import { ListOpenWorkflowExecutionsCommand, ListOpenWorkflowExecutionsCommandInput, ListOpenWorkflowExecutionsCommandOutput, } from "./commands/ListOpenWorkflowExecutionsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { ListWorkflowTypesCommand, ListWorkflowTypesCommandInput, ListWorkflowTypesCommandOutput, } from "./commands/ListWorkflowTypesCommand"; import { PollForActivityTaskCommand, PollForActivityTaskCommandInput, PollForActivityTaskCommandOutput, } from "./commands/PollForActivityTaskCommand"; import { PollForDecisionTaskCommand, PollForDecisionTaskCommandInput, PollForDecisionTaskCommandOutput, } from "./commands/PollForDecisionTaskCommand"; import { RecordActivityTaskHeartbeatCommand, RecordActivityTaskHeartbeatCommandInput, RecordActivityTaskHeartbeatCommandOutput, } from "./commands/RecordActivityTaskHeartbeatCommand"; import { RegisterActivityTypeCommand, RegisterActivityTypeCommandInput, RegisterActivityTypeCommandOutput, } from "./commands/RegisterActivityTypeCommand"; import { RegisterDomainCommand, RegisterDomainCommandInput, RegisterDomainCommandOutput, } from "./commands/RegisterDomainCommand"; import { RegisterWorkflowTypeCommand, RegisterWorkflowTypeCommandInput, RegisterWorkflowTypeCommandOutput, } from "./commands/RegisterWorkflowTypeCommand"; import { RequestCancelWorkflowExecutionCommand, RequestCancelWorkflowExecutionCommandInput, RequestCancelWorkflowExecutionCommandOutput, } from "./commands/RequestCancelWorkflowExecutionCommand"; import { RespondActivityTaskCanceledCommand, RespondActivityTaskCanceledCommandInput, RespondActivityTaskCanceledCommandOutput, } from "./commands/RespondActivityTaskCanceledCommand"; import { RespondActivityTaskCompletedCommand, RespondActivityTaskCompletedCommandInput, RespondActivityTaskCompletedCommandOutput, } from "./commands/RespondActivityTaskCompletedCommand"; import { RespondActivityTaskFailedCommand, RespondActivityTaskFailedCommandInput, RespondActivityTaskFailedCommandOutput, } from "./commands/RespondActivityTaskFailedCommand"; import { RespondDecisionTaskCompletedCommand, RespondDecisionTaskCompletedCommandInput, RespondDecisionTaskCompletedCommandOutput, } from "./commands/RespondDecisionTaskCompletedCommand"; import { SignalWorkflowExecutionCommand, SignalWorkflowExecutionCommandInput, SignalWorkflowExecutionCommandOutput, } from "./commands/SignalWorkflowExecutionCommand"; import { StartWorkflowExecutionCommand, StartWorkflowExecutionCommandInput, StartWorkflowExecutionCommandOutput, } from "./commands/StartWorkflowExecutionCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { TerminateWorkflowExecutionCommand, TerminateWorkflowExecutionCommandInput, TerminateWorkflowExecutionCommandOutput, } from "./commands/TerminateWorkflowExecutionCommand"; import { UndeprecateActivityTypeCommand, UndeprecateActivityTypeCommandInput, UndeprecateActivityTypeCommandOutput, } from "./commands/UndeprecateActivityTypeCommand"; import { UndeprecateDomainCommand, UndeprecateDomainCommandInput, UndeprecateDomainCommandOutput, } from "./commands/UndeprecateDomainCommand"; import { UndeprecateWorkflowTypeCommand, UndeprecateWorkflowTypeCommandInput, UndeprecateWorkflowTypeCommandOutput, } from "./commands/UndeprecateWorkflowTypeCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { SWFClient } from "./SWFClient"; /** * <fullname>Amazon Simple Workflow Service</fullname> * * <p>The Amazon Simple Workflow Service (Amazon SWF) makes it easy to build applications that use Amazon's cloud to * coordinate work across distributed components. In Amazon SWF, a <i>task</i> * represents a logical unit of work that is performed by a component of your workflow. * Coordinating tasks in a workflow involves managing intertask dependencies, scheduling, and * concurrency in accordance with the logical flow of the application.</p> * * <p>Amazon SWF gives you full control over implementing tasks and coordinating them without * worrying about underlying complexities such as tracking their progress and maintaining their * state.</p> * * <p>This documentation serves as reference only. For a broader overview of the Amazon SWF * programming model, see the <i> * <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/">Amazon SWF Developer Guide</a> * </i>.</p> */ export class SWF extends SWFClient { /** * <p>Returns the number of closed workflow executions within the given domain that meet the * specified filtering criteria.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>tagFilter.tag</code>: String constraint. The key is * <code>swf:tagFilter.tag</code>.</p> * </li> * <li> * <p> * <code>typeFilter.name</code>: String constraint. The key is * <code>swf:typeFilter.name</code>.</p> * </li> * <li> * <p> * <code>typeFilter.version</code>: String constraint. The key is * <code>swf:typeFilter.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public countClosedWorkflowExecutions( args: CountClosedWorkflowExecutionsCommandInput, options?: __HttpHandlerOptions ): Promise<CountClosedWorkflowExecutionsCommandOutput>; public countClosedWorkflowExecutions( args: CountClosedWorkflowExecutionsCommandInput, cb: (err: any, data?: CountClosedWorkflowExecutionsCommandOutput) => void ): void; public countClosedWorkflowExecutions( args: CountClosedWorkflowExecutionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CountClosedWorkflowExecutionsCommandOutput) => void ): void; public countClosedWorkflowExecutions( args: CountClosedWorkflowExecutionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CountClosedWorkflowExecutionsCommandOutput) => void), cb?: (err: any, data?: CountClosedWorkflowExecutionsCommandOutput) => void ): Promise<CountClosedWorkflowExecutionsCommandOutput> | void { const command = new CountClosedWorkflowExecutionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the number of open workflow executions within the given domain that meet the * specified filtering criteria.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>tagFilter.tag</code>: String constraint. The key is * <code>swf:tagFilter.tag</code>.</p> * </li> * <li> * <p> * <code>typeFilter.name</code>: String constraint. The key is * <code>swf:typeFilter.name</code>.</p> * </li> * <li> * <p> * <code>typeFilter.version</code>: String constraint. The key is * <code>swf:typeFilter.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public countOpenWorkflowExecutions( args: CountOpenWorkflowExecutionsCommandInput, options?: __HttpHandlerOptions ): Promise<CountOpenWorkflowExecutionsCommandOutput>; public countOpenWorkflowExecutions( args: CountOpenWorkflowExecutionsCommandInput, cb: (err: any, data?: CountOpenWorkflowExecutionsCommandOutput) => void ): void; public countOpenWorkflowExecutions( args: CountOpenWorkflowExecutionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CountOpenWorkflowExecutionsCommandOutput) => void ): void; public countOpenWorkflowExecutions( args: CountOpenWorkflowExecutionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CountOpenWorkflowExecutionsCommandOutput) => void), cb?: (err: any, data?: CountOpenWorkflowExecutionsCommandOutput) => void ): Promise<CountOpenWorkflowExecutionsCommandOutput> | void { const command = new CountOpenWorkflowExecutionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the estimated number of activity tasks in the specified task list. The count * returned is an approximation and isn't guaranteed to be exact. If you specify a task list that * no activity task was ever scheduled in then <code>0</code> is returned.</p> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the <code>taskList.name</code> parameter by using a * <code>Condition</code> element with the <code>swf:taskList.name</code> key to allow the * action to access only certain task lists.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public countPendingActivityTasks( args: CountPendingActivityTasksCommandInput, options?: __HttpHandlerOptions ): Promise<CountPendingActivityTasksCommandOutput>; public countPendingActivityTasks( args: CountPendingActivityTasksCommandInput, cb: (err: any, data?: CountPendingActivityTasksCommandOutput) => void ): void; public countPendingActivityTasks( args: CountPendingActivityTasksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CountPendingActivityTasksCommandOutput) => void ): void; public countPendingActivityTasks( args: CountPendingActivityTasksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CountPendingActivityTasksCommandOutput) => void), cb?: (err: any, data?: CountPendingActivityTasksCommandOutput) => void ): Promise<CountPendingActivityTasksCommandOutput> | void { const command = new CountPendingActivityTasksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the estimated number of decision tasks in the specified task list. The count * returned is an approximation and isn't guaranteed to be exact. If you specify a task list that * no decision task was ever scheduled in then <code>0</code> is returned.</p> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the <code>taskList.name</code> parameter by using a * <code>Condition</code> element with the <code>swf:taskList.name</code> key to allow the * action to access only certain task lists.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public countPendingDecisionTasks( args: CountPendingDecisionTasksCommandInput, options?: __HttpHandlerOptions ): Promise<CountPendingDecisionTasksCommandOutput>; public countPendingDecisionTasks( args: CountPendingDecisionTasksCommandInput, cb: (err: any, data?: CountPendingDecisionTasksCommandOutput) => void ): void; public countPendingDecisionTasks( args: CountPendingDecisionTasksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CountPendingDecisionTasksCommandOutput) => void ): void; public countPendingDecisionTasks( args: CountPendingDecisionTasksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CountPendingDecisionTasksCommandOutput) => void), cb?: (err: any, data?: CountPendingDecisionTasksCommandOutput) => void ): Promise<CountPendingDecisionTasksCommandOutput> | void { const command = new CountPendingDecisionTasksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deprecates the specified <i>activity type</i>. After an activity type has * been deprecated, you cannot create new tasks of that activity type. Tasks of this type that * were scheduled before the type was deprecated continue to run.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>activityType.name</code>: String constraint. The key is * <code>swf:activityType.name</code>.</p> * </li> * <li> * <p> * <code>activityType.version</code>: String constraint. The key is * <code>swf:activityType.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public deprecateActivityType( args: DeprecateActivityTypeCommandInput, options?: __HttpHandlerOptions ): Promise<DeprecateActivityTypeCommandOutput>; public deprecateActivityType( args: DeprecateActivityTypeCommandInput, cb: (err: any, data?: DeprecateActivityTypeCommandOutput) => void ): void; public deprecateActivityType( args: DeprecateActivityTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeprecateActivityTypeCommandOutput) => void ): void; public deprecateActivityType( args: DeprecateActivityTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeprecateActivityTypeCommandOutput) => void), cb?: (err: any, data?: DeprecateActivityTypeCommandOutput) => void ): Promise<DeprecateActivityTypeCommandOutput> | void { const command = new DeprecateActivityTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deprecates the specified domain. After a domain has been deprecated it cannot be used * to create new workflow executions or register new types. However, you can still use visibility * actions on this domain. Deprecating a domain also deprecates all activity and workflow types * registered in the domain. Executions that were started before the domain was deprecated * continues to run.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public deprecateDomain( args: DeprecateDomainCommandInput, options?: __HttpHandlerOptions ): Promise<DeprecateDomainCommandOutput>; public deprecateDomain( args: DeprecateDomainCommandInput, cb: (err: any, data?: DeprecateDomainCommandOutput) => void ): void; public deprecateDomain( args: DeprecateDomainCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeprecateDomainCommandOutput) => void ): void; public deprecateDomain( args: DeprecateDomainCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeprecateDomainCommandOutput) => void), cb?: (err: any, data?: DeprecateDomainCommandOutput) => void ): Promise<DeprecateDomainCommandOutput> | void { const command = new DeprecateDomainCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deprecates the specified <i>workflow type</i>. After a workflow type has * been deprecated, you cannot create new executions of that type. Executions that were started * before the type was deprecated continues to run. A deprecated workflow type may still be used * when calling visibility actions.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>workflowType.name</code>: String constraint. The key is * <code>swf:workflowType.name</code>.</p> * </li> * <li> * <p> * <code>workflowType.version</code>: String constraint. The key is * <code>swf:workflowType.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public deprecateWorkflowType( args: DeprecateWorkflowTypeCommandInput, options?: __HttpHandlerOptions ): Promise<DeprecateWorkflowTypeCommandOutput>; public deprecateWorkflowType( args: DeprecateWorkflowTypeCommandInput, cb: (err: any, data?: DeprecateWorkflowTypeCommandOutput) => void ): void; public deprecateWorkflowType( args: DeprecateWorkflowTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeprecateWorkflowTypeCommandOutput) => void ): void; public deprecateWorkflowType( args: DeprecateWorkflowTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeprecateWorkflowTypeCommandOutput) => void), cb?: (err: any, data?: DeprecateWorkflowTypeCommandOutput) => void ): Promise<DeprecateWorkflowTypeCommandOutput> | void { const command = new DeprecateWorkflowTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the specified activity type. This includes configuration * settings provided when the type was registered and other general information about the * type.</p> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>activityType.name</code>: String constraint. The key is * <code>swf:activityType.name</code>.</p> * </li> * <li> * <p> * <code>activityType.version</code>: String constraint. The key is * <code>swf:activityType.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public describeActivityType( args: DescribeActivityTypeCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeActivityTypeCommandOutput>; public describeActivityType( args: DescribeActivityTypeCommandInput, cb: (err: any, data?: DescribeActivityTypeCommandOutput) => void ): void; public describeActivityType( args: DescribeActivityTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeActivityTypeCommandOutput) => void ): void; public describeActivityType( args: DescribeActivityTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeActivityTypeCommandOutput) => void), cb?: (err: any, data?: DescribeActivityTypeCommandOutput) => void ): Promise<DescribeActivityTypeCommandOutput> | void { const command = new DescribeActivityTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the specified domain, including description and * status.</p> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public describeDomain( args: DescribeDomainCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeDomainCommandOutput>; public describeDomain( args: DescribeDomainCommandInput, cb: (err: any, data?: DescribeDomainCommandOutput) => void ): void; public describeDomain( args: DescribeDomainCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeDomainCommandOutput) => void ): void; public describeDomain( args: DescribeDomainCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeDomainCommandOutput) => void), cb?: (err: any, data?: DescribeDomainCommandOutput) => void ): Promise<DescribeDomainCommandOutput> | void { const command = new DescribeDomainCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the specified workflow execution including its type and some * statistics.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public describeWorkflowExecution( args: DescribeWorkflowExecutionCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeWorkflowExecutionCommandOutput>; public describeWorkflowExecution( args: DescribeWorkflowExecutionCommandInput, cb: (err: any, data?: DescribeWorkflowExecutionCommandOutput) => void ): void; public describeWorkflowExecution( args: DescribeWorkflowExecutionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeWorkflowExecutionCommandOutput) => void ): void; public describeWorkflowExecution( args: DescribeWorkflowExecutionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeWorkflowExecutionCommandOutput) => void), cb?: (err: any, data?: DescribeWorkflowExecutionCommandOutput) => void ): Promise<DescribeWorkflowExecutionCommandOutput> | void { const command = new DescribeWorkflowExecutionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the specified <i>workflow type</i>. This * includes configuration settings specified when the type was registered and other information * such as creation date, current status, etc.</p> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>workflowType.name</code>: String constraint. The key is * <code>swf:workflowType.name</code>.</p> * </li> * <li> * <p> * <code>workflowType.version</code>: String constraint. The key is * <code>swf:workflowType.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public describeWorkflowType( args: DescribeWorkflowTypeCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeWorkflowTypeCommandOutput>; public describeWorkflowType( args: DescribeWorkflowTypeCommandInput, cb: (err: any, data?: DescribeWorkflowTypeCommandOutput) => void ): void; public describeWorkflowType( args: DescribeWorkflowTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeWorkflowTypeCommandOutput) => void ): void; public describeWorkflowType( args: DescribeWorkflowTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeWorkflowTypeCommandOutput) => void), cb?: (err: any, data?: DescribeWorkflowTypeCommandOutput) => void ): Promise<DescribeWorkflowTypeCommandOutput> | void { const command = new DescribeWorkflowTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the history of the specified workflow execution. The results may be split into * multiple pages. To retrieve subsequent pages, make the call again using the * <code>nextPageToken</code> returned by the initial call.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public getWorkflowExecutionHistory( args: GetWorkflowExecutionHistoryCommandInput, options?: __HttpHandlerOptions ): Promise<GetWorkflowExecutionHistoryCommandOutput>; public getWorkflowExecutionHistory( args: GetWorkflowExecutionHistoryCommandInput, cb: (err: any, data?: GetWorkflowExecutionHistoryCommandOutput) => void ): void; public getWorkflowExecutionHistory( args: GetWorkflowExecutionHistoryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetWorkflowExecutionHistoryCommandOutput) => void ): void; public getWorkflowExecutionHistory( args: GetWorkflowExecutionHistoryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetWorkflowExecutionHistoryCommandOutput) => void), cb?: (err: any, data?: GetWorkflowExecutionHistoryCommandOutput) => void ): Promise<GetWorkflowExecutionHistoryCommandOutput> | void { const command = new GetWorkflowExecutionHistoryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about all activities registered in the specified domain that match * the specified name and registration status. The result includes information like creation * date, current status of the activity, etc. The results may be split into multiple pages. To * retrieve subsequent pages, make the call again using the <code>nextPageToken</code> returned * by the initial call.</p> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public listActivityTypes( args: ListActivityTypesCommandInput, options?: __HttpHandlerOptions ): Promise<ListActivityTypesCommandOutput>; public listActivityTypes( args: ListActivityTypesCommandInput, cb: (err: any, data?: ListActivityTypesCommandOutput) => void ): void; public listActivityTypes( args: ListActivityTypesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListActivityTypesCommandOutput) => void ): void; public listActivityTypes( args: ListActivityTypesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListActivityTypesCommandOutput) => void), cb?: (err: any, data?: ListActivityTypesCommandOutput) => void ): Promise<ListActivityTypesCommandOutput> | void { const command = new ListActivityTypesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of closed workflow executions in the specified domain that meet the * filtering criteria. The results may be split into multiple pages. To retrieve subsequent * pages, make the call again using the nextPageToken returned by the initial call.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>tagFilter.tag</code>: String constraint. The key is * <code>swf:tagFilter.tag</code>.</p> * </li> * <li> * <p> * <code>typeFilter.name</code>: String constraint. The key is * <code>swf:typeFilter.name</code>.</p> * </li> * <li> * <p> * <code>typeFilter.version</code>: String constraint. The key is * <code>swf:typeFilter.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public listClosedWorkflowExecutions( args: ListClosedWorkflowExecutionsCommandInput, options?: __HttpHandlerOptions ): Promise<ListClosedWorkflowExecutionsCommandOutput>; public listClosedWorkflowExecutions( args: ListClosedWorkflowExecutionsCommandInput, cb: (err: any, data?: ListClosedWorkflowExecutionsCommandOutput) => void ): void; public listClosedWorkflowExecutions( args: ListClosedWorkflowExecutionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListClosedWorkflowExecutionsCommandOutput) => void ): void; public listClosedWorkflowExecutions( args: ListClosedWorkflowExecutionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListClosedWorkflowExecutionsCommandOutput) => void), cb?: (err: any, data?: ListClosedWorkflowExecutionsCommandOutput) => void ): Promise<ListClosedWorkflowExecutionsCommandOutput> | void { const command = new ListClosedWorkflowExecutionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the list of domains registered in the account. The results may be split into * multiple pages. To retrieve subsequent pages, make the call again using the nextPageToken * returned by the initial call.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains. The element must be set to * <code>arn:aws:swf::AccountID:domain/*</code>, where <i>AccountID</i> is * the account ID, with no dashes.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public listDomains(args: ListDomainsCommandInput, options?: __HttpHandlerOptions): Promise<ListDomainsCommandOutput>; public listDomains(args: ListDomainsCommandInput, cb: (err: any, data?: ListDomainsCommandOutput) => void): void; public listDomains( args: ListDomainsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListDomainsCommandOutput) => void ): void; public listDomains( args: ListDomainsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDomainsCommandOutput) => void), cb?: (err: any, data?: ListDomainsCommandOutput) => void ): Promise<ListDomainsCommandOutput> | void { const command = new ListDomainsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a list of open workflow executions in the specified domain that meet the * filtering criteria. The results may be split into multiple pages. To retrieve subsequent * pages, make the call again using the nextPageToken returned by the initial call.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>tagFilter.tag</code>: String constraint. The key is * <code>swf:tagFilter.tag</code>.</p> * </li> * <li> * <p> * <code>typeFilter.name</code>: String constraint. The key is * <code>swf:typeFilter.name</code>.</p> * </li> * <li> * <p> * <code>typeFilter.version</code>: String constraint. The key is * <code>swf:typeFilter.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public listOpenWorkflowExecutions( args: ListOpenWorkflowExecutionsCommandInput, options?: __HttpHandlerOptions ): Promise<ListOpenWorkflowExecutionsCommandOutput>; public listOpenWorkflowExecutions( args: ListOpenWorkflowExecutionsCommandInput, cb: (err: any, data?: ListOpenWorkflowExecutionsCommandOutput) => void ): void; public listOpenWorkflowExecutions( args: ListOpenWorkflowExecutionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListOpenWorkflowExecutionsCommandOutput) => void ): void; public listOpenWorkflowExecutions( args: ListOpenWorkflowExecutionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListOpenWorkflowExecutionsCommandOutput) => void), cb?: (err: any, data?: ListOpenWorkflowExecutionsCommandOutput) => void ): Promise<ListOpenWorkflowExecutionsCommandOutput> | void { const command = new ListOpenWorkflowExecutionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>List tags for a given domain.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about workflow types in the specified domain. The results may be * split into multiple pages that can be retrieved by making the call repeatedly.</p> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public listWorkflowTypes( args: ListWorkflowTypesCommandInput, options?: __HttpHandlerOptions ): Promise<ListWorkflowTypesCommandOutput>; public listWorkflowTypes( args: ListWorkflowTypesCommandInput, cb: (err: any, data?: ListWorkflowTypesCommandOutput) => void ): void; public listWorkflowTypes( args: ListWorkflowTypesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListWorkflowTypesCommandOutput) => void ): void; public listWorkflowTypes( args: ListWorkflowTypesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListWorkflowTypesCommandOutput) => void), cb?: (err: any, data?: ListWorkflowTypesCommandOutput) => void ): Promise<ListWorkflowTypesCommandOutput> | void { const command = new ListWorkflowTypesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used by workers to get an <a>ActivityTask</a> from the specified activity * <code>taskList</code>. This initiates a long poll, where the service holds the HTTP * connection open and responds as soon as a task becomes available. The maximum time the service * holds on to the request before responding is 60 seconds. If no task is available within 60 * seconds, the poll returns an empty result. An empty result, in this context, means that an * ActivityTask is returned, but that the value of taskToken is an empty string. If a task is * returned, the worker should use its type to identify and process it correctly.</p> * <important> * <p>Workers should set their client side socket timeout to at least 70 seconds (10 * seconds higher than the maximum time service may hold the poll request).</p> * </important> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the <code>taskList.name</code> parameter by using a * <code>Condition</code> element with the <code>swf:taskList.name</code> key to allow the * action to access only certain task lists.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public pollForActivityTask( args: PollForActivityTaskCommandInput, options?: __HttpHandlerOptions ): Promise<PollForActivityTaskCommandOutput>; public pollForActivityTask( args: PollForActivityTaskCommandInput, cb: (err: any, data?: PollForActivityTaskCommandOutput) => void ): void; public pollForActivityTask( args: PollForActivityTaskCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PollForActivityTaskCommandOutput) => void ): void; public pollForActivityTask( args: PollForActivityTaskCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PollForActivityTaskCommandOutput) => void), cb?: (err: any, data?: PollForActivityTaskCommandOutput) => void ): Promise<PollForActivityTaskCommandOutput> | void { const command = new PollForActivityTaskCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used by deciders to get a <a>DecisionTask</a> from the specified decision * <code>taskList</code>. A decision task may be returned for any open workflow execution that * is using the specified task list. The task includes a paginated view of the history of the * workflow execution. The decider should use the workflow type and the history to determine how * to properly handle the task.</p> * <p>This action initiates a long poll, where the service holds the HTTP connection open and * responds as soon a task becomes available. If no decision task is available in the specified * task list before the timeout of 60 seconds expires, an empty result is returned. An empty * result, in this context, means that a DecisionTask is returned, but that the value of * taskToken is an empty string.</p> * <important> * <p>Deciders should set their client side socket timeout to at least 70 seconds (10 * seconds higher than the timeout).</p> * </important> * <important> * <p>Because the number of workflow history events for a single workflow execution might * be very large, the result returned might be split up across a number of pages. To retrieve * subsequent pages, make additional calls to <code>PollForDecisionTask</code> using the * <code>nextPageToken</code> returned by the initial call. Note that you do * <i>not</i> call <code>GetWorkflowExecutionHistory</code> with this * <code>nextPageToken</code>. Instead, call <code>PollForDecisionTask</code> * again.</p> * </important> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the <code>taskList.name</code> parameter by using a * <code>Condition</code> element with the <code>swf:taskList.name</code> key to allow the * action to access only certain task lists.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public pollForDecisionTask( args: PollForDecisionTaskCommandInput, options?: __HttpHandlerOptions ): Promise<PollForDecisionTaskCommandOutput>; public pollForDecisionTask( args: PollForDecisionTaskCommandInput, cb: (err: any, data?: PollForDecisionTaskCommandOutput) => void ): void; public pollForDecisionTask( args: PollForDecisionTaskCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PollForDecisionTaskCommandOutput) => void ): void; public pollForDecisionTask( args: PollForDecisionTaskCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PollForDecisionTaskCommandOutput) => void), cb?: (err: any, data?: PollForDecisionTaskCommandOutput) => void ): Promise<PollForDecisionTaskCommandOutput> | void { const command = new PollForDecisionTaskCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used by activity workers to report to the service that the <a>ActivityTask</a> represented by the specified <code>taskToken</code> is still making progress. The worker * can also specify details of the progress, for example percent complete, using the * <code>details</code> parameter. This action can also be used by the worker as a mechanism to * check if cancellation is being requested for the activity task. If a cancellation is being * attempted for the specified task, then the boolean <code>cancelRequested</code> flag returned * by the service is set to <code>true</code>.</p> * <p>This action resets the <code>taskHeartbeatTimeout</code> clock. The * <code>taskHeartbeatTimeout</code> is specified in <a>RegisterActivityType</a>.</p> * <p>This action doesn't in itself create an event in the workflow execution history. * However, if the task times out, the workflow execution history contains a * <code>ActivityTaskTimedOut</code> event that contains the information from the last * heartbeat generated by the activity worker.</p> * <note> * <p>The <code>taskStartToCloseTimeout</code> of an activity type is the maximum duration * of an activity task, regardless of the number of <a>RecordActivityTaskHeartbeat</a> requests received. The <code>taskStartToCloseTimeout</code> is also specified in <a>RegisterActivityType</a>.</p> * </note> * <note> * <p>This operation is only useful for long-lived activities to report liveliness of the * task and to determine if a cancellation is being attempted.</p> * </note> * <important> * <p>If the <code>cancelRequested</code> flag returns <code>true</code>, a cancellation is * being attempted. If the worker can cancel the activity, it should respond with <a>RespondActivityTaskCanceled</a>. Otherwise, it should ignore the cancellation * request.</p> * </important> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public recordActivityTaskHeartbeat( args: RecordActivityTaskHeartbeatCommandInput, options?: __HttpHandlerOptions ): Promise<RecordActivityTaskHeartbeatCommandOutput>; public recordActivityTaskHeartbeat( args: RecordActivityTaskHeartbeatCommandInput, cb: (err: any, data?: RecordActivityTaskHeartbeatCommandOutput) => void ): void; public recordActivityTaskHeartbeat( args: RecordActivityTaskHeartbeatCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RecordActivityTaskHeartbeatCommandOutput) => void ): void; public recordActivityTaskHeartbeat( args: RecordActivityTaskHeartbeatCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RecordActivityTaskHeartbeatCommandOutput) => void), cb?: (err: any, data?: RecordActivityTaskHeartbeatCommandOutput) => void ): Promise<RecordActivityTaskHeartbeatCommandOutput> | void { const command = new RecordActivityTaskHeartbeatCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Registers a new <i>activity type</i> along with its configuration * settings in the specified domain.</p> * <important> * <p>A <code>TypeAlreadyExists</code> fault is returned if the type already exists in the * domain. You cannot change any configuration settings of the type after its registration, and * it must be registered as a new version.</p> * </important> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>defaultTaskList.name</code>: String constraint. The key is * <code>swf:defaultTaskList.name</code>.</p> * </li> * <li> * <p> * <code>name</code>: String constraint. The key is <code>swf:name</code>.</p> * </li> * <li> * <p> * <code>version</code>: String constraint. The key is * <code>swf:version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public registerActivityType( args: RegisterActivityTypeCommandInput, options?: __HttpHandlerOptions ): Promise<RegisterActivityTypeCommandOutput>; public registerActivityType( args: RegisterActivityTypeCommandInput, cb: (err: any, data?: RegisterActivityTypeCommandOutput) => void ): void; public registerActivityType( args: RegisterActivityTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RegisterActivityTypeCommandOutput) => void ): void; public registerActivityType( args: RegisterActivityTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RegisterActivityTypeCommandOutput) => void), cb?: (err: any, data?: RegisterActivityTypeCommandOutput) => void ): Promise<RegisterActivityTypeCommandOutput> | void { const command = new RegisterActivityTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Registers a new domain.</p> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>You cannot use an IAM policy to control domain access for this action. The name of * the domain being registered is available as the resource of this action.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public registerDomain( args: RegisterDomainCommandInput, options?: __HttpHandlerOptions ): Promise<RegisterDomainCommandOutput>; public registerDomain( args: RegisterDomainCommandInput, cb: (err: any, data?: RegisterDomainCommandOutput) => void ): void; public registerDomain( args: RegisterDomainCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RegisterDomainCommandOutput) => void ): void; public registerDomain( args: RegisterDomainCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RegisterDomainCommandOutput) => void), cb?: (err: any, data?: RegisterDomainCommandOutput) => void ): Promise<RegisterDomainCommandOutput> | void { const command = new RegisterDomainCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Registers a new <i>workflow type</i> and its configuration settings in * the specified domain.</p> * <p>The retention period for the workflow history is set by the <a>RegisterDomain</a> action.</p> * <important> * <p>If the type already exists, then a <code>TypeAlreadyExists</code> fault is returned. * You cannot change the configuration settings of a workflow type once it is registered and it * must be registered as a new version.</p> * </important> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>defaultTaskList.name</code>: String constraint. The key is * <code>swf:defaultTaskList.name</code>.</p> * </li> * <li> * <p> * <code>name</code>: String constraint. The key is <code>swf:name</code>.</p> * </li> * <li> * <p> * <code>version</code>: String constraint. The key is * <code>swf:version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public registerWorkflowType( args: RegisterWorkflowTypeCommandInput, options?: __HttpHandlerOptions ): Promise<RegisterWorkflowTypeCommandOutput>; public registerWorkflowType( args: RegisterWorkflowTypeCommandInput, cb: (err: any, data?: RegisterWorkflowTypeCommandOutput) => void ): void; public registerWorkflowType( args: RegisterWorkflowTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RegisterWorkflowTypeCommandOutput) => void ): void; public registerWorkflowType( args: RegisterWorkflowTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RegisterWorkflowTypeCommandOutput) => void), cb?: (err: any, data?: RegisterWorkflowTypeCommandOutput) => void ): Promise<RegisterWorkflowTypeCommandOutput> | void { const command = new RegisterWorkflowTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Records a <code>WorkflowExecutionCancelRequested</code> event in the currently running * workflow execution identified by the given domain, workflowId, and runId. This logically * requests the cancellation of the workflow execution as a whole. It is up to the decider to * take appropriate actions when it receives an execution history with this event.</p> * * <note> * <p>If the runId isn't specified, the <code>WorkflowExecutionCancelRequested</code> event * is recorded in the history of the current open workflow execution with the specified * workflowId in the domain.</p> * </note> * * <note> * <p>Because this action allows the workflow to properly clean up and gracefully close, it * should be used instead of <a>TerminateWorkflowExecution</a> when * possible.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public requestCancelWorkflowExecution( args: RequestCancelWorkflowExecutionCommandInput, options?: __HttpHandlerOptions ): Promise<RequestCancelWorkflowExecutionCommandOutput>; public requestCancelWorkflowExecution( args: RequestCancelWorkflowExecutionCommandInput, cb: (err: any, data?: RequestCancelWorkflowExecutionCommandOutput) => void ): void; public requestCancelWorkflowExecution( args: RequestCancelWorkflowExecutionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RequestCancelWorkflowExecutionCommandOutput) => void ): void; public requestCancelWorkflowExecution( args: RequestCancelWorkflowExecutionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RequestCancelWorkflowExecutionCommandOutput) => void), cb?: (err: any, data?: RequestCancelWorkflowExecutionCommandOutput) => void ): Promise<RequestCancelWorkflowExecutionCommandOutput> | void { const command = new RequestCancelWorkflowExecutionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used by workers to tell the service that the <a>ActivityTask</a> identified * by the <code>taskToken</code> was successfully canceled. Additional <code>details</code> can * be provided using the <code>details</code> argument.</p> * * <p>These <code>details</code> (if provided) appear in the * <code>ActivityTaskCanceled</code> event added to the workflow history.</p> * * <important> * <p>Only use this operation if the <code>canceled</code> flag of a <a>RecordActivityTaskHeartbeat</a> request returns <code>true</code> and if the * activity can be safely undone or abandoned.</p> * </important> * * <p>A task is considered open from the time that it is scheduled until it is closed. * Therefore a task is reported as open while a worker is processing it. A task is closed after * it has been specified in a call to <a>RespondActivityTaskCompleted</a>, * RespondActivityTaskCanceled, <a>RespondActivityTaskFailed</a>, or the task has * <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dg-basic.html#swf-dev-timeout-types">timed * out</a>.</p> * * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public respondActivityTaskCanceled( args: RespondActivityTaskCanceledCommandInput, options?: __HttpHandlerOptions ): Promise<RespondActivityTaskCanceledCommandOutput>; public respondActivityTaskCanceled( args: RespondActivityTaskCanceledCommandInput, cb: (err: any, data?: RespondActivityTaskCanceledCommandOutput) => void ): void; public respondActivityTaskCanceled( args: RespondActivityTaskCanceledCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RespondActivityTaskCanceledCommandOutput) => void ): void; public respondActivityTaskCanceled( args: RespondActivityTaskCanceledCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RespondActivityTaskCanceledCommandOutput) => void), cb?: (err: any, data?: RespondActivityTaskCanceledCommandOutput) => void ): Promise<RespondActivityTaskCanceledCommandOutput> | void { const command = new RespondActivityTaskCanceledCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used by workers to tell the service that the <a>ActivityTask</a> identified * by the <code>taskToken</code> completed successfully with a <code>result</code> (if provided). * The <code>result</code> appears in the <code>ActivityTaskCompleted</code> event in the * workflow history.</p> * * <important> * <p>If the requested task doesn't complete successfully, use <a>RespondActivityTaskFailed</a> instead. If the worker finds that the task is * canceled through the <code>canceled</code> flag returned by <a>RecordActivityTaskHeartbeat</a>, it should cancel the task, clean up and then call * <a>RespondActivityTaskCanceled</a>.</p> * </important> * * <p>A task is considered open from the time that it is scheduled until it is closed. * Therefore a task is reported as open while a worker is processing it. A task is closed after * it has been specified in a call to RespondActivityTaskCompleted, <a>RespondActivityTaskCanceled</a>, <a>RespondActivityTaskFailed</a>, or the * task has <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dg-basic.html#swf-dev-timeout-types">timed * out</a>.</p> * * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public respondActivityTaskCompleted( args: RespondActivityTaskCompletedCommandInput, options?: __HttpHandlerOptions ): Promise<RespondActivityTaskCompletedCommandOutput>; public respondActivityTaskCompleted( args: RespondActivityTaskCompletedCommandInput, cb: (err: any, data?: RespondActivityTaskCompletedCommandOutput) => void ): void; public respondActivityTaskCompleted( args: RespondActivityTaskCompletedCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RespondActivityTaskCompletedCommandOutput) => void ): void; public respondActivityTaskCompleted( args: RespondActivityTaskCompletedCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RespondActivityTaskCompletedCommandOutput) => void), cb?: (err: any, data?: RespondActivityTaskCompletedCommandOutput) => void ): Promise<RespondActivityTaskCompletedCommandOutput> | void { const command = new RespondActivityTaskCompletedCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used by workers to tell the service that the <a>ActivityTask</a> identified * by the <code>taskToken</code> has failed with <code>reason</code> (if specified). The * <code>reason</code> and <code>details</code> appear in the <code>ActivityTaskFailed</code> * event added to the workflow history.</p> * * <p>A task is considered open from the time that it is scheduled until it is closed. * Therefore a task is reported as open while a worker is processing it. A task is closed after * it has been specified in a call to <a>RespondActivityTaskCompleted</a>, <a>RespondActivityTaskCanceled</a>, RespondActivityTaskFailed, or the task has <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dg-basic.html#swf-dev-timeout-types">timed * out</a>.</p> * * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public respondActivityTaskFailed( args: RespondActivityTaskFailedCommandInput, options?: __HttpHandlerOptions ): Promise<RespondActivityTaskFailedCommandOutput>; public respondActivityTaskFailed( args: RespondActivityTaskFailedCommandInput, cb: (err: any, data?: RespondActivityTaskFailedCommandOutput) => void ): void; public respondActivityTaskFailed( args: RespondActivityTaskFailedCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RespondActivityTaskFailedCommandOutput) => void ): void; public respondActivityTaskFailed( args: RespondActivityTaskFailedCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RespondActivityTaskFailedCommandOutput) => void), cb?: (err: any, data?: RespondActivityTaskFailedCommandOutput) => void ): Promise<RespondActivityTaskFailedCommandOutput> | void { const command = new RespondActivityTaskFailedCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Used by deciders to tell the service that the <a>DecisionTask</a> identified * by the <code>taskToken</code> has successfully completed. The <code>decisions</code> argument * specifies the list of decisions made while processing the task.</p> * * <p>A <code>DecisionTaskCompleted</code> event is added to the workflow history. The * <code>executionContext</code> specified is attached to the event in the workflow execution * history.</p> * * <p> * <b>Access Control</b> * </p> * * <p>If an IAM policy grants permission to use <code>RespondDecisionTaskCompleted</code>, it * can express permissions for the list of decisions in the <code>decisions</code> parameter. * Each of the decisions has one or more parameters, much like a regular API call. To allow for * policies to be as readable as possible, you can express permissions on decisions as if they * were actual API calls, including applying conditions to some parameters. For more information, * see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using * IAM to Manage Access to Amazon SWF Workflows</a> in the * <i>Amazon SWF Developer Guide</i>.</p> */ public respondDecisionTaskCompleted( args: RespondDecisionTaskCompletedCommandInput, options?: __HttpHandlerOptions ): Promise<RespondDecisionTaskCompletedCommandOutput>; public respondDecisionTaskCompleted( args: RespondDecisionTaskCompletedCommandInput, cb: (err: any, data?: RespondDecisionTaskCompletedCommandOutput) => void ): void; public respondDecisionTaskCompleted( args: RespondDecisionTaskCompletedCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RespondDecisionTaskCompletedCommandOutput) => void ): void; public respondDecisionTaskCompleted( args: RespondDecisionTaskCompletedCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RespondDecisionTaskCompletedCommandOutput) => void), cb?: (err: any, data?: RespondDecisionTaskCompletedCommandOutput) => void ): Promise<RespondDecisionTaskCompletedCommandOutput> | void { const command = new RespondDecisionTaskCompletedCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Records a <code>WorkflowExecutionSignaled</code> event in the workflow execution * history and creates a decision task for the workflow execution identified by the given domain, * workflowId and runId. The event is recorded with the specified user defined signalName and * input (if provided).</p> * * <note> * <p>If a runId isn't specified, then the <code>WorkflowExecutionSignaled</code> event is * recorded in the history of the current open workflow with the matching workflowId in the * domain.</p> * </note> * * <note> * <p>If the specified workflow execution isn't open, this method fails with * <code>UnknownResource</code>.</p> * </note> * * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public signalWorkflowExecution( args: SignalWorkflowExecutionCommandInput, options?: __HttpHandlerOptions ): Promise<SignalWorkflowExecutionCommandOutput>; public signalWorkflowExecution( args: SignalWorkflowExecutionCommandInput, cb: (err: any, data?: SignalWorkflowExecutionCommandOutput) => void ): void; public signalWorkflowExecution( args: SignalWorkflowExecutionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: SignalWorkflowExecutionCommandOutput) => void ): void; public signalWorkflowExecution( args: SignalWorkflowExecutionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SignalWorkflowExecutionCommandOutput) => void), cb?: (err: any, data?: SignalWorkflowExecutionCommandOutput) => void ): Promise<SignalWorkflowExecutionCommandOutput> | void { const command = new SignalWorkflowExecutionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Starts an execution of the workflow type in the specified domain using the provided * <code>workflowId</code> and input data.</p> * * <p>This action returns the newly started workflow execution.</p> * * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>tagList.member.0</code>: The key is <code>swf:tagList.member.0</code>.</p> * </li> * <li> * <p> * <code>tagList.member.1</code>: The key is <code>swf:tagList.member.1</code>.</p> * </li> * <li> * <p> * <code>tagList.member.2</code>: The key is <code>swf:tagList.member.2</code>.</p> * </li> * <li> * <p> * <code>tagList.member.3</code>: The key is <code>swf:tagList.member.3</code>.</p> * </li> * <li> * <p> * <code>tagList.member.4</code>: The key is <code>swf:tagList.member.4</code>.</p> * </li> * <li> * <p> * <code>taskList</code>: String constraint. The key is * <code>swf:taskList.name</code>.</p> * </li> * <li> * <p> * <code>workflowType.name</code>: String constraint. The key is * <code>swf:workflowType.name</code>.</p> * </li> * <li> * <p> * <code>workflowType.version</code>: String constraint. The key is * <code>swf:workflowType.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public startWorkflowExecution( args: StartWorkflowExecutionCommandInput, options?: __HttpHandlerOptions ): Promise<StartWorkflowExecutionCommandOutput>; public startWorkflowExecution( args: StartWorkflowExecutionCommandInput, cb: (err: any, data?: StartWorkflowExecutionCommandOutput) => void ): void; public startWorkflowExecution( args: StartWorkflowExecutionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StartWorkflowExecutionCommandOutput) => void ): void; public startWorkflowExecution( args: StartWorkflowExecutionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartWorkflowExecutionCommandOutput) => void), cb?: (err: any, data?: StartWorkflowExecutionCommandOutput) => void ): Promise<StartWorkflowExecutionCommandOutput> | void { const command = new StartWorkflowExecutionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Add a tag to a Amazon SWF domain.</p> * <note> * <p>Amazon SWF supports a maximum of 50 tags per resource.</p> * </note> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Records a <code>WorkflowExecutionTerminated</code> event and forces closure of the * workflow execution identified by the given domain, runId, and workflowId. The child policy, * registered with the workflow type or specified when starting this execution, is applied to any * open child workflow executions of this workflow execution.</p> * * <important> * <p>If the identified workflow execution was in progress, it is terminated * immediately.</p> * </important> * * <note> * <p>If a runId isn't specified, then the <code>WorkflowExecutionTerminated</code> event * is recorded in the history of the current open workflow with the matching workflowId in the * domain.</p> * </note> * * <note> * <p>You should consider using <a>RequestCancelWorkflowExecution</a> action * instead because it allows the workflow to gracefully close while <a>TerminateWorkflowExecution</a> doesn't.</p> * </note> * * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public terminateWorkflowExecution( args: TerminateWorkflowExecutionCommandInput, options?: __HttpHandlerOptions ): Promise<TerminateWorkflowExecutionCommandOutput>; public terminateWorkflowExecution( args: TerminateWorkflowExecutionCommandInput, cb: (err: any, data?: TerminateWorkflowExecutionCommandOutput) => void ): void; public terminateWorkflowExecution( args: TerminateWorkflowExecutionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TerminateWorkflowExecutionCommandOutput) => void ): void; public terminateWorkflowExecution( args: TerminateWorkflowExecutionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TerminateWorkflowExecutionCommandOutput) => void), cb?: (err: any, data?: TerminateWorkflowExecutionCommandOutput) => void ): Promise<TerminateWorkflowExecutionCommandOutput> | void { const command = new TerminateWorkflowExecutionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Undeprecates a previously deprecated <i>activity type</i>. After an activity type has * been undeprecated, you can create new tasks of that activity type.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>activityType.name</code>: String constraint. The key is * <code>swf:activityType.name</code>.</p> * </li> * <li> * <p> * <code>activityType.version</code>: String constraint. The key is * <code>swf:activityType.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public undeprecateActivityType( args: UndeprecateActivityTypeCommandInput, options?: __HttpHandlerOptions ): Promise<UndeprecateActivityTypeCommandOutput>; public undeprecateActivityType( args: UndeprecateActivityTypeCommandInput, cb: (err: any, data?: UndeprecateActivityTypeCommandOutput) => void ): void; public undeprecateActivityType( args: UndeprecateActivityTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UndeprecateActivityTypeCommandOutput) => void ): void; public undeprecateActivityType( args: UndeprecateActivityTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UndeprecateActivityTypeCommandOutput) => void), cb?: (err: any, data?: UndeprecateActivityTypeCommandOutput) => void ): Promise<UndeprecateActivityTypeCommandOutput> | void { const command = new UndeprecateActivityTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Undeprecates a previously deprecated domain. After a domain has been undeprecated it can be used * to create new workflow executions or register new types.</p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>You cannot use an IAM policy to constrain this action's parameters.</p> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public undeprecateDomain( args: UndeprecateDomainCommandInput, options?: __HttpHandlerOptions ): Promise<UndeprecateDomainCommandOutput>; public undeprecateDomain( args: UndeprecateDomainCommandInput, cb: (err: any, data?: UndeprecateDomainCommandOutput) => void ): void; public undeprecateDomain( args: UndeprecateDomainCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UndeprecateDomainCommandOutput) => void ): void; public undeprecateDomain( args: UndeprecateDomainCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UndeprecateDomainCommandOutput) => void), cb?: (err: any, data?: UndeprecateDomainCommandOutput) => void ): Promise<UndeprecateDomainCommandOutput> | void { const command = new UndeprecateDomainCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Undeprecates a previously deprecated <i>workflow type</i>. After a workflow type has * been undeprecated, you can create new executions of that type. </p> * <note> * <p>This operation is eventually consistent. The results are best effort and may not * exactly reflect recent updates and changes.</p> * </note> * <p> * <b>Access Control</b> * </p> * <p>You can use IAM policies to control this action's access to Amazon SWF resources as * follows:</p> * <ul> * <li> * <p>Use a <code>Resource</code> element with the domain name to limit the action to * only specified domains.</p> * </li> * <li> * <p>Use an <code>Action</code> element to allow or deny permission to call this * action.</p> * </li> * <li> * <p>Constrain the following parameters by using a <code>Condition</code> element with * the appropriate keys.</p> * <ul> * <li> * <p> * <code>workflowType.name</code>: String constraint. The key is * <code>swf:workflowType.name</code>.</p> * </li> * <li> * <p> * <code>workflowType.version</code>: String constraint. The key is * <code>swf:workflowType.version</code>.</p> * </li> * </ul> * </li> * </ul> * <p>If the caller doesn't have sufficient permissions to invoke the action, or the * parameter values fall outside the specified constraints, the action fails. The associated * event attribute's <code>cause</code> parameter is set to <code>OPERATION_NOT_PERMITTED</code>. * For details and example IAM policies, see <a href="https://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access to Amazon SWF * Workflows</a> in the <i>Amazon SWF Developer Guide</i>.</p> */ public undeprecateWorkflowType( args: UndeprecateWorkflowTypeCommandInput, options?: __HttpHandlerOptions ): Promise<UndeprecateWorkflowTypeCommandOutput>; public undeprecateWorkflowType( args: UndeprecateWorkflowTypeCommandInput, cb: (err: any, data?: UndeprecateWorkflowTypeCommandOutput) => void ): void; public undeprecateWorkflowType( args: UndeprecateWorkflowTypeCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UndeprecateWorkflowTypeCommandOutput) => void ): void; public undeprecateWorkflowType( args: UndeprecateWorkflowTypeCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UndeprecateWorkflowTypeCommandOutput) => void), cb?: (err: any, data?: UndeprecateWorkflowTypeCommandOutput) => void ): Promise<UndeprecateWorkflowTypeCommandOutput> | void { const command = new UndeprecateWorkflowTypeCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Remove a tag from a Amazon SWF domain.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { createElement, setCulture } from '@syncfusion/ej2-base'; import { DropDownTree } from '../../../src/drop-down-tree/drop-down-tree'; import { hierarchicalData, hierarchicalData1, hierarchicalData3, hierarchicalDataString } from '../dataSource.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; describe('DropDown Tree control hierarchical datasource', () => { describe('Property testing', () => { let ddtreeObj: any; let mouseEventArgs: any; let tapEvent: any; let originalTimeout: any; let temp: number = 0; function templateClick(): void { document.getElementById('btn').addEventListener('click', function(){ temp++; }) } beforeEach((): void => { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; mouseEventArgs = { preventDefault: (): void => { }, stopImmediatePropagation: (): void => { }, target: null, type: null, shiftKey: false, ctrlKey: false, originalEvent: { target: null } }; tapEvent = { originalEvent: mouseEventArgs, tapCount: 1 }; temp = 0; let ele: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'ddtree' }); document.body.appendChild(ele); ddtreeObj = undefined }); afterEach((): void => { if (ddtreeObj) ddtreeObj.destroy(); document.body.innerHTML = ''; jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); /** * enableRtl property */ it('for enableRtl true', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, enableRtl: true }, '#ddtree'); var ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(ddtreeObj.element.parentElement.classList.contains('e-rtl')).toEqual(true); expect((ddtreeObj as any).popupObj.element.classList.contains('e-rtl')).toBe(true); expect((ddtreeObj as any).popupObj.enableRtl).toEqual(true); expect((ddtreeObj as any).treeObj.element.classList.contains('e-rtl')).toBe(true); expect((ddtreeObj as any).treeObj.enableRtl).toEqual(true); }); it('for enableRtl false', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, enableRtl: false }, '#ddtree'); var ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect((ddtreeObj as any).element.parentElement.classList.contains('e-rtl')).toEqual(false); expect((ddtreeObj as any).popupObj.element.classList.contains('e-rtl')).toBe(false); expect((ddtreeObj as any).popupObj.enableRtl).toEqual(false); expect((ddtreeObj as any).treeObj.element.classList.contains('e-rtl')).toBe(false); expect((ddtreeObj as any).treeObj.enableRtl).toEqual(false); }); /** * cssclass property */ it('for cssClass with popup', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, cssClass: 'custom-dropdowntree' }, '#ddtree'); var ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect((ddtreeObj as any).element.parentElement.classList.contains('custom-dropdowntree')).toBe(true); expect((ddtreeObj as any).popupObj.element.classList.contains('custom-dropdowntree')).toBe(true); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, cssClass: null }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).element.parentElement.classList.contains('custom-dropdowntree')).toBe(false); expect((ddtreeObj as any).popupObj.element.classList.contains('custom-dropdowntree')).toBe(false); expect((ddtreeObj as any).element.parentElement.classList.contains(null)).toBe(false); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, cssClass: undefined }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).element.parentElement.classList.contains('custom-dropdowntree')).toBe(false); expect((ddtreeObj as any).popupObj.element.classList.contains('custom-dropdowntree')).toBe(false); expect((ddtreeObj as any).element.parentElement.classList.contains(undefined)).toBe(false); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, cssClass: '' }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).element.parentElement.classList.contains('custom-dropdowntree')).toBe(false); expect((ddtreeObj as any).popupObj.element.classList.contains('custom-dropdowntree')).toBe(false); expect((ddtreeObj as any).element.parentElement.classList.contains('')).toBe(false); }); /** * enablePersistence property */ it('for enablePersistence', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, enablePersistence: true }, '#ddtree'); let persisData: any = JSON.parse(ddtreeObj.getPersistData()); ddtreeObj.showPopup(); let li: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('li'); mouseEventArgs.target = li[0].querySelector('.e-list-text'); ddtreeObj.treeObj.touchClickObj.tap(tapEvent); mouseEventArgs.target = li[0].querySelector('.e-icons'); ddtreeObj.treeObj.touchClickObj.tap(tapEvent); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { let seItems: any = JSON.parse(ddtreeObj.getPersistData()); expect(seItems.value.length).toBe(1); expect(seItems.value).toContain('1'); done(); }, 450); }); /** * enabled property */ it('for enabled false', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, enabled: false }, '#ddtree'); expect(ddtreeObj.element.parentElement.classList.contains('e-disabled')).toBe(true); expect(ddtreeObj.element.classList.contains('e-disabled')).toBe(true); expect(ddtreeObj.element.getAttribute('aria-disabled')).toBe('true'); expect(ddtreeObj.element.parentElement.getAttribute('aria-disabled')).toBe('true'); var ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(ddtreeObj.element.parentElement.getAttribute("aria-expanded")).toEqual("false"); ddtreeObj.showPopup(); expect(ddtreeObj.element.parentElement.getAttribute("aria-expanded")).toEqual("false"); }); /** * readonly property */ it('for readonly true', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, readonly: true }, '#ddtree'); var ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(ddtreeObj.element.parentElement.getAttribute("aria-expanded")).toEqual("false"); ddtreeObj.showPopup(); expect(ddtreeObj.element.parentElement.getAttribute("aria-expanded")).toEqual("false"); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, readonly: false }, '#ddtree'); ddtreeObj.showPopup(); expect(document.querySelectorAll('.e-popup').length).toBe(1); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); expect(ddtreeObj.element.parentElement.getAttribute("aria-expanded")).toEqual("true"); }); /** * Width */ it('for width', () => { // Width as em ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, width: "30em" }, '#ddtree'); expect(ddtreeObj.element.parentElement.style.width).toEqual('30em'); ddtreeObj.destroy(); // Width as % ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, width: "80%" }, '#ddtree'); expect(ddtreeObj.element.parentElement.style.width).toEqual('80%'); ddtreeObj.destroy(); // Width as px ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, width: "450px" }, '#ddtree'); expect(ddtreeObj.element.parentElement.style.width).toEqual('450px'); ddtreeObj.destroy(); // Width as number ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, width: 800 }, '#ddtree'); expect(ddtreeObj.element.parentElement.style.width).toEqual('800px'); ddtreeObj.destroy(); // Width as null ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, width: null }, '#ddtree'); expect(ddtreeObj.element.parentElement.style.width).toEqual(''); ddtreeObj.destroy() // Width as undefined ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, width: undefined }, '#ddtree'); expect(ddtreeObj.element.parentElement.style.width).toEqual('100%'); }); /** * popupWidth */ it('for popupWidth', () => { // popupWidth as px ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupWidth: "450px" }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.width).toEqual('450px'); ddtreeObj.destroy(); // popupWidth as number ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupWidth: 800 }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.width).toEqual('800px'); ddtreeObj.destroy(); // popupWidth as string ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupWidth: '800' }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.width).toEqual('800px'); ddtreeObj.destroy(); // popupWidth as null ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupWidth: null }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.width).toEqual(''); }); /** * popupHeight */ it('for popupHeight', () => { // popupHeight as em ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupHeight: "30em" }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.maxHeight).toEqual('30em'); ddtreeObj.destroy(); // popupHeight as px ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupHeight: "450px" }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.maxHeight).toEqual('450px'); ddtreeObj.destroy(); // popupHeight as number ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupHeight: 800 }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.maxHeight).toEqual('800px'); ddtreeObj.destroy(); // popupHeight as string ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupHeight: '800' }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.maxHeight).toEqual('800px'); ddtreeObj.destroy(); // popupHeight as null ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupHeight: null }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.maxHeight).toEqual(''); ddtreeObj.destroy() // popupHeight as undefined ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupHeight: undefined }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.maxHeight).toEqual('300px'); ddtreeObj.destroy() ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, popupHeight: '30%' }, '#ddtree'); ddtreeObj.showPopup(); }); /** * zIndex */ it('for zIndex', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, zIndex: 2000 }, '#ddtree'); ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.style.zIndex === '2000').toBe(true); }); /** * sort order property */ it('for sortOrder - Ascending', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData1, value: "nodeId", text: "nodeText", child: "nodeChild", iconCss: 'nodeIcon', imageUrl: 'nodeImage', tooltip: 'nodeTooltip', htmlAttributes: 'nodeHtmlAttr', selected: 'nodeSelected' }, sortOrder: 'Ascending' }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); expect(ddtreeObj.treeObj.element.querySelector('.e-list-text').innerHTML).toBe('Documents'); expect(ddtreeObj.treeObj.element.querySelector('.e-list-item').getAttribute('data-uid')).toBe('03'); done(); }, 100); }); it('for sortOrder - Descending', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData1, value: "nodeId", text: "nodeText", child: "nodeChild", iconCss: 'nodeIcon', imageUrl: 'nodeImage', tooltip: 'nodeTooltip', htmlAttributes: 'nodeHtmlAttr', selected: 'nodeSelected' }, sortOrder: 'Descending' }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); expect(ddtreeObj.treeObj.element.querySelector('.e-list-text').innerHTML).toBe('Videos'); expect(ddtreeObj.treeObj.element.querySelector('.e-list-item').getAttribute('data-uid')).toBe('02'); done(); }, 100); }); /** * placeholder */ it('for placeholder', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, placeholder: 'Select a Country' }, '#ddtree'); expect(ddtreeObj.element.getAttribute('placeholder')).toEqual('Select a Country'); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, placeholder: '' }, '#ddtree'); expect(ddtreeObj.element.getAttribute('placeholder')).toEqual(null); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, placeholder: null }, '#ddtree'); expect(ddtreeObj.element.getAttribute('placeholder')).toEqual(null); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, placeholder: undefined }, '#ddtree'); expect(ddtreeObj.element.getAttribute('placeholder')).toEqual(null); }); /** * FloatLabelType property */ it('for floatLabelType - Auto', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, floatLabelType: 'Auto', placeholder: 'Select a Country' }, '#ddtree'); mouseEventArgs.target = document.body; let floatElement = (ddtreeObj as any).inputWrapper.querySelector('.e-float-text') var ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(floatElement.classList.contains('e-label-bottom')).toBe(true); }); it('for floatLabelType - Always', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, floatLabelType: 'Always', placeholder: 'Select a Country' }, '#ddtree'); mouseEventArgs.target = document.body; let floatElement = (ddtreeObj as any).inputWrapper.querySelector('.e-float-text') var ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(floatElement.classList.contains('e-label-top')).toBe(true); }); /** * expandOn */ it('for expandOn- None', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { expandOn: 'None' } }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); let li: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('li'); tapEvent.tapCount = 1; mouseEventArgs.target = li[5].querySelector('.e-list-text'); ddtreeObj.treeObj.touchClickObj.tap(tapEvent); tapEvent.tapCount = 2; mouseEventArgs.target = li[5].querySelector('.e-list-text'); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-expandable')).toBe(true); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-collapsible')).toBe(false); expect(li[5].childElementCount).toBe(3); expect(li[5].querySelector('.e-list-text').childElementCount).toBe(0); ddtreeObj.showPopup(); ddtreeObj.treeObj.touchClickObj.tap(tapEvent); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { expect(li[5].querySelector('.e-icons').classList.contains('e-icon-expandable')).toBe(true); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-collapsible')).toBe(false); done(); }, 450); }, 100); }); it('for expandOn - Click', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { expandOn: 'Click' } }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); let li: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('li'); mouseEventArgs.target = li[5].querySelector('.e-list-text'); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-expandable')).toBe(true); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-collapsible')).toBe(false); expect(li[5].childElementCount).toBe(3); expect(li[5].querySelector('.e-list-text').childElementCount).toBe(0); ddtreeObj.showPopup(); ddtreeObj.treeObj.touchExpandObj.tap(tapEvent); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { expect(li[5].querySelector('.e-icons').classList.contains('e-icon-expandable')).toBe(false); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-collapsible')).toBe(true); done(); }, 450); }, 100); }); it('for expandOn - DblClick', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { expandOn: 'DblClick' } }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); let li: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('li'); mouseEventArgs.target = li[5].querySelector('.e-list-text'); tapEvent.tapCount = 1; ddtreeObj.treeObj.touchExpandObj.tap(tapEvent); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-expandable')).toBe(true); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-collapsible')).toBe(false); expect(li[5].childElementCount).toBe(3); expect(li[5].querySelector('.e-list-text').childElementCount).toBe(0); ddtreeObj.showPopup(); tapEvent.tapCount = 2; ddtreeObj.treeObj.touchExpandObj.tap(tapEvent); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { expect(li[5].querySelector('.e-icons').classList.contains('e-icon-expandable')).toBe(false); expect(li[5].querySelector('.e-icons').classList.contains('e-icon-collapsible')).toBe(true); done(); }, 450); }, 100); }); /** * showDropDownIcon */ it('for ShowDropDownIcon', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showDropDownIcon: false }, '#ddtree'); expect((ddtreeObj as any).element.parentElement.lastElementChild.classList.contains('e-ddt-icon')).toBe(false); expect(ddtreeObj.element.parentElement.lastElementChild.classList.contains('e-clear-icon')).toBe(true); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showDropDownIcon: true }, '#ddtree'); expect((ddtreeObj as any).element.parentElement.lastElementChild.classList.contains('e-ddt-icon')).toBe(true); expect(ddtreeObj.element.parentElement.lastElementChild.classList.contains('e-clear-icon')).toBe(false); }); /** * showClearButton */ it('for showClearButton', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showClearButton: false }, '#ddtree'); expect((ddtreeObj).element.nextElementSibling.classList.contains('e-clear-icon')).toBe(false); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showClearButton: true }, '#ddtree'); expect((ddtreeObj as any).element.nextElementSibling.classList.contains('e-clear-icon')).toBe(true); expect((ddtreeObj).element.nextElementSibling.classList.contains('e-icon-hide')).toBe(true); var ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var li = (ddtreeObj as any).treeObj.element.querySelectorAll('li'); mouseEventArgs.target = li[0].querySelector('.e-list-text'); tapEvent.tapCount = 1; (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect((ddtreeObj).element.nextElementSibling.classList.contains('e-icon-hide')).toBe(false); let ele1: HTMLElement = (ddtreeObj as any).element.nextElementSibling; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele1.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele1.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele1.dispatchEvent(e); expect((ddtreeObj as any).element.value).toBe(""); expect((ddtreeObj).element.nextElementSibling.classList.contains('e-icon-hide')).toBe(true); }); /** * fields */ it('with null fields', () => { ddtreeObj = new DropDownTree({ fields: null }, '#ddtree'); expect(ddtreeObj.treeObj.element.querySelectorAll('li').length).toBe(0); }); it('with empty fields', () => { ddtreeObj = new DropDownTree({ fields: {} }, '#ddtree'); expect(ddtreeObj.element.querySelectorAll('li').length).toBe(0); }); it('with null datasource', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: null } }, '#ddtree'); expect(ddtreeObj.element.querySelectorAll('li').length).toBe(0); }); it('with empty datasource', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: [] } }, '#ddtree'); expect(ddtreeObj.element.querySelectorAll('li').length).toBe(0); }); it('without mapping fields', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData }, treeSettings: { loadOnDemand: true } }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(ddtreeObj.treeObj.element.querySelectorAll('li').length).toBe(10); expect(ddtreeObj.treeObj.element.querySelector('.e-list-text').innerHTML).toBe('Artwork'); expect(ddtreeObj.treeObj.element.querySelector('.e-list-item').getAttribute('data-uid')).toBe("1"); expect(ddtreeObj.treeObj.element.querySelector('.e-list-icon').classList.contains('folder')).toBe(true); expect(ddtreeObj.treeObj.element.querySelector('.e-list-img').src.indexOf('images/Shooting.png')).not.toBe(-1); expect(ddtreeObj.treeObj.element.querySelector('.e-list-item').title).toBe('This is Artwork node'); expect(ddtreeObj.treeObj.element.querySelector('.e-list-item').classList.contains('e-active')).toBe(true); expect(ddtreeObj.treeObj.element.querySelectorAll('li')[1].classList.contains('firstnode')).toBe(true); expect(ddtreeObj.treeObj.element.querySelectorAll('li')[1].style.backgroundColor).toBe('red'); let newli: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('li'); expect(newli[2].childElementCount).toBe(3); expect((newli[2].querySelector('.e-icons') as Element).classList.contains('e-icon-expandable')).toBe(false); expect((newli[2].querySelector('.e-icons') as Element).classList.contains('e-icon-collapsible')).toBe(true); expect(newli[2].getAttribute('aria-expanded')).toBe('true'); expect(newli[3].childElementCount).toBe(3); expect((newli[3].querySelector('.e-icons') as Element).classList.contains('e-icon-expandable')).toBe(false); expect((newli[3].querySelector('.e-icons') as Element).classList.contains('e-icon-collapsible')).toBe(true); expect(newli[3].getAttribute('aria-expanded')).toBe('true'); }); it('without child mapping', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalDataString, value: "id", text: "name", child: null }, treeSettings: { loadOnDemand: true } }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(ddtreeObj.treeObj.element.querySelectorAll('li').length).toBe(3); }); it('with mapping fields and value as string', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalDataString, value: "id", text: "name", child: "subChild" }, treeSettings: { loadOnDemand: true } }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(ddtreeObj.treeObj.element.querySelectorAll('li').length).toBe(9); }); /** * allowMultiSelection property */ it('for allowMultiSelection with selected attribute provided in datasource', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child", selected: 'isSelected' }, allowMultiSelection: true }, '#ddtree'); expect(ddtreeObj.text).toBe('New South Wales,Ceará'); expect(ddtreeObj.value.length).toBe(2) }); it('for allowMultiSelection', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, allowMultiSelection: true, mode: 'Default', treeSettings: { loadOnDemand: true } }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let li: Element[] = <Element[] & NodeListOf<Element>>(ddtreeObj as any).treeObj.element.querySelectorAll('li'); // ctrl key pressed mouseEventArgs.ctrlKey = true; mouseEventArgs.target = li[0].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(li[0].classList.contains('e-active')).toBe(true); expect(ddtreeObj.text).toBe('Australia'); let chipElement = ddtreeObj.element.parentElement.firstElementChild; expect(chipElement.classList.contains('e-chips-wrapper')).toBe(true); let chips = chipElement.querySelectorAll('.e-chips'); expect(chips.length).toBe(1); expect(chips[0].getAttribute("data-value")).toBe("1"); expect(chips[0].querySelector(".e-chipcontent").textContent).toBe("Australia"); expect(ddtreeObj.value[0]).toBe('1'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); (ddtreeObj as any).onFocusOut(); expect(chipElement.classList.contains('e-icon-hide')).toBe(true); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); ddtreeObj.showPopup(); mouseEventArgs.ctrlKey = true; mouseEventArgs.target = li[2].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(li[2].classList.contains('e-active')).toBe(true); expect(ddtreeObj.text).toBe('Australia,Victoria'); let chips_1 = chipElement.querySelectorAll('.e-chips'); expect(chips_1.length).toBe(2); expect(chips_1[1].getAttribute("data-value")).toBe("3"); expect(chips_1[0].querySelector(".e-chipcontent").textContent).toBe("Australia"); expect(chips_1[1].querySelector(".e-chipcontent").textContent).toBe("Victoria"); expect(ddtreeObj.value.length).toBe(2); expect(ddtreeObj.value[1]).toBe('3'); (ddtreeObj as any).onFocusOut(); expect(chipElement.classList.contains('e-icon-hide')).toBe(true); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); ddtreeObj.showPopup(); expect(chipElement.classList.contains('e-icon-hide')).toBe(false); // checking shift key mouseEventArgs.ctrlKey = false; mouseEventArgs.shiftKey = true; mouseEventArgs.target = li[5].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(ddtreeObj.text).toBe('Victoria,South Australia,Western Australia,Brazil'); expect(ddtreeObj.value.length).toBe(4); expect(ddtreeObj.value[3]).toBe('7'); let chips_2 = chipElement.querySelectorAll('.e-chips'); expect(chips_2.length).toBe(4); expect(chips_2[0].querySelector(".e-chipcontent").textContent).toBe("Victoria"); expect(chips_2[1].querySelector(".e-chipcontent").textContent).toBe("South Australia"); expect(chips_2[2].querySelector(".e-chipcontent").textContent).toBe("Western Australia"); expect(chips_2[3].querySelector(".e-chipcontent").textContent).toBe("Brazil"); (ddtreeObj as any).onFocusOut(); expect(chipElement.classList.contains('e-icon-hide')).toBe(true); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); }); /** * mode */ it('for Delimiter mode with allowMultiSelection', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: true }, allowMultiSelection: true, mode: 'Delimiter' }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let li: Element[] = <Element[] & NodeListOf<Element>>(ddtreeObj as any).treeObj.element.querySelectorAll('li'); // ctrl key pressed mouseEventArgs.ctrlKey = true; mouseEventArgs.target = li[0].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(li[0].classList.contains('e-active')).toBe(true); expect(ddtreeObj.text).toBe('Australia'); expect(ddtreeObj.value[0]).toBe('1'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); mouseEventArgs.ctrlKey = true; mouseEventArgs.target = li[2].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(li[2].classList.contains('e-active')).toBe(true); expect(ddtreeObj.text).toBe('Australia,Victoria'); expect(ddtreeObj.value.length).toBe(2); expect(ddtreeObj.value[1]).toBe('3'); expect(ddtreeObj.element.previousElementSibling.firstElementChild.getAttribute('value')).toBe('1'); expect(ddtreeObj.element.previousElementSibling.firstElementChild.nextElementSibling.getAttribute('value')).toBe('3'); // checking shift key mouseEventArgs.ctrlKey = false; mouseEventArgs.shiftKey = true; mouseEventArgs.target = li[5].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(ddtreeObj.text).toBe('Victoria,South Australia,Western Australia,Brazil'); expect(ddtreeObj.value.length).toBe(4); expect(ddtreeObj.value[3]).toBe('7'); let ele1 = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele1.dispatchEvent(e); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); }); it('for Box mode with allowMultiSelection', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: true }, allowMultiSelection: true, mode: 'Box' }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let li: Element[] = <Element[] & NodeListOf<Element>>(ddtreeObj as any).treeObj.element.querySelectorAll('li'); // ctrl key pressed mouseEventArgs.ctrlKey = true; mouseEventArgs.target = li[0].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(li[0].classList.contains('e-active')).toBe(true); expect(ddtreeObj.text).toBe('Australia'); let chipElement = ddtreeObj.element.parentElement.firstElementChild; expect(chipElement.classList.contains('e-chips-wrapper')).toBe(true); let chips = chipElement.querySelectorAll('.e-chips'); expect(chips.length).toBe(1); expect(chips[0].getAttribute("data-value")).toBe("1"); expect(chips[0].querySelector(".e-chipcontent").textContent).toBe("Australia"); expect(ddtreeObj.value[0]).toBe('1'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); mouseEventArgs.ctrlKey = true; mouseEventArgs.target = li[2].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(li[2].classList.contains('e-active')).toBe(true); expect(ddtreeObj.text).toBe('Australia,Victoria'); let chips_1 = chipElement.querySelectorAll('.e-chips'); expect(chips_1.length).toBe(2); expect(chips_1[1].getAttribute("data-value")).toBe("3"); expect(chips_1[0].querySelector(".e-chipcontent").textContent).toBe("Australia"); expect(chips_1[1].querySelector(".e-chipcontent").textContent).toBe("Victoria"); expect(ddtreeObj.value.length).toBe(2); expect(ddtreeObj.value[1]).toBe('3'); // checking shift key mouseEventArgs.ctrlKey = false; mouseEventArgs.shiftKey = true; mouseEventArgs.target = li[5].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(ddtreeObj.text).toBe('Victoria,South Australia,Western Australia,Brazil'); expect(ddtreeObj.value.length).toBe(4); expect(ddtreeObj.value[3]).toBe('7'); let chips_2 = chipElement.querySelectorAll('.e-chips'); expect(chips_2.length).toBe(4); expect(chips_2[0].querySelector(".e-chipcontent").textContent).toBe("Victoria"); expect(chips_2[1].querySelector(".e-chipcontent").textContent).toBe("South Australia"); expect(chips_2[2].querySelector(".e-chipcontent").textContent).toBe("Western Australia"); expect(chips_2[3].querySelector(".e-chipcontent").textContent).toBe("Brazil"); let ele1 = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele1.dispatchEvent(e); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); }); /** * Delimiter char */ it('for delimiterChar', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: true }, allowMultiSelection: true, mode: 'Delimiter', delimiterChar: '*' }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let li: Element[] = <Element[] & NodeListOf<Element>>(ddtreeObj as any).treeObj.element.querySelectorAll('li'); // ctrl key pressed mouseEventArgs.ctrlKey = true; mouseEventArgs.target = li[0].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(li[0].classList.contains('e-active')).toBe(true); expect(ddtreeObj.text).toBe('Australia'); expect(ddtreeObj.value[0]).toBe('1'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); mouseEventArgs.ctrlKey = true; mouseEventArgs.target = li[2].querySelector('.e-list-text'); (ddtreeObj as any).treeObj.touchClickObj.tap(tapEvent); expect(li[2].classList.contains('e-active')).toBe(true); expect(ddtreeObj.text).toBe('Australia,Victoria'); expect(ddtreeObj.element.value).toBe('Australia* Victoria'); expect(ddtreeObj.value.length).toBe(2); expect(ddtreeObj.value[1]).toBe('3'); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: true }, delimiterChar: ':', allowMultiSelection: true, mode: 'Delimiter', value: ['1', '3'] }, '#ddtree'); expect(ddtreeObj.text).toBe('Australia,Victoria'); expect(ddtreeObj.element.value).toBe('Australia: Victoria'); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: true }, delimiterChar: ';', allowMultiSelection: true, mode: 'Delimiter', value: ['1', '3'] }, '#ddtree'); expect(ddtreeObj.text).toBe('Australia,Victoria'); expect(ddtreeObj.element.value).toBe('Australia; Victoria'); }); /** * showCheckBox enabled */ it('for showCheckBox with single selected value provided in dataSource', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData }, treeSettings: { loadOnDemand: true }, showCheckBox: true }, '#ddtree'); expect(ddtreeObj.value.length).toBe(1); expect(ddtreeObj.text).toBe('Artwork'); }); it('for showCheckBox with multiple selected attribute provided in datasource', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child", selected: 'isSelected' }, showCheckBox: true }, '#ddtree'); expect(ddtreeObj.text).toBe('New South Wales,Ceará'); expect(ddtreeObj.value.length).toBe(2) }); it('for showCheckBox with Default mode', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showCheckBox: true }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let checkEle: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); expect(checkEle[0].getAttribute('aria-checked')).toBe('true'); expect(ddtreeObj.value[0]).toBe('1'); let chipElement = ddtreeObj.element.parentElement.firstElementChild; expect(chipElement.classList.contains('e-chips-wrapper')).toBe(true); let chips = chipElement.querySelectorAll('.e-chips'); expect(chips.length).toBe(1); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); (ddtreeObj as any).onFocusOut(); expect(ddtreeObj.text).toBe('Australia'); expect(chipElement.classList.contains('e-icon-hide')).toBe(true); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); ddtreeObj.showPopup(); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.value[1]).toBe('2'); let chips_1 = chipElement.querySelectorAll('.e-chips'); expect(chips_1.length).toBe(2); (ddtreeObj as any).onFocusOut(); expect(ddtreeObj.text).toBe('Australia,New South Wales'); expect(chipElement.classList.contains('e-icon-hide')).toBe(true); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); ddtreeObj.showPopup(); expect(chipElement.classList.contains('e-icon-hide')).toBe(false); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia,New South Wales,Brazil'); expect(ddtreeObj.value[2]).toBe('7'); let chips_2 = chipElement.querySelectorAll('.e-chips'); expect(chips_2.length).toBe(3); let ele1 = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele1.dispatchEvent(e); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); ddtreeObj.onFocusOut(); }); /** * mode */ it('for Delimiter mode with showCheckBox', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showCheckBox: true, mode: 'Delimiter' }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let checkEle: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); expect(checkEle[0].getAttribute('aria-checked')).toBe('true'); expect(ddtreeObj.text).toBe('Australia'); expect(ddtreeObj.value[0]).toBe('1'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia,New South Wales'); expect(ddtreeObj.value[1]).toBe('2'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia,New South Wales,Brazil'); expect(ddtreeObj.value[2]).toBe('7'); let ele1 = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele1.dispatchEvent(e); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); ddtreeObj.onFocusOut(); }); it('for Box mode with showCheckBox', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showCheckBox: true, mode: 'Box' }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let checkEle: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); expect(checkEle[0].getAttribute('aria-checked')).toBe('true'); expect(ddtreeObj.text).toBe('Australia'); expect(ddtreeObj.value[0]).toBe('1'); let chipElement = ddtreeObj.element.parentElement.firstElementChild; expect(chipElement.classList.contains('e-chips-wrapper')).toBe(true); let chips = chipElement.querySelectorAll('.e-chips'); expect(chips.length).toBe(1); expect(chips[0].getAttribute("data-value")).toBe("1"); expect(chips[0].querySelector(".e-chipcontent").textContent).toBe("Australia"); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[1].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia,New South Wales'); expect(ddtreeObj.value[1]).toBe('2'); let nchips = chipElement.querySelectorAll('.e-chips'); expect(nchips.length).toBe(2); expect(nchips[1].getAttribute("data-value")).toBe("2"); expect(nchips[1].querySelector(".e-chipcontent").textContent).toBe("New South Wales"); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia,New South Wales,Brazil'); let chips_1 = chipElement.querySelectorAll('.e-chips'); expect(chips_1.length).toBe(3); expect(chips_1[0].querySelector(".e-chipcontent").textContent).toBe("Australia"); expect(chips_1[1].querySelector(".e-chipcontent").textContent).toBe("New South Wales"); expect(chips_1[2].querySelector(".e-chipcontent").textContent).toBe("Brazil"); expect(ddtreeObj.value[2]).toBe('7'); let ele1 = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele1.dispatchEvent(e); expect(document.querySelector('.e-popup').classList.contains('e-popup-close')).toBe(true); ddtreeObj.onFocusOut(); }); /** * Delimiter char */ it('for Delimiter char with showCheckBox', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: true }, showCheckBox: true, mode: 'Delimiter' }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let checkEle: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia'); expect(ddtreeObj.value[0]).toBe('1'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[2].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[2].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[2].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia,Victoria'); expect(ddtreeObj.value.length).toBe(2); expect(ddtreeObj.value[1]).toBe('3'); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: true }, showCheckBox: true, mode: 'Delimiter', delimiterChar: ':', value: ['1', '3'] }, '#ddtree'); expect(ddtreeObj.text).toBe('Australia,Victoria'); expect(ddtreeObj.element.value).toBe('Australia: Victoria'); }); /** * showSelectAll testing */ it('for ShowSelectAll', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showSelectAll: true, showCheckBox: true, mode: 'Delimiter' }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var selectAllElement = ddtreeObj.popupEle.firstElementChild; expect(selectAllElement.classList.contains('e-selectall-parent')).toBe(true); expect(selectAllElement.querySelector('.e-all-text').textContent).toBe('Select All'); let checkEle: Element = <Element & NodeListOf<Element>>selectAllElement.querySelector('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle.querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle.querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle.querySelector('.e-frame').dispatchEvent(e); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { expect(ddtreeObj.value.length).toBe(24); expect(selectAllElement.querySelector('.e-all-text').textContent).toBe('Unselect All'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); let ncheckEle: Element = <Element & NodeListOf<Element>>selectAllElement.querySelector('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ncheckEle.querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ncheckEle.querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ncheckEle.querySelector('.e-frame').dispatchEvent(e); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { expect(ddtreeObj.value.length).toBe(0); expect(selectAllElement.querySelector('.e-all-text').textContent).toBe('Select All'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); done(); }, 400); }, 400); }); /** * selectAllText and unSelectAllText */ it('for selectAllText and unSelectAllText', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showSelectAll: true, showCheckBox: true, mode: 'Delimiter', selectAllText: 'check All Nodes', unSelectAllText: 'unCheck All Nodes' }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var selectAllElement = ddtreeObj.popupEle.firstElementChild; expect(selectAllElement.classList.contains('e-selectall-parent')).toBe(true); expect(selectAllElement.querySelector('.e-all-text').textContent).toBe('check All Nodes'); let checkEle: Element = <Element & NodeListOf<Element>>selectAllElement.querySelector('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle.querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle.querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle.querySelector('.e-frame').dispatchEvent(e); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { expect(ddtreeObj.value.length).toBe(24); expect(selectAllElement.querySelector('.e-all-text').textContent).toBe('unCheck All Nodes'); let ncheckEle: Element = <Element & NodeListOf<Element>>selectAllElement.querySelector('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ncheckEle.querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ncheckEle.querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ncheckEle.querySelector('.e-frame').dispatchEvent(e); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { expect(ddtreeObj.value.length).toBe(0); expect(selectAllElement.querySelector('.e-all-text').textContent).toBe('check All Nodes'); done(); }, 400); }, 400); }); /** * autoCheck */ it('for autocheck', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showCheckBox: true, mode: 'Delimiter', treeSettings: { autoCheck: true } }, '#ddtree'); let ele = ddtreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); let checkEle: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[0].querySelector('.e-frame').dispatchEvent(e); expect(checkEle[0].getAttribute('aria-checked')).toBe('true'); expect(ddtreeObj.text).toBe('Australia,New South Wales,Victoria,South Australia,Western Australia'); expect(ddtreeObj.value.length).toBe(5); expect(ddtreeObj.value[2]).toBe('3'); expect(document.querySelector('.e-popup').classList.contains('e-popup-open')).toBe(true); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle[5].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia,New South Wales,Victoria,South Australia,Western Australia,Brazil,Paraná,Ceará,Acre'); expect(ddtreeObj.value.length).toBe(9); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, showCheckBox: true, mode: 'Delimiter', treeSettings: { autoCheck: false } }, '#ddtree'); ddtreeObj.showPopup(); let checkEle1: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('.e-checkbox-wrapper'); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle1[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle1[0].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle1[0].querySelector('.e-frame').dispatchEvent(e); expect(checkEle1[0].getAttribute('aria-checked')).toBe('true'); expect(ddtreeObj.text).toBe('Australia'); expect(ddtreeObj.value.length).toBe(1); var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); checkEle1[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); checkEle1[5].querySelector('.e-frame').dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); checkEle1[5].querySelector('.e-frame').dispatchEvent(e); expect(ddtreeObj.text).toBe('Australia,Brazil'); expect(ddtreeObj.value.length).toBe(2); }); /** * headerTemplate */ it('for headerTemplate support with string', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, headerTemplate: '<div class="new headerString"><span>HEADER VIA STRING</span></div>' }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); expect(ddtreeObj.headerTemplate).not.toBe(null); expect(ddtreeObj.popupObj.element.firstChild.classList.contains('e-ddt-header')).toBe(true); expect(ddtreeObj.popupObj.element.firstChild.innerText).toEqual("HEADER VIA STRING"); ddtreeObj.hidePopup(); done(); }, 400); }); it('for headerTemplate support with script', (done: Function) => { let headerTemplate: Element = createElement('div', { id: 'headerTemplate' }); headerTemplate.innerHTML = '<div class="header"><span >HEADER Via SCRIPT</span></div>'; document.body.appendChild(headerTemplate); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, headerTemplate: '#headerTemplate' }, '#ddtree'); setTimeout(function () { ddtreeObj.showPopup(); expect(ddtreeObj.headerTemplate).not.toBe(null); expect(ddtreeObj.popupObj.element.firstChild.classList.contains('e-ddt-header')).toBe(true); expect(ddtreeObj.popupObj.element.firstChild.innerText).toEqual("HEADER Via SCRIPT"); ddtreeObj.hidePopup(); done(); }, 400); }); it('button click in headerTemplate', function (done: Function) { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, headerTemplate: '<div class="head"> Photo' + '<button type="button" id="btn">' + 'Click here' + '</button>' + '<span> Contact Info </span></div>', open: templateClick }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); expect(ddtreeObj.headerTemplate).not.toBe(null); expect(temp).toBe(0); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ddtreeObj.popupObj.element.firstChild.querySelector('#btn').dispatchEvent(e); expect(temp).toBe(1); ddtreeObj.hidePopup(); done(); }, 400); }); /** * footerTemplate */ it('for footerTemplate support with string', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, footerTemplate: '<div class="new headerString"><span>FOOTER VIA STRING</span></div>' }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); expect(ddtreeObj.footerTemplate).not.toBe(null); expect(ddtreeObj.popupObj.element.lastElementChild.classList.contains('e-ddt-footer')).toBe(true); expect(ddtreeObj.popupObj.element.lastElementChild.innerText).toEqual("FOOTER VIA STRING"); ddtreeObj.hidePopup(); done(); }, 400); }); it('for footerTemplate support with script', (done: Function) => { let footerTemplate: Element = createElement('div', { id: 'footerTemplate' }); footerTemplate.innerHTML = '<div class="header"><span >FOOTER Via SCRIPT</span></div>'; document.body.appendChild(footerTemplate); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, footerTemplate: '#footerTemplate' }, '#ddtree'); setTimeout(function () { ddtreeObj.showPopup(); expect(ddtreeObj.footerTemplate).not.toBe(null); expect(ddtreeObj.popupObj.element.lastElementChild.classList.contains('e-ddt-footer')).toBe(true); expect(ddtreeObj.popupObj.element.lastElementChild.innerText).toEqual("FOOTER Via SCRIPT"); ddtreeObj.hidePopup(); done(); }, 400); }); it('button click in footerTemplate', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, footerTemplate: '<div class="head"> Photo' + '<button type="button" id="btn">' + 'Click here' + '</button>' + '<span> Contact Info </span></div>', open: templateClick }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); expect(ddtreeObj.footerTemplate).not.toBe(null); expect(ddtreeObj.popupObj.element.lastElementChild.classList.contains('e-ddt-footer')).toBe(true); expect(temp).toBe(0); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ddtreeObj.popupObj.element.lastElementChild.querySelector('#btn').dispatchEvent(e); expect(temp).toBe(1); ddtreeObj.hidePopup(); done(); }, 400); }); /** * itemTemplate */ it('for itemTemplate support with string', (done: Function) => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData1, value: "nodeId", text: "nodeText", child: "nodeChild", expanded: 'nodeExpanded1' }, itemTemplate: '${if(nodeChild == undefined)}<b>${nodeText}</b>${else}<i>${nodeText}</i>${/if}' }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); let li: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('.e-text-content'); expect(li[0].querySelector('i')).not.toBe(null); expect(li[0].querySelector('b')).toBe(null); expect(li[1].querySelector('b')).not.toBe(null); expect(li[1].querySelector('i')).toBe(null); ddtreeObj.hidePopup(); done(); }, 450); }); it('for itemTemplate support with script', (done: Function) => { let template: Element = createElement('div', { id: 'template' }); template.innerHTML = '${if(nodeChild == undefined)}<b>${nodeText}</b>${else}<i>${nodeText}</i>${/if}'; document.body.appendChild(template); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData1, value: "nodeId", text: "nodeText", child: "nodeChild", expanded: 'nodeExpanded1' }, itemTemplate: '#template' }, '#ddtree'); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { ddtreeObj.showPopup(); let li: Element[] = <Element[] & NodeListOf<Element>>ddtreeObj.treeObj.element.querySelectorAll('.e-text-content'); expect(li[0].querySelector('i')).not.toBe(null); expect(li[0].querySelector('b')).toBe(null); expect(li[1].querySelector('b')).not.toBe(null); expect(li[1].querySelector('i')).toBe(null); ddtreeObj.hidePopup(); done(); }, 450); }); /** * loadOnDemand true */ it('for loadOnDemand', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: true } }, '#ddtree'); var li = (ddtreeObj as any).treeObj.element.querySelectorAll('li'); expect(li.length).toBe(9); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, treeSettings: { loadOnDemand: false } }, '#ddtree'); var li = (ddtreeObj as any).treeObj.element.querySelectorAll('li'); expect(li.length).toBe(24); }); /* *value */ it('for value as string type', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalDataString, value: "id", text: "name", child: "subChild" }, treeSettings: { loadOnDemand: true }, value: ['01'] }, '#ddtree'); expect(ddtreeObj.treeObj.element.querySelectorAll('li').length).toBe(9); expect(ddtreeObj.value.length).toBe(1); expect(ddtreeObj.text).toBe('Local Disk (C:)'); ddtreeObj.showPopup(); ddtreeObj.value = ['02-01']; ddtreeObj.dataBind(); expect(ddtreeObj.value.length).toBe(1); expect(ddtreeObj.text).not.toBe('Local Disk (C:)'); expect(ddtreeObj.text).toBe('Personals'); ddtreeObj.value = ['444']; ddtreeObj.dataBind(); expect(ddtreeObj.value[0]).not.toBe('444') expect(ddtreeObj.text).toBe('Personals'); ddtreeObj.value = null; ddtreeObj.dataBind(); expect(ddtreeObj.value).toBe(null); expect(ddtreeObj.text).toBe(null); }); /** * text */ it('for text', () => { ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, text: 'Australia', treeSettings: { loadOnDemand: true } }, '#ddtree'); expect(ddtreeObj.treeObj.element.querySelectorAll('li').length).toBe(9); expect(ddtreeObj.text).toBe('Australia'); expect(ddtreeObj.value.length).toBe(1); expect(ddtreeObj.value[0]).toBe('1'); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, text: 'India', treeSettings: { loadOnDemand: true } }, '#ddtree'); expect(ddtreeObj.text).toBe('India'); expect(ddtreeObj.value.length).toBe(1); expect(ddtreeObj.value[0]).toBe('21'); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, text: 'aaaaa', treeSettings: { loadOnDemand: true } }, '#ddtree'); expect(ddtreeObj.value).toBe(null); expect(ddtreeObj.text).toBe(null); ddtreeObj.destroy(); ddtreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, text: null, treeSettings: { loadOnDemand: true } }, '#ddtree'); expect(ddtreeObj.value).toBe(null); expect(ddtreeObj.text).toBe(null); }); }); describe('htmlAttributes testing', () => { let ddTreeObj: any; let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdowntree' }); element.setAttribute('data-required', 'name'); let mouseEventArgs: any = { preventDefault: function () { }, target: null }; beforeAll(() => { document.body.appendChild(element); ddTreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, htmlAttributes: { 'data-msg-container-id': 'msgid' } }); ddTreeObj.appendTo(element); }); afterAll(() => { if (element) { element.remove(); document.body.innerHTML = ''; } }); it('functionaliy testing', () => { expect(ddTreeObj.hiddenElement.getAttribute('data-msg-container-id')).not.toBeNull(); expect(ddTreeObj.hiddenElement.getAttribute('data-required')).toBe('name'); expect(ddTreeObj.htmlAttributes['data-required']).toBe('name'); ddTreeObj.destroy(); ddTreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, htmlAttributes: { 'class': 'myTree' } }); ddTreeObj.appendTo(element); expect(ddTreeObj.element.parentElement.classList.contains('myTree')).toBe(true); ddTreeObj.destroy(); ddTreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, htmlAttributes: { readonly: 'readonly' } }); ddTreeObj.appendTo(element); var ele = ddTreeObj.element; var e = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); var e = new MouseEvent("click", { view: window, bubbles: true, cancelable: true }); ele.dispatchEvent(e); expect(ddTreeObj.element.parentElement.getAttribute("aria-expanded")).toEqual("false"); ddTreeObj.showPopup(); expect(ddTreeObj.element.parentElement.getAttribute("aria-expanded")).toEqual("false"); ddTreeObj.destroy(); ddTreeObj = new DropDownTree({ fields: { dataSource: hierarchicalData3, value: "id", text: "name", expanded: 'expanded', child: "child" }, htmlAttributes: { style: 'background: red' } }); ddTreeObj.appendTo(element); expect(ddTreeObj.element.parentElement.style.background).toBe('red'); }); }); describe('noRecordTemplate testing', () => { let ddtreeObj: DropDownTree; let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdowntree' }); let mouseEventArgs: any = { preventDefault: function () { }, target: null }; beforeAll(() => { setCulture('en-US') document.body.appendChild(element); ddtreeObj = new DropDownTree({ fields: { dataSource: [], value: 'id', parentValue: 'pid', hasChildren: 'hasChild', text: 'name' } }); ddtreeObj.appendTo(element); }); afterAll(() => { if (element) { element.remove(); document.body.innerHTML = ''; } }); it('with default value', () => { ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.firstElementChild.classList.contains('e-no-data')).toBe(true); expect((ddtreeObj as any).popupObj.element.firstElementChild.innerText).toBe('No Records Found'); }); }); describe('noRecordTemplate testing', () => { let ddtreeObj: DropDownTree; let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdowntree' }); let mouseEventArgs: any = { preventDefault: function () { }, target: null }; beforeAll(() => { setCulture('en-US') document.body.appendChild(element); ddtreeObj = new DropDownTree({ fields: { dataSource: [], value: 'id', parentValue: 'pid', hasChildren: 'hasChild', text: 'name' }, noRecordsTemplate: '<div> There is no records to rendering the list items</div>' }); ddtreeObj.appendTo(element); }); afterAll(() => { if (element) { element.remove(); document.body.innerHTML = ''; } }); it('with custom value', () => { ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.firstElementChild.classList.contains('e-no-data')).toBe(true); expect((ddtreeObj as any).popupObj.element.firstElementChild.innerText).toBe('There is no records to rendering the list items'); }); }); describe('Performance testing', () => { let ddtreeObj1: DropDownTree; let mouseEventArgs: any; let originalTimeout: any; let tapEvent: any; beforeEach((): void => { mouseEventArgs = { preventDefault: (): void => {}, stopImmediatePropagation: (): void => {}, target: null, type: null, shiftKey: false, ctrlKey: false, originalEvent:{ target: null} }; tapEvent = { originalEvent: mouseEventArgs, tapCount: 1 }; let ele: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdowntree' }); document.body.appendChild(ele); originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; }); afterEach((): void => { if (ddtreeObj1) ddtreeObj1.destroy(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; document.body.innerHTML = ''; }); it('with 1000 nodes', (done) => { let hierarchicalData: { [key: string]: Object }[] = []; let parent:number = 1;let child:number = 2;let child1:number = 4;let child2:number = 100; for (let m:number = 1; m <= parent; m++) { let childArray1:{ [key: string]: Object }[] = []; for (let n:number = 1; n <= child; n++) { let childArray2:{ [key: string]: Object }[] = []; for (let o:number = 1; o <= child1; o++) { let childArray3:{ [key: string]: Object }[] = []; for (let p:number = 1; p <= child2; p++) { childArray3.push({ id: "d" + m + n + o + p, name: "Node" + m + n + o + p }); } childArray2.push({ id: "c" + m + n + o, name: "Node" + m + n + o, child: childArray3, expanded: false }); } childArray1.push({ id: "b" + m + n, name: "Node" + m + n, child: childArray2, expanded: false }); } hierarchicalData.push({ id: "a" + m, name: "Node" + m, child: childArray1, expanded: false }); } let startDate:number; let timeTaken:number; // Render the Dropdown Tree by mapping its fields property with data source properties ddtreeObj1 = new DropDownTree({ fields: { dataSource: hierarchicalData, value: "id", text: "name", child: "child", }, showCheckBox: true, changeOnBlur: false, treeSettings: { loadOnDemand: true, autoCheck: true }, mode: "Delimiter", popupHeight: "220px", placeholder: "Select a folder or file", change: function () { timeTaken = new Date().getTime() - startDate; } }); ddtreeObj1.appendTo('#dropdowntree'); ddtreeObj1.showPopup(); setTimeout(() => { let li: Element[] = (ddtreeObj1.element as any).ej2_instances[0].tree.querySelectorAll('li'); mouseEventArgs.target = li[0].querySelector('.e-list-text'); startDate = new Date().getTime(); (ddtreeObj1 as any).treeObj.touchClickObj.tap(tapEvent); setTimeout(() => { expect(timeTaken).toBeLessThan(1000); done(); },1000 ); },1000 ); }); }); describe('noRecordTemplate testing', () => { let ddtreeObj: DropDownTree; let element: HTMLInputElement = <HTMLInputElement>createElement('input', { id: 'dropdowntree' }); let mouseEventArgs: any = { preventDefault: function () { }, target: null }; beforeAll(() => { setCulture('en-US') document.body.appendChild(element); let noRecordTemplate: Element = createElement('div', { id: 'noRecordTemplate' }); noRecordTemplate.innerHTML = '<div><span>There is no record found</span></div>'; document.body.appendChild(noRecordTemplate); ddtreeObj = new DropDownTree({ fields: { dataSource: [], value: 'id', parentValue: 'pid', hasChildren: 'hasChild', text: 'name' }, noRecordsTemplate: '#noRecordTemplate' }); ddtreeObj.appendTo(element); }); afterAll(() => { if (element) { element.remove(); document.body.innerHTML = ''; } }); it('with script', () => { ddtreeObj.showPopup(); expect((ddtreeObj as any).popupObj.element.firstElementChild.classList.contains('e-no-data')).toBe(true); expect((ddtreeObj as any).popupObj.element.firstElementChild.innerText).toBe('There is no record found'); }); }); });
the_stack
import moment = require('../'); // Tests are copied from all the code examples on https://momentjs.com/timezone/docs/ and then lightly tweaked to be valid code. // Run this in Chrome's DevTools: // const exclude = Array.from($('.docs-method-signature>pre>code')); // const include = Array.from($('code.language-js')); // copy(include.filter(v => !exclude.some(v2 => v2 === v)).map(v => v.innerText).join('\n\n')); moment().tz("America/Los_Angeles").format(); var a = moment.tz("2013-11-18 11:55", "America/Toronto"); var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto"); var c = moment.tz(1403454068850, "America/Toronto"); a.format(); // 2013-11-18T11:55:00-05:00 b.format(); // 2014-05-12T20:00:00-04:00 c.format(); // 2014-06-22T12:21:08-04:00 moment.tz("2013-12-01", "America/Los_Angeles").format(); // 2013-12-01T00:00:00-08:00 moment.tz("2013-06-01", "America/Los_Angeles").format(); // 2013-06-01T00:00:00-07:00 var arr = [2013, 5, 1], str = "2013-12-01", obj = { year : 2013, month : 5, day : 1 }; moment.tz(arr, "America/Los_Angeles").format(); // 2013-06-01T00:00:00-07:00 moment.tz(str, "America/Los_Angeles").format(); // 2013-12-01T00:00:00-08:00 moment.tz(obj, "America/Los_Angeles").format(); // 2013-06-01T00:00:00-07:00 moment.tz(arr, "America/New_York").format(); // 2013-06-01T00:00:00-04:00 moment.tz(str, "America/New_York").format(); // 2013-12-01T00:00:00-05:00 moment.tz(obj, "America/New_York").format(); // 2013-06-01T00:00:00-04:00 var zoneName = "America/Los_Angeles"; moment.tz('2013-06-01T00:00:00', zoneName).format(); // 2013-06-01T00:00:00-07:00 moment.tz('2013-06-01T00:00:00-04:00', zoneName).format(); // 2013-05-31T21:00:00-07:00 moment.tz('2013-06-01T00:00:00+00:00', zoneName).format(); // 2013-05-31T17:00:00-07:00 var timestamp = 1403454068850, date = new Date(timestamp); moment.tz(timestamp, "America/Los_Angeles").format(); // 2014-06-22T09:21:08-07:00 moment(timestamp).tz("America/Los_Angeles").format(); // 2014-06-22T09:21:08-07:00 moment.tz(date, "America/Los_Angeles").format(); // 2014-06-22T09:21:08-07:00 moment(date).tz("America/Los_Angeles").format(); // 2014-06-22T09:21:08-07:00 moment.tz("2012-03-11 01:59:59", "America/New_York").format() // 2012-03-11T01:59:59-05:00 moment.tz("2012-03-11 02:00:00", "America/New_York").format() // 2012-03-11T03:00:00-04:00 moment.tz("2012-03-11 02:59:59", "America/New_York").format() // 2012-03-11T03:59:59-04:00 moment.tz("2012-03-11 03:00:00", "America/New_York").format() // 2012-03-11T03:00:00-04:00 moment.tz("2012-11-04 00:59:59", "America/New_York"); // 2012-11-04T00:59:59-04:00 moment.tz("2012-11-04 01:00:00", "America/New_York"); // 2012-11-04T01:00:00-04:00 moment.tz("2012-11-04 01:59:59", "America/New_York"); // 2012-11-04T01:59:59-04:00 moment.tz("2012-11-04 02:00:00", "America/New_York"); // 2012-11-04T02:00:00-05:00 moment.tz("2012-11-04 01:00:00-04:00", "America/New_York"); // 2012-11-04T01:00:00-04:00 moment.tz("2012-11-04 01:00:00-05:00", "America/New_York"); // 2012-11-04T01:00:00-05:00 moment.tz([2012, 0], 'America/New_York').format('z'); // EST moment.tz([2012, 5], 'America/New_York').format('z'); // EDT moment.tz([2012, 0], 'America/Los_Angeles').format('z'); // PST moment.tz([2012, 5], 'America/Los_Angeles').format('z'); // PDT // Denver observes DST moment.tz([2012, 0], 'America/Denver').format('Z z'); // -07:00 MST moment.tz([2012, 5], 'America/Denver').format('Z z'); // -06:00 MDT // Phoenix does not observe DST moment.tz([2012, 0], 'America/Phoenix').format('Z z'); // -07:00 MST moment.tz([2012, 5], 'America/Phoenix').format('Z z'); // -07:00 MST moment.tz('2016-01-01', 'America/Chicago').format('z'); // CST moment.tz('2016-01-01', 'Asia/Shanghai').format('z'); // CST moment.tz([2012, 0], 'America/New_York').zoneAbbr(); // EST moment.tz([2012, 5], 'America/New_York').zoneAbbr(); // EDT var abbrs: {[prop: string]: string} = { EST : 'Eastern Standard Time', EDT : 'Eastern Daylight Time', CST : 'Central Standard Time', CDT : 'Central Daylight Time', MST : 'Mountain Standard Time', MDT : 'Mountain Daylight Time', PST : 'Pacific Standard Time', PDT : 'Pacific Daylight Time', }; moment.fn.zoneName = function () { var abbr = this.zoneAbbr(); return abbrs[abbr] || abbr; }; moment.tz([2012, 0], 'America/New_York').format('zz'); // Eastern Standard Time moment.tz([2012, 5], 'America/New_York').format('zz'); // Eastern Daylight Time moment.tz([2012, 0], 'America/Los_Angeles').format('zz'); // Pacific Standard Time moment.tz([2012, 5], 'America/Los_Angeles').format('zz'); // Pacific Daylight Time moment.tz('America/Los_Angeles').format('z') // "PDT" (abbreviation) moment.tz('Asia/Magadan').format('z') // "+11" (3-char offset) moment.tz('Asia/Colombo').format('z') // "+0530" (5-char offset) moment.tz.setDefault("America/New_York"); moment.tz.setDefault(); moment.tz.guess(); // America/Chicago const unpackedZone: moment.UnpackedZone = { name : 'America/Los_Angeles', // the unique identifier abbrs : ['PDT', 'PST'], // the abbreviations untils : [1414918800000, 1425808800000], // the timestamps in milliseconds offsets : [420, 480] // the offsets in minutes } moment.tz.zone('America/Los_Angeles').abbr(1403465838805); // PDT moment.tz.zone('America/Los_Angeles').abbr(1388563200000); // PST moment.tz.zone('America/Los_Angeles').offset(1403465838805); // 420 moment.tz.zone('America/Los_Angeles').offset(1388563200000); // 480 var zone = moment.tz.zone('America/New_York'); zone.parse(Date.UTC(2012, 2, 19, 8, 30)); // 240 var zone = moment.tz.zone('America/New_York'); zone.parse(Date.UTC(2012, 2, 11, 1, 59)); // 300 zone.parse(Date.UTC(2012, 2, 11, 2, 0)); // 240 const unpackedZone2: moment.UnpackedZone = { name : 'America/Los_Angeles', abbrs : ['PST', 'PDT','PST', 'PDT', 'PST', 'PDT', 'PST', 'PDT', 'PST', 'PDT', 'PST'], untils : [1394359200000, 1414918800000, 1425808800000, 1446368400000, 1457863200000, 1478422800000, 1489312800000, 1509872400000, 1520762400000, 1541322000000, null], offsets : [480, 420, 480, 420, 480, 420, 480, 420, 480, 420, 480] } 'America/Los_Angeles|PST PDT|80 70|01010101010|1Lzm0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0' moment.tz.add('America/Los_Angeles|PST PDT|80 70|01010101010|1Lzm0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0'); moment.tz.link('America/Los_Angeles|US/Pacific'); moment.tz("2013-12-01", "America/Los_Angeles").format(); // 2013-12-01T00:00:00-08:00 moment.tz("2013-12-01", "US/Pacific").format(); // 2013-12-01T00:00:00-08:00 moment.tz.add('America/Los_Angeles|PST PDT|80 70|0101|1Lzm0 1zb0 Op0'); moment.tz.add([ 'America/Los_Angeles|PST PDT|80 70|0101|1Lzm0 1zb0 Op0', 'America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0' ]); moment.tz.link('America/Los_Angeles|US/Pacific'); moment.tz.link([ 'America/Los_Angeles|US/Pacific', 'America/New_York|US/Eastern' ]); const packedZoneBundle: moment.PackedZoneBundle = { version : '2014e', zones : [ 'America/Los_Angeles|PST PDT|80 70|0101|1Lzm0 1zb0 Op0', 'America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0' ], links : [ 'America/Los_Angeles|US/Pacific', 'America/New_York|US/Eastern' ] } moment.tz.load({ version : '2014e', zones : ['packed', 'packed'], links : ['packedlink', 'packedlink'] }) moment.tz.zone("UnloadedZone"); // null moment.tz.add("UnloadedZone|UZ|0|0|"); moment.tz.zone("UnloadedZone"); // Zone { name : "UnloadedZone", ...} moment.tz.names(); // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", ...] // in moment-timezone.js moment.tz.unpack moment.tz.unpackBase60 // in moment-timezone-utils.js moment.tz.pack moment.tz.packBase60 moment.tz.createLinks moment.tz.filterYears moment.tz.filterLinkPack var unpacked = { name : 'Indian/Mauritius', abbrs : ['LMT', 'MUT', 'MUST', 'MUT', 'MUST', 'MUT'], offsets : [-230, -240, -300, -240, -300, -240], untils : [-1988164200000, 403041600000, 417034800000, 1224972000000, 1238274000000, null] }; moment.tz.pack(unpacked); // "Indian/Mauritius|LMT MUT MUST|-3O -40 -50|012121|-2xorO 34unO 14L0 12kr0 11z0" var packed = "Indian/Mauritius|LMT MUT MUST|-3O -40 -50|012121|-2xorO 34unO 14L0 12kr0 11z0"; moment.tz.unpack(packed); // { // name : 'Indian/Mauritius', // abbrs : ['LMT', 'MUT', 'MUST', 'MUT', 'MUST', 'MUT'], // offsets : [-230, -240, -300, -240, -300, -240], // untils : [-1988164200000, 403041600000, 417034800000, 1224972000000, 1238274000000, null] // }; moment.tz.packBase60(9); // 9 moment.tz.packBase60(10); // a moment.tz.packBase60(59); // X moment.tz.packBase60(1337); // mh moment.tz.packBase60(1.1667, 1); // 1.a moment.tz.packBase60(20.12345, 3); // k.7op moment.tz.packBase60(59, 1); // X moment.tz.packBase60(1.1667, 1); // 1.a moment.tz.packBase60(0.1667, 1); // .a moment.tz.packBase60(1/6, 1); // .a moment.tz.packBase60(1/6, 5); // .a moment.tz.packBase60(59, 5); // X moment.tz.unpackBase60('9'); // 9 moment.tz.unpackBase60('a'); // 10 moment.tz.unpackBase60('X'); // 59 moment.tz.unpackBase60('mh'); // 1337 moment.tz.unpackBase60('1.9'); // 1.15 moment.tz.unpackBase60('k.7op'); // 20.123449074074074 var unlinked: moment.UnpackedZoneBundle = { zones : [ {name:"Zone/One",abbrs:["OST","ODT"],offsets:[60,120],untils:[403041600000,417034800000]}, {name:"Zone/Two",abbrs:["OST","ODT"],offsets:[60,120],untils:[403041600000,417034800000]} ], links: [], version : "2014x-doc-example" }; moment.tz.createLinks(unlinked); // { // zones : [ // {name:"Zone/One",abbrs:["OST","ODT"],offsets:[60,120],untils:[403041600000,417034800000]} // ], // links : ["Zone/One|Zone/Two"], // version : "2014x-doc-example" // } var all = { name : "America/Los_Angeles", abbrs : ['EST', 'EDT'], offsets : [1, 2], untils : [1, 2]}; var subset = moment.tz.filterYears(all, 2012, 2016); all.untils.length; // 186 subset.untils.length; // 11 var all = { name : "America/Los_Angeles", abbrs : ['EST', 'EDT'], offsets : [1, 2], untils : [1, 2]}; var subset = moment.tz.filterYears(all, 2012); all.untils.length; // 186 subset.untils.length; // 3
the_stack
import { blackAlpha, hcButtonFace, hcButtonText, hcCanvas, hcCanvasText, hcDisabled, hcHighlight, hcHighlightText, hcHyperlink, } from '../global/colors'; import type { ColorTokens } from '../types'; export const generateColorTokens = (): ColorTokens => ({ colorNeutralForeground1: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralForeground1Hover: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground1Pressed: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground1Selected: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground2: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralForeground2Hover: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground2Pressed: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground2Selected: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground2BrandHover: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground2BrandPressed: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground2BrandSelected: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground3: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralForeground3Hover: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground3Pressed: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground3Selected: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground3BrandHover: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground3BrandPressed: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground3BrandSelected: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForeground4: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralForegroundDisabled: hcDisabled, // GrayText Global.Color.hcDisabled colorNeutralForegroundInvertedDisabled: hcDisabled, // GrayText Global.Color.hcDisabled colorBrandForegroundLink: hcHyperlink, // LinkText Global.Color.hcHyperlink colorBrandForegroundLinkHover: hcHyperlink, // LinkText Global.Color.hcHyperlink colorBrandForegroundLinkPressed: hcHyperlink, // LinkText Global.Color.hcHyperlink colorBrandForegroundLinkSelected: hcHyperlink, // LinkText Global.Color.hcHyperlink colorNeutralForeground2Link: hcHyperlink, // LinkText Global.Color.hcHyperlink colorNeutralForeground2LinkHover: hcHyperlink, // LinkText Global.Color.hcHyperlink colorNeutralForeground2LinkPressed: hcHyperlink, // LinkText Global.Color.hcHyperlink colorNeutralForeground2LinkSelected: hcHyperlink, // LinkText Global.Color.hcHyperlink colorCompoundBrandForeground1: hcHighlight, // Highlight Global.Color.hcHighlight colorCompoundBrandForeground1Hover: hcHighlight, // Highlight Global.Color.hcHighlight colorCompoundBrandForeground1Pressed: hcHighlight, // Highlight Global.Color.hcHighlight colorBrandForeground1: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorBrandForeground2: hcButtonText, // ButtonText Global.Color.hcButtonText colorNeutralForeground1Static: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralForegroundInverted: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralForegroundInvertedHover: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForegroundInvertedPressed: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForegroundInvertedSelected: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralForegroundOnBrand: hcButtonText, // ButtonText Global.Color.hcButtonText colorNeutralForegroundInvertedLink: hcHyperlink, // LinkText Global.Color.hcHyperlink colorNeutralForegroundInvertedLinkHover: hcHyperlink, // LinkText Global.Color.hcHyperlink colorNeutralForegroundInvertedLinkPressed: hcHyperlink, // LinkText Global.Color.hcHyperlink colorNeutralForegroundInvertedLinkSelected: hcHyperlink, // LinkText Global.Color.hcHyperlink colorBrandForegroundInverted: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorBrandForegroundInvertedHover: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorBrandForegroundInvertedPressed: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorBrandForegroundOnLight: hcButtonText, // ButtonText Global.Color.hcButtonText colorBrandForegroundOnLightHover: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorBrandForegroundOnLightPressed: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorBrandForegroundOnLightSelected: hcHighlightText, // HighlightText Global.Color.hcHighlightText colorNeutralBackground1: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralBackground1Hover: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground1Pressed: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground1Selected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground2: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralBackground2Hover: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground2Pressed: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground2Selected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground3: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralBackground3Hover: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground3Pressed: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground3Selected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground4: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralBackground4Hover: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground4Pressed: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground4Selected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground5: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralBackground5Hover: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground5Pressed: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground5Selected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackground6: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralBackgroundInverted: hcCanvas, // Canvas Global.Color.hcCanvas colorSubtleBackground: 'transparent', // transparent undefined colorSubtleBackgroundHover: hcHighlight, // Highlight Global.Color.hcHighlight colorSubtleBackgroundPressed: hcHighlight, // Highlight Global.Color.hcHighlight colorSubtleBackgroundSelected: hcHighlight, // Highlight Global.Color.hcHighlight colorSubtleBackgroundLightAlphaHover: hcHighlight, // Highlight Global.Color.hcHighlight colorSubtleBackgroundLightAlphaPressed: hcHighlight, // Highlight Global.Color.hcHighlight colorSubtleBackgroundLightAlphaSelected: hcHighlight, // Highlight Global.Color.hcHighlight colorSubtleBackgroundInverted: 'transparent', // transparent undefined colorSubtleBackgroundInvertedHover: hcHighlight, // Highlight Global.Color.hcHighlight colorSubtleBackgroundInvertedPressed: hcHighlight, // Highlight Global.Color.hcHighlight colorSubtleBackgroundInvertedSelected: hcHighlight, // Highlight Global.Color.hcHighlight colorTransparentBackground: 'transparent', // transparent undefined colorTransparentBackgroundHover: hcHighlight, // Highlight Global.Color.hcHighlight colorTransparentBackgroundPressed: hcHighlight, // Highlight Global.Color.hcHighlight colorTransparentBackgroundSelected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralBackgroundDisabled: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralBackgroundInvertedDisabled: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralStencil1: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralStencil2: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorBackgroundOverlay: blackAlpha[50], // rgba(0, 0, 0, 0.5) Global.Color.BlackAlpha.50 colorScrollbarOverlay: hcButtonFace, // ButtonFace Global.Color.hcButtonFace colorBrandBackground: hcButtonFace, // ButtonFace Global.Color.hcButtonFace colorBrandBackgroundHover: hcHighlight, // Highlight Global.Color.hcHighlight colorBrandBackgroundPressed: hcHighlight, // Highlight Global.Color.hcHighlight colorBrandBackgroundSelected: hcHighlight, // Highlight Global.Color.hcHighlight colorCompoundBrandBackground: hcHighlight, // Highlight Global.Color.hcHighlight colorCompoundBrandBackgroundHover: hcHighlight, // Highlight Global.Color.hcHighlight colorCompoundBrandBackgroundPressed: hcHighlight, // Highlight Global.Color.hcHighlight colorBrandBackgroundStatic: hcCanvas, // Canvas Global.Color.hcCanvas colorBrandBackground2: hcButtonFace, // ButtonFace Global.Color.hcButtonFace colorBrandBackgroundInverted: hcButtonFace, // ButtonFace Global.Color.hcButtonFace colorBrandBackgroundInvertedHover: hcHighlight, // Highlight Global.Color.hcHighlight colorBrandBackgroundInvertedPressed: hcHighlight, // Highlight Global.Color.hcHighlight colorBrandBackgroundInvertedSelected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralStrokeAccessible: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralStrokeAccessibleHover: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralStrokeAccessiblePressed: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralStrokeAccessibleSelected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralStroke1: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralStroke1Hover: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralStroke1Pressed: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralStroke1Selected: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralStroke2: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralStroke3: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralStrokeOnBrand: hcCanvas, // Canvas Global.Color.hcCanvas colorNeutralStrokeOnBrand2: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralStrokeOnBrand2Hover: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralStrokeOnBrand2Pressed: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorNeutralStrokeOnBrand2Selected: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorBrandStroke1: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorBrandStroke2: hcCanvas, // Canvas Global.Color.hcCanvas colorCompoundBrandStroke: hcHighlight, // Highlight Global.Color.hcHighlight colorCompoundBrandStrokeHover: hcHighlight, // Highlight Global.Color.hcHighlight colorCompoundBrandStrokePressed: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralStrokeDisabled: hcDisabled, // GrayText Global.Color.hcDisabled colorNeutralStrokeInvertedDisabled: hcDisabled, // GrayText Global.Color.hcDisabled colorTransparentStroke: hcCanvasText, // CanvasText Global.Color.hcCanvasText colorTransparentStrokeInteractive: hcHighlight, // Highlight Global.Color.hcHighlight colorTransparentStrokeDisabled: hcDisabled, // GrayText Global.Color.hcDisabled colorStrokeFocus1: hcCanvas, // Canvas Global.Color.hcCanvas colorStrokeFocus2: hcHighlight, // Highlight Global.Color.hcHighlight colorNeutralShadowAmbient: 'rgba(0,0,0,0.24)', // rgba(0,0,0,0.24) undefined colorNeutralShadowKey: 'rgba(0,0,0,0.28)', // rgba(0,0,0,0.28) undefined colorNeutralShadowAmbientLighter: 'rgba(0,0,0,0.12)', // rgba(0,0,0,0.12) undefined colorNeutralShadowKeyLighter: 'rgba(0,0,0,0.14)', // rgba(0,0,0,0.14) undefined colorNeutralShadowAmbientDarker: 'rgba(0,0,0,0.40)', // rgba(0,0,0,0.40) undefined colorNeutralShadowKeyDarker: 'rgba(0,0,0,0.48)', // rgba(0,0,0,0.48) undefined colorBrandShadowAmbient: 'rgba(0,0,0,0.30)', // rgba(0,0,0,0.30) undefined colorBrandShadowKey: 'rgba(0,0,0,0.25)', // rgba(0,0,0,0.25) undefined });
the_stack
import { OnInit, OnDestroy, AfterViewInit, AfterViewChecked, OnChanges, SimpleChanges, ChangeDetectorRef, TemplateRef, ViewChild, NgZone } from '@angular/core'; import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; import { WidgetService } from '../../../widget.service'; import { NotificationService, Base64Service, Principal, WidgetEventBusService } from '../../../../../shared'; import * as $ from 'jquery'; import { Observable } from 'rxjs'; import { JhiEventManager } from 'ng-jhipster'; import { DataWidgetComponent } from '../datawidget.component'; import { DataSourceService } from '../../../../data-source/data-source.service'; import * as echarts from 'echarts'; import { HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { DataSource } from 'app/entities/data-source'; import { SnapshotMenuComponent } from '../..'; import { Router } from '@angular/router'; import { WidgetType } from 'app/entities/widget/widget.model'; const elementResizeEvent = require('element-resize-event'); const fileSaver = require('file-saver'); export abstract class AbstractPieChartWidgetComponent extends DataWidgetComponent implements OnInit, OnDestroy, AfterViewInit, AfterViewChecked, OnChanges { @ViewChild('minDocCountSlider') minDocCountSlider: any; @ViewChild('maxValuesPerFieldSlider') maxValuesPerFieldSlider: any; // classes names (both edges and nodes even though the datasource is a graph) allClassesNames: string[]; // nodes fetching selectedClass: string; limitEnabled: boolean = true; limitForNodeFetching: number = 100; // pie chart data pieChartContainer; pieChart; pieChartData: Object[]; pieChartLegendData: string[]; pieChartLegendDataSelected: Object; selectedClassProperties: string[]; selectedProperty: string; currentFaceting: Object; // analysis modalRef: BsModalRef; startingPopoverMessage: string = 'Start your analysis by choosing a class, then specify a property.'; startingPopoverMustBeOpen: boolean = true; // use to force the opening or closure of the popover // snapshot menu @ViewChild('snapshotMenu') snapshotMenu: SnapshotMenuComponent; // perspective pieChartTabActive: boolean = true; datasourceTabActive: boolean = false; // layout options showLegend: boolean = true; showLabels: boolean = true; labelPosition: string = 'outside'; maxSidebarHeight: string; radius: number = 75; // slider configs radiusSliderConfig = { behaviour: 'drag', connect: true, start: [this.radius], keyboard: false, // same as [keyboard]='true' step: 1, range: { min: 10, max: 100 } }; // settings minDocCount: number = 5; maxValuesPerField: number = 100; // settings sliders configs minDocCountSliderConfig: any; maxValuesPerFieldSliderConfig: any; minDocCountSliderUpperValue: number = 1000; maxValuesPerFieldSliderUpperValue: number = 1000; // popovers minDocCountTip: string = `Include in the series just all the values for the selected properties with cardinality (number of occurrences) greater than or equal to the specified threshold.<br/> Thus all the value properties with cardinality below the set threshold will be excluded from the distribution.`; maxValuesPerFieldTip: string = `Include in the series just the first <i>n</i> values (where <i>n</i> is the specified threshold) for the selected properties with greater cardinality.<br/> The set threshold corresponds to the maximum number of slices that can be rendered in the chart.`; radiusTip: string = 'Pie chart radius length declared as percentage respect to the chart container. Allowed values from 10% to 100%.'; // messages checkThresholdsMessage: string = `\n\nTry to check the "Min Value Occurrences" and "Most Relevant Values Occurrences" thresholds in the Settings menu. Maybe the constraints are too strong to get any result.`; public outerAccordion: string = 'outer-accordion'; public innerAccordion: string = 'inner-accordion'; constructor( protected ngZone: NgZone, protected principal: Principal, protected widgetService: WidgetService, protected notificationService: NotificationService, protected dataSourceService: DataSourceService, protected eventManager: JhiEventManager, protected cdr: ChangeDetectorRef, protected modalService: BsModalService, protected base64Service: Base64Service, protected widgetEventBusService: WidgetEventBusService, protected router: Router) { super(principal, widgetService, notificationService, dataSourceService, eventManager, cdr, modalService, base64Service, widgetEventBusService, router); } /** * Abstract methods */ abstract handleSelectedPropertyModelChanging(): void; abstract runSeriesComputation(saveAfterUpdate?: boolean): void; ngOnInit() { // widget id init this.widgetId = this.widget['id']; this.fileName = this.widget['name']; // loading datasource, then the snapshot const datasourceId = this.widget['dataSourceId']; if (!this.embedded) { this.dataSourceService.find(datasourceId).subscribe((res: DataSource) => { this.dataSource = res; this.checkDatasourceIndexingAlert(); }); } if (this.oldSnapshotToLoad) { // load snapshot this.loadSnapshot(); this.startingPopoverMustBeOpen = false; } else { // first metadata request in order to fetch all the metadata about nodes and edges classes with the related cardinalities. // Performed just if the current widget is an independent widget. if (!this.minimizedView && !this.widget.primaryWidgetId) { this.dataSourceService.loadMetadata(datasourceId).subscribe((dataSourceMetadata: Object) => { this.dataSourceMetadata = dataSourceMetadata; this.updateClassesNamesAccordingMetadata(); }, (error: HttpErrorResponse) => { this.handleError(error.error, 'Metadata loading'); }); } } // initializing the search term observer this.searchTermObserver = this.searchTerm.subscribe((event) => { this.lastEmittedSearchTerm = event; }); this.registerChangeInDashboards(); // authorities and depending params init if (!this.embedded) { this.initParamsDependingOnUserIdentities(); } // settings sliders configs this.minDocCountSliderConfig = { behaviour: 'drag', connect: true, start: this.minDocCount, keyboard: false, // same as [keyboard]='true' step: 1, pageSteps: 10, // number of page steps, defaults to 10 range: { min: 1, max: this.minDocCountSliderUpperValue }, pips: { mode: 'count', density: 10, values: 2, stepped: true } }; this.maxValuesPerFieldSliderConfig = { behaviour: 'drag', connect: true, start: this.maxValuesPerField, keyboard: false, // same as [keyboard]='true' step: 1, pageSteps: 10, // number of page steps, defaults to 10 range: { min: 1, max: this.maxValuesPerFieldSliderUpperValue }, pips: { mode: 'count', density: 10, values: 2, stepped: true } }; } ngOnChanges(changes: SimpleChanges): void {} ngOnDestroy() { this.eventManager.destroy(this.dashboardPanelResizedSubscriber); } ngAfterViewInit() { // defined in the secondary-bar-chart and independent-bar-chart classes } performAdditionalInit() { this.sidebarResetMenu(); // possible overflow handling this.tooltipOnOverflow(); // attach listener to resize event const elementId = '#widget-viewport_' + this.widgetId; const element = $(elementId).get(0); elementResizeEvent(element, () => { // TODO: resize table? }); if (this.minimizedView) { // hide tabs (<any>$('.widget-viewport .tab-container ul')).css('display', 'none'); } // pie chart init just if something was loaded from the snapshot if (this.snapshotLoaded) { this.initPieChart(); } } ngAfterViewChecked() { } updateClassesNamesAccordingMetadata() { const nodesClassesNames: string[] = [...Object.keys(this.dataSourceMetadata['nodesClasses'])]; nodesClassesNames.sort(); const edgesClassesNames: string[] = [...Object.keys(this.dataSourceMetadata['edgesClasses'])]; edgesClassesNames.sort(); this.allClassesNames = nodesClassesNames.concat(edgesClassesNames); } registerChangeInDashboards() { this.dashboardPanelResizedSubscriber = this.eventManager.subscribe( 'dashboardPanelResized', (response) => { if (response.content === this.widgetId) { console.log('Pie Chart widget #' + this.widgetId + ' detected resize in minimized view.'); } } ); } initPieChart() { this.ngZone.runOutsideAngular(() => { this.pieChartContainer = document.getElementById('pieChart_' + this.widgetId); this.pieChart = echarts.init(this.pieChartContainer); }); this.attachPieChartEvents(); } attachPieChartEvents() { // attach listener to resize event elementResizeEvent(this.pieChartContainer, () => { if (this.pieChart) { this.pieChart.resize(); } else { console.log('Cannot resize the pie chart as is not present in the widget viewport.'); } }); this.pieChart.on('legendselectchanged', (event) => { // updating selected items in pie chart legend this.pieChartLegendDataSelected = event['selected']; }); } /** * Snapshot, data and metadata handling */ loadSnapshot() { this.startSpinner(); if (this.embedded) { // use the open service to load the snapshot this.widgetService.loadSnapshotForEmbeddedWidget(this.widget['uuid']).subscribe((snapshot: Object) => { this.performSnapshotLoading(snapshot); }, (error: HttpErrorResponse) => { this.stopSpinner(); this.notificationService.push('error', 'Widget not available', this.notSharedWidgetMessage); }); } else { // use the closed service to load the snpashot this.widgetService.loadSnapshot(this.widgetId).subscribe((snapshot: Object) => { this.performSnapshotLoading(snapshot); }, (error: HttpErrorResponse) => { this.stopSpinner(); this.handleError(error.error, 'Snapshot loading'); }); } } performSnapshotLoading(snapshot) { setTimeout(() => { // small timeout just to allow spinner to start, otherwise cy loading interferes with angular variable // update process and the spinner does not start this.updatePieChartWidgetFromSnapshot(snapshot); this.updateClassesNamesAccordingMetadata(); }, 10); } updatePieChartWidgetFromSnapshot(snapshot) { // if the pie chart is already initialised we are not performing the first loading, // then we have to destroy the chart instance before a new initialisation. if (this.pieChart) { this.ngZone.runOutsideAngular(() => { this.pieChart.dispose(); this.pieChart = undefined; }); } /* * Loading bar chart data */ this.pieChartData = snapshot['pieChartData']; this.pieChartLegendData = snapshot['pieChartLegendData']; this.pieChartLegendDataSelected = snapshot['pieChartLegendDataSelected']; this.currentFaceting = snapshot['currentFaceting']; /* * Loading metadata */ this.dataSourceMetadata = snapshot['dataSourceMetadata']; /* * Loading options */ if (!this.minimizedView && snapshot['perspective']) { this.pieChartTabActive = snapshot['perspective']['pieChartTabActive']; this.datasourceTabActive = snapshot['perspective']['datasourceTabActive']; } this.selectedClass = snapshot['selectedClass']; this.limitEnabled = snapshot['limitEnabled']; this.limitForNodeFetching = snapshot['limitForNodeFetching']; this.selectedClassProperties = snapshot['selectedClassProperties']; this.selectedProperty = snapshot['selectedProperty']; this.showLegend = snapshot['showLegend']; this.showLabels = snapshot['showLabels']; this.labelPosition = snapshot['labelPosition']; if (snapshot['radius']) { this.radius = snapshot['radius']; } if (snapshot['minDocCountSliderUpperValue']) { this.minDocCountSliderUpperValue = snapshot['minDocCountSliderUpperValue']; } if (snapshot['maxValuesPerFieldSliderUpperValue']) { this.maxValuesPerFieldSliderUpperValue = snapshot['maxValuesPerFieldSliderUpperValue']; } // updating slider values if not in minimized view or embedded if (!this.minimizedView && !this.embedded && this.widget.type !== WidgetType.SECONDARY_QUERY_PIE_CHART) { this.updateSettingsSliderUpperValue().subscribe(() => { console.log('Thresholds updated.'); if (snapshot['minDocCount']) { this.minDocCount = snapshot['minDocCount']; } if (snapshot['maxValuesPerField']) { this.maxValuesPerField = snapshot['maxValuesPerField']; } this.snapshotLoaded = true; }); } else { if (snapshot['minDocCount']) { this.minDocCount = snapshot['minDocCount']; } else { this.minDocCount = 1; // we take off this series filter } if (snapshot['maxValuesPerField']) { this.maxValuesPerField = snapshot['maxValuesPerField']; } this.snapshotLoaded = true; } this.stopSpinner(); // initializing pie chart according to just loaded data this.updatePieChart(); } /** * Pie Chart Handling */ /** * Updates minDocCount and maxFieldPerValues settings, then return true if it succeeds, otherwise false. */ updateSettingsSliderUpperValue(): Observable<boolean> { const errorTitle: string = 'Faceting Threshold Computing'; if (this.selectedClass && this.selectedProperty) { const classes: string[] = [this.selectedClass]; const fields: string[] = [this.selectedProperty]; const minDocCount: number = 1; // we don't want filter out anything let maxValuesPerField: number; if (this.dataSourceMetadata['nodesClasses'][this.selectedClass]) { maxValuesPerField = this.dataSourceMetadata['nodesClasses'][this.selectedClass]['cardinality']; } else if (this.dataSourceMetadata['edgesClasses'][this.selectedClass]) { maxValuesPerField = this.dataSourceMetadata['edgesClasses'][this.selectedClass]['cardinality']; } else { this.notificationService.push('error', errorTitle, 'Current class not present in datasource metadata.'); } if (this.dataSource && this.dataSource['indexing'] && this.dataSource['indexing'].toString() === 'INDEXED') { return this.widgetService.fetchWholeFacetingForDatasource(this.widget['dataSourceId'], classes, fields, minDocCount, maxValuesPerField).map((res: Object) => { this.currentFaceting = res; // get the max cardinality to set the minDocCountSliderUpperValue const propertyFaceting = res[this.selectedClass]['propertyValues'][this.selectedProperty]; const arr = Object.keys(propertyFaceting).map((key) => { return propertyFaceting[key]; }); this.minDocCountSliderUpperValue = Math.max.apply(null, arr); // get the number of property values to set the maxValuesPerFieldSliderUpperValue this.maxValuesPerFieldSliderUpperValue = Object.keys(propertyFaceting).length; // setting the minDocCount and maxValuesPerField params according to the new range this.minDocCount = 1; this.maxValuesPerField = this.maxValuesPerFieldSliderUpperValue; this.updateSettingsSlidersConfigRange(); return true; }, (error: HttpErrorResponse) => { this.handleError(error.error, errorTitle); }); } else { this.stopSpinner(); this.notificationService.push('warning', errorTitle, 'Index datasource missing, thresholds cannot be computed.'); return Observable.of(false); } } else { this.stopSpinner(); console.log('[' + this.widget.name + '] Faceting Threshold Computing', 'Class or property are undefined, thresholds cannot be computed.'); return Observable.of(false); } } updateSettingsSlidersConfigRange() { const lowerValue: number = 1; if (this.minDocCountSlider) { if (this.minDocCountSliderUpperValue === lowerValue) { this.minDocCountSliderUpperValue++; } this.minDocCountSlider.slider.updateOptions({ range: { min: lowerValue, max: this.minDocCountSliderUpperValue } }); } if (this.maxValuesPerFieldSlider) { if (this.maxValuesPerFieldSliderUpperValue === lowerValue) { this.maxValuesPerFieldSliderUpperValue++; } this.maxValuesPerFieldSlider.slider.updateOptions({ range: { min: lowerValue, max: this.maxValuesPerFieldSliderUpperValue } }); } } /* * It updates the pie chart data according to the faceting passed as param. * If no faceting is passed as input, then the last loaded faceting will be used. */ updatePieChartFromFaceting(faceting?: any) { this.stopSpinner(); if (!faceting) { faceting = this.currentFaceting; } // updating pie chart data if (faceting && faceting[this.selectedClass]) { const selectedClassFaceting = faceting[this.selectedClass]['propertyValues']; if (!selectedClassFaceting) { let message = 'No faceting is present for the current selected class.'; message += this.checkThresholdsMessage; console.log(message); this.notificationService.push('warning', 'Distribution computation', message); return; } const selectedPropertyFaceting = selectedClassFaceting[this.selectedProperty]; if (!selectedPropertyFaceting) { let message = 'No faceting is present for the current selected property.'; message += this.checkThresholdsMessage; console.log(message); this.notificationService.push('warning', 'Distribution computation', message); return; } this.pieChartData = []; this.pieChartLegendData = []; this.pieChartLegendDataSelected = {}; for (const currValueProperty of Object.keys(selectedPropertyFaceting)) { const currPieChartItem = { name: currValueProperty, value: selectedPropertyFaceting[currValueProperty] }; this.pieChartData.push(currPieChartItem); // legend data updating this.pieChartLegendData.push(currValueProperty); this.pieChartLegendDataSelected[currValueProperty] = true; } this.updatePieChart(); // updating to-save flag this.toSave = true; } else { const message: string = 'Faceting data not correcly retrieved for the ' + this.selectedClass + ' class.'; this.notificationService.push('warning', 'Pie Chart Update', message); } } updatePieChart() { const radiusPercentage = this.radius + '%'; const option = { tooltip : { trigger: 'item', formatter: '{b} : {c} <br/> ({d}%)', enterable: false, confine: true }, legend: { show: this.showLegend, type: 'scroll', orient: 'vertical', right: 10, top: 20, bottom: 20, width: '200px', formatter: (value) => { return this.buildTruncatedLabel(value, 20); }, textStyle: { fontSize: 11 // default is 12 }, data: this.pieChartLegendData, selected: this.pieChartLegendDataSelected }, series: { type: 'pie', center: this.showLegend ? ['40%', '50%'] : ['50%', '50%'], radius : ['0%', radiusPercentage], selectedMode: 'multiple', selectedOffset: 20, label: { formatter: (value) => { return this.buildTruncatedLabel(value['name'], 25); }, show: this.showLabels, position: this.labelPosition, fontSize: 11 }, labelLine: { show: this.showLabels, smooth: false, // specifies if the label line is curved or not emphasis: { width: 1 } }, emphasis: { label: { fontWeight: 'bold', z: 5 } }, data: this.pieChartData, formatter: '{b} : {c} <br/> ({d}%)' } }; // use configuration item and data specified to show chart if (!this.pieChart) { this.initPieChart(); } this.pieChart.setOption(option); } buildTruncatedLabel(inputString: string, numberOfChars: number) { if (inputString) { let outputString: string = inputString; if (outputString.length > numberOfChars) { outputString = outputString.substring(0, numberOfChars); // deleting the last char if it is a blank space if (outputString.charAt(outputString.length - 1) === ' ') { outputString = outputString.substring(0, outputString.length - 1); } outputString = outputString + '...'; } return outputString; } else { return undefined; } } /** * Template Functions */ handleSelectedClassModelChanging() { this.updateSelectedClassProperties(); } updateSelectedClassProperties() { this.selectedProperty = undefined; this.selectedClassProperties = []; if (this.selectedClass) { this.selectedClassProperties = this.getClassProperties(this.selectedClass); if (this.selectedClassProperties.length === 0) { this.notificationService.push('warning', 'No Property found', 'No property found for the selected class.'); } } else { console.log('Cannot update properties as the selected class seems to be udefined.'); } } getClassProperties(className: string): string[] { const classProperties: string[] = []; let classesMetadata = this.dataSourceMetadata['nodesClasses']; if (!classesMetadata[className]) { classesMetadata = this.dataSourceMetadata['edgesClasses']; } if (!classesMetadata) { console.error('[getClassProperties] class not found.'); return; } for (const propName of Object.keys(classesMetadata[className]['properties'])) { classProperties.push(propName); } return classProperties; } hideElements(elements, removeSelection: boolean) { for (const element of elements) { element['data']['hidden'] = true; if (removeSelection) { elements['selected'] = false; } } } // Shows all the elements according to the elements collection passed as param. // It calls the auxiliary method with the showConnectedEdges set true. showElements(elements) { for (const element of elements) { element['data']['hidden'] = false; } } /** * It performs all the operations that must be performed after the indexing process completion. */ performOperationsAfterIndexingComplete() { // DO NOTHING } /** * Perspective */ switchTab(justChosenTab: string) { if (justChosenTab === 'pie-chart') { this.pieChartTabActive = true; this.datasourceTabActive = false; } else if (justChosenTab === 'datasource') { this.pieChartTabActive = false; this.datasourceTabActive = true; } } /** * Theme limitless */ closePopover(popoverName: string) { if (popoverName === 'startingPopover') { if (this.startingPopoverMustBeOpen) { this.startingPopoverMustBeOpen = false; } } } getEmptyWidgetMessageHeight() { const widgetHeight: number = parseInt(this.widgetHeight.replace('px', ''), 10); const top: string = widgetHeight / 3 + 'px'; return top; } sidebarResetMenu() { // Add 'active' class to parent list item in all levels $('.navigation').find('li.active').parents('li').addClass('active'); // Hide all nested lists $('.navigation').find('li').not('.active, .category-title').has('ul').children('ul').addClass('hidden-ul'); // Highlight children links $('.navigation').find('li').has('ul').children('a').addClass('has-ul'); $('.navigation-main').find('li').has('ul').children('a').unbind('click'); $('.navigation-main').find('li').has('ul').children('a').on('click', function(e) { e.preventDefault(); // Collapsible $(this).parent('li') .not('.disabled') .not($('.sidebar-xs') .not('.sidebar-xs-indicator') .find('.navigation-main') .children('li')) .toggleClass('active') .children('ul') .slideToggle(250); // Accordion if ($('.navigation-main').hasClass('navigation-accordion')) { $(this).parent('li') .not('.disabled') .not($('.sidebar-xs') .not('.sidebar-xs-indicator') .find('.navigation-main') .children('li')) .siblings(':has(.has-ul)') .removeClass('active') .children('ul') .slideUp(250); } }); this.toggleOverflowMenu(); } tooltipOnOverflow() { (<any>$('.mightOverflow')).bind('mouseover', function() { const $this = $(this); const width = (<any>$('span')).width(); if (this.offsetWidth > width && !$this.attr('title')) { $this.attr('title', $this.text()); } }); } toggleSideBar() { if (this.sidebarCollapsed) { this.expandSidebar(); } else { this.collapseSidebar(); } } checkSidebarStatusOnExit() { if (this.sidebarCollapsed) { (<any>$('body')).removeClass('sidebar-xs'); } } collapseSidebar() { const initialSidebarSize = (<any>$('.sidebar')).width(); (<any>$('body')).addClass('sidebar-xs'); const finalSidebarSize = (<any>$('.sidebar')).width(); this.sidebarCollapsed = !this.sidebarCollapsed; this.toggleOverflowMenu(); } expandSidebar() { const initialSidebarSize = (<any>$('.sidebar')).width(); (<any>$('body')).removeClass('sidebar-xs'); const finalSidebarSize = (<any>$('.sidebar')).width(); this.sidebarCollapsed = !this.sidebarCollapsed; this.toggleOverflowMenu(); } toggleOverflowMenu() { if (this.sidebarCollapsed) { // remove 'vertical-overflow-scroll' from element with 'cell-content-wrapper' class $('#sidebar-dynamic').removeClass('vertical-overflow-scroll'); // add 'submenu-vertical-overflow' to element with 'hidden-ul' class $('.hidden-ul').addClass('submenu-vertical-overflow'); } else { // add 'vertical-overflow-scroll' to element with 'cell-content-wrapper' class $('#sidebar-dynamic').addClass('vertical-overflow-scroll'); // remove 'submenu-vertical-overflow' from element with 'hidden-ul' class $('.hidden-ul').removeClass('submenu-vertical-overflow'); } } /** * Modals handling */ openQueryModal(template: TemplateRef<any>) { this.modalRef = this.modalService.show(template); } /* * Save/export functions, snapshot loading */ // saves both data and metadata saveAll() { const infoNotification = this.notificationService.push('info', 'Save', 'Saving the widget...', 3000, 'fa fa-spinner fa-spin'); const delay: number = 10; setTimeout(() => { // just to avoid the saving ops block the first notification message const jsonForSnapshotSaving = { pieChartData: this.pieChartData, pieChartLegendData: this.pieChartLegendData, pieChartLegendDataSelected: this.pieChartLegendDataSelected, dataSourceMetadata: this.dataSourceMetadata, currentFaceting: this.currentFaceting, selectedClass: this.selectedClass, limitEnabled: this.limitEnabled, limitForNodeFetching: this.limitForNodeFetching, selectedClassProperties: this.selectedClassProperties, selectedProperty: this.selectedProperty, showLegend: this.showLegend, showLabels: this.showLabels, labelPosition: this.labelPosition, radius: this.radius, minDocCount: this.minDocCount, maxValuesPerField: this.maxValuesPerField, minDocCountSliderUpperValue: this.minDocCountSliderUpperValue, maxValuesPerFieldSliderUpperValue: this.maxValuesPerFieldSliderUpperValue }; const perspective: Object = { pieChartTabActive: this.pieChartTabActive, datasourceTabActive: this.datasourceTabActive, }; jsonForSnapshotSaving['perspective'] = perspective; this.callSnapshotSave(jsonForSnapshotSaving, infoNotification); }, delay); } callSnapshotSave(jsonForSnapshotSaving: Object, infoNotification): void { const jsonContent = JSON.stringify(jsonForSnapshotSaving); this.widgetService.updateWidget(this.widgetId, jsonContent).subscribe((res: HttpResponse<any>) => { if (res.status === 200 || res.status === 204) { if (infoNotification) { const message: string = 'Data correctly saved.'; this.notificationService.updateNotification(infoNotification, 'success', 'Save', message, undefined, true); } // updating to-save flag this.toSave = false; // updating snapshot-menu if (this.snapshotMenu) { this.snapshotMenu.loadSnapshotsNames(); } } else { if (infoNotification) { const message = 'Saving attempt failed.\n' + 'Response status: ' + res.status; this.notificationService.updateNotification(infoNotification, 'error', 'Save', message, undefined, true); } } }, (error: HttpErrorResponse) => { if (infoNotification) { this.notificationService.updateNotification(infoNotification, 'error', 'Save', 'Saving attempt failed.', undefined, true); } console.log(error.error); }); } pieChartExport(content: any, exportType: string) { let blob = undefined; if (exportType === 'image/png' || exportType === 'image/jpg' || exportType === 'image/jpeg') { blob = this.base64Service.b64toBlob(content, exportType, 512); } else if (exportType === 'json') { this.exportAsJSON(); } else { console.log('Error: export type not supported, just "png", "jpeg/jpg" and "json" allowed.'); } exportType = exportType.slice(exportType.indexOf('/') + 1); const fileName = this.fileName + '.' + exportType; fileSaver.saveAs(blob, fileName); } exportAsJSON() { const blob = new Blob([JSON.stringify(this.pieChartData, null, 2)], { type: 'text/plain;charset=utf-8' }); const exportType = 'json'; const fileName = this.fileName + '.' + exportType; fileSaver.saveAs(blob, fileName); } }
the_stack
import * as TestUtils from '../test-utils/test-utils'; import * as testPlugin from './TestPlugin'; import {createState} from '../state/atom'; import {PluginClient} from '../plugin/Plugin'; import {DevicePluginClient} from '../plugin/DevicePlugin'; import mockConsole from 'jest-mock-console'; import {sleep} from 'flipper-common'; import {createDataSource} from '../state/createDataSource'; test('it can start a plugin and lifecycle events', () => { const {instance, ...p} = TestUtils.startPlugin(testPlugin); // @ts-expect-error p.bla; // @ts-expect-error instance.bla; // startPlugin starts connected expect(instance.connectStub).toBeCalledTimes(1); expect(instance.disconnectStub).toBeCalledTimes(0); expect(instance.activateStub).toBeCalledTimes(1); expect(instance.deactivateStub).toBeCalledTimes(0); expect(instance.destroyStub).toBeCalledTimes(0); p.connect(); // noop expect(instance.connectStub).toBeCalledTimes(1); expect(instance.disconnectStub).toBeCalledTimes(0); expect(instance.activateStub).toBeCalledTimes(1); expect(instance.deactivateStub).toBeCalledTimes(0); expect(instance.destroyStub).toBeCalledTimes(0); p.disconnect(); p.connect(); expect(instance.connectStub).toBeCalledTimes(2); expect(instance.disconnectStub).toBeCalledTimes(1); expect(instance.destroyStub).toBeCalledTimes(0); p.deactivate(); // also disconnects p.activate(); expect(instance.connectStub).toBeCalledTimes(3); expect(instance.disconnectStub).toBeCalledTimes(2); expect(instance.activateStub).toBeCalledTimes(2); expect(instance.deactivateStub).toBeCalledTimes(1); p.destroy(); expect(instance.connectStub).toBeCalledTimes(3); expect(instance.disconnectStub).toBeCalledTimes(3); expect(instance.activateStub).toBeCalledTimes(2); expect(instance.deactivateStub).toBeCalledTimes(2); expect(instance.destroyStub).toBeCalledTimes(1); expect(instance.readyStub).toBeCalledTimes(1); expect(instance.appName).toBe('TestApplication'); expect(instance.appId).toBe('TestApplication#Android#TestDevice#serial-000'); // cannot interact with destroyed plugin expect(() => { p.connect(); }).toThrowErrorMatchingInlineSnapshot(`"Plugin has been destroyed already"`); expect(() => { p.activate(); }).toThrowErrorMatchingInlineSnapshot(`"Plugin has been destroyed already"`); }); test('it can start a plugin and lifecycle events for background plugins', () => { const {instance, ...p} = TestUtils.startPlugin(testPlugin, { isBackgroundPlugin: true, }); // @ts-expect-error p.bla; // @ts-expect-error instance.bla; // startPlugin starts connected expect(instance.connectStub).toBeCalledTimes(1); expect(instance.disconnectStub).toBeCalledTimes(0); expect(instance.activateStub).toBeCalledTimes(1); expect(instance.deactivateStub).toBeCalledTimes(0); expect(instance.destroyStub).toBeCalledTimes(0); p.deactivate(); // bg, no disconnection p.activate(); expect(instance.connectStub).toBeCalledTimes(1); expect(instance.disconnectStub).toBeCalledTimes(0); expect(instance.activateStub).toBeCalledTimes(2); expect(instance.deactivateStub).toBeCalledTimes(1); p.destroy(); expect(instance.connectStub).toBeCalledTimes(1); expect(instance.disconnectStub).toBeCalledTimes(1); expect(instance.activateStub).toBeCalledTimes(2); expect(instance.deactivateStub).toBeCalledTimes(2); expect(instance.destroyStub).toBeCalledTimes(1); }); test('it can render a plugin', () => { const {renderer, sendEvent, instance} = TestUtils.renderPlugin(testPlugin); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <h1> Hi from test plugin 0 </h1> </div> </body> `); sendEvent('inc', {delta: 3}); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <h1> Hi from test plugin 3 </h1> </div> </body> `); // @ts-ignore expect(instance.state.listeners.length).toBe(1); renderer.unmount(); // @ts-ignore expect(instance.state.listeners.length).toBe(0); }); test('a plugin can send messages', async () => { const {instance, onSend} = TestUtils.startPlugin(testPlugin); // By default send is stubbed expect(await instance.getCurrentState()).toBeUndefined(); expect(onSend).toHaveBeenCalledWith('currentState', {since: 0}); // @ts-expect-error onSend('bla'); // ... But we can intercept! onSend.mockImplementationOnce(async (method, params) => { expect(method).toEqual('currentState'); expect(params).toEqual({since: 0}); return 3; }); expect(await instance.getCurrentState()).toEqual(3); }); test('a plugin cannot send messages after being disconnected', async () => { const {instance, disconnect} = TestUtils.startPlugin(testPlugin); disconnect(); let threw = false; try { await instance.getCurrentState(); } catch (e) { threw = true; // for some weird reason expect(async () => instance.getCurrentState()).toThrow(...) doesn't work today... expect(e).toMatchInlineSnapshot(`[Error: Plugin is not connected]`); } expect(threw).toBeTruthy(); }); test('a plugin can receive messages', async () => { const {instance, sendEvent, exportState} = TestUtils.startPlugin(testPlugin); expect(instance.state.get().count).toBe(0); sendEvent('inc', {delta: 2}); expect(instance.state.get().count).toBe(2); expect(exportState()).toMatchInlineSnapshot(` Object { "counter": Object { "count": 2, }, } `); expect(instance.unhandledMessages.get().length).toBe(0); sendEvent('unhandled' as any, {hello: 'world'}); expect(instance.unhandledMessages.get()).toEqual([ { event: 'unhandled', params: {hello: 'world'}, }, ]); }); test('plugins support non-serializable state', async () => { const {exportState} = TestUtils.startPlugin({ plugin() { const field1 = createState(true); const field2 = createState( { test: 3, }, { persist: 'field2', }, ); return { field1, field2, }; }, Component() { return null; }, }); // states are serialized in creation order expect(exportState()).toEqual({field2: {test: 3}}); }); test('plugins support restoring state', async () => { const readyFn = jest.fn(); const {exportState, instance} = TestUtils.startPlugin( { plugin(c: PluginClient<{}, {}>) { const field1 = createState(1, {persist: 'field1'}); const field2 = createState(2); const field3 = createState(3, {persist: 'field3'}); c.onReady(readyFn); return { field1, field2, field3, }; }, Component() { return null; }, }, { initialState: {field1: 'a', field3: 'b'}, }, ); const {field1, field2, field3} = instance; expect(field1.get()).toBe('a'); expect(field2.get()).toBe(2); expect(field3.get()).toBe('b'); expect(exportState()).toEqual({field1: 'a', field3: 'b'}); expect(readyFn).toBeCalledTimes(1); }); test('plugins cannot use a persist key twice', async () => { expect(() => { TestUtils.startPlugin({ plugin() { const field1 = createState(1, {persist: 'test'}); const field2 = createState(2, {persist: 'test'}); return {field1, field2}; }, Component() { return null; }, }); }).toThrowErrorMatchingInlineSnapshot( `"Some other state is already persisting with key \\"test\\""`, ); }); test('plugins can have custom import handler', () => { const readyFn = jest.fn(); const {instance} = TestUtils.startPlugin( { plugin(client: PluginClient) { const field1 = createState(0); const field2 = createState(0); client.onImport((data) => { field1.set(data.a); field2.set(data.b); }); client.onReady(readyFn); return {field1, field2}; }, Component() { return null; }, }, { initialState: { a: 1, b: 2, }, }, ); expect(instance.field1.get()).toBe(1); expect(instance.field2.get()).toBe(2); expect(readyFn).toBeCalledTimes(1); }); test('plugins cannot combine import handler with persist option', async () => { expect(() => { TestUtils.startPlugin({ plugin(client: PluginClient) { const field1 = createState(1, {persist: 'f1'}); const field2 = createState(1, {persist: 'f2'}); client.onImport(() => {}); return {field1, field2}; }, Component() { return null; }, }); }).toThrowErrorMatchingInlineSnapshot( `"A custom onImport handler was defined for plugin 'TestPlugin', the 'persist' option of states f1, f2 should not be set."`, ); }); test('plugins can handle import errors', async () => { const restoreConsole = mockConsole(); let instance: any; try { instance = TestUtils.startPlugin( { plugin(client: PluginClient) { const field1 = createState(0); const field2 = createState(0); client.onImport(() => { throw new Error('Oops'); }); return {field1, field2}; }, Component() { return null; }, }, { initialState: { a: 1, b: 2, }, }, ).instance; // @ts-ignore expect(console.error.mock.calls).toMatchInlineSnapshot(` Array [ Array [ "An error occurred when importing data for plugin 'TestPlugin': 'Error: Oops", [Error: Oops], ], ] `); } finally { restoreConsole(); } expect(instance.field1.get()).toBe(0); expect(instance.field2.get()).toBe(0); }); test('plugins can have custom export handler', async () => { const {exportStateAsync} = TestUtils.startPlugin({ plugin(client: PluginClient) { const field1 = createState(0, {persist: 'field1'}); client.onExport(async () => { await sleep(10); return { b: 3, }; }); return {field1}; }, Component() { return null; }, }); expect(await exportStateAsync()).toEqual({b: 3}); }); test('plugins can have custom export handler that doesnt return', async () => { const {exportStateAsync} = TestUtils.startPlugin( { plugin(client: PluginClient) { const field1 = createState(0, {persist: 'field1'}); client.onExport(async () => { await sleep(10); field1.set(field1.get() + 1); }); return {field1}; }, Component() { return null; }, }, { initialState: { field1: 1, }, }, ); expect(await exportStateAsync()).toEqual({field1: 2}); }); test('plugins can receive deeplinks', async () => { const plugin = TestUtils.startPlugin({ plugin(client: PluginClient) { client.onDeepLink((deepLink) => { if (typeof deepLink === 'string') { field1.set(deepLink); } }); const field1 = createState('', {persist: 'test'}); return {field1}; }, Component() { return null; }, }); expect(plugin.instance.field1.get()).toBe(''); await plugin.triggerDeepLink('test'); expect(plugin.instance.field1.get()).toBe('test'); }); test('device plugins can receive deeplinks', async () => { const plugin = TestUtils.startDevicePlugin({ devicePlugin(client: DevicePluginClient) { client.onDeepLink((deepLink) => { if (typeof deepLink === 'string') { field1.set(deepLink); } }); const field1 = createState('', {persist: 'test'}); return {field1}; }, supportsDevice: () => true, Component() { return null; }, }); expect(plugin.instance.field1.get()).toBe(''); await plugin.triggerDeepLink('test'); expect(plugin.instance.field1.get()).toBe('test'); }); test('plugins can register menu entries', async () => { const plugin = TestUtils.startPlugin({ plugin(client: PluginClient) { const counter = createState(0); client.addMenuEntry( { action: 'createPaste', handler() { counter.set(counter.get() + 1); }, }, { label: 'Custom Action', topLevelMenu: 'Edit', handler() { counter.set(counter.get() + 3); }, }, ); return {counter}; }, Component() { return null; }, }); expect(plugin.instance.counter.get()).toBe(0); await plugin.triggerDeepLink('test'); plugin.triggerMenuEntry('createPaste'); plugin.triggerMenuEntry('Custom Action'); expect(plugin.instance.counter.get()).toBe(4); expect(plugin.flipperLib.enableMenuEntries).toBeCalledTimes(1); plugin.deactivate(); expect(() => { plugin.triggerMenuEntry('Non Existing'); }).toThrowErrorMatchingInlineSnapshot( `"No menu entry found with action: Non Existing"`, ); }); test('plugins can create pastes', async () => { const plugin = TestUtils.startPlugin({ plugin(client: PluginClient) { return { doIt() { client.createPaste('test'); }, }; }, Component() { return null; }, }); plugin.instance.doIt(); expect(plugin.flipperLib.createPaste).toBeCalledWith('test'); }); test('plugins support all methods by default', async () => { type Methods = { doit(): Promise<boolean>; }; const plugin = TestUtils.startPlugin({ plugin(client: PluginClient<{}, Methods>) { return { async checkEnabled() { return client.supportsMethod('doit'); }, }; }, Component() { return null; }, }); expect(await plugin.instance.checkEnabled()).toBeTruthy(); }); test('available methods can be overridden', async () => { type Methods = { doit(): Promise<boolean>; }; const plugin = TestUtils.startPlugin( { plugin(client: PluginClient<{}, Methods>) { return { async checkEnabled() { return client.supportsMethod('doit'); }, }; }, Component() { return null; }, }, { unsupportedMethods: ['doit'], }, ); expect(await plugin.instance.checkEnabled()).toBeFalsy(); }); test('GKs are supported', () => { const pluginModule = { plugin(client: PluginClient<{}, {}>) { return { isTest() { return client.GK('bla'); }, }; }, Component() { return null; }, }; { const plugin = TestUtils.startPlugin(pluginModule); expect(plugin.instance.isTest()).toBe(false); } { const plugin = TestUtils.startPlugin(pluginModule, {GKs: ['bla']}); expect(plugin.instance.isTest()).toBe(true); } { const plugin = TestUtils.startPlugin(pluginModule, {GKs: ['x']}); expect(plugin.instance.isTest()).toBe(false); } }); test('plugins can serialize dataSources', () => { const {instance, exportState} = TestUtils.startPlugin( { plugin(_client: PluginClient) { const ds = createDataSource([1, 2, 3], {persist: 'ds'}); return {ds}; }, Component() { return null; }, }, { initialState: { ds: [4, 5], }, }, ); expect(instance.ds.records()).toEqual([4, 5]); instance.ds.shift(1); instance.ds.append(6); expect(exportState()).toEqual({ ds: [5, 6], }); });
the_stack
import { isValid, validOutcode } from "postcode"; import { Outcode, OutcodeInterface, OutcodeTuple } from "./outcode"; import { QueryResult } from "pg"; import { query, ForeignColumn, RowExtract, Relationship, getClient, generateMethods, Relation, csvExtractor, } from "./base"; import QueryStream from "pg-query-stream"; import { getConfig } from "../../config/config"; import { InvalidGeolocationError, InvalidLimitError, InvalidRadiusError, } from "../lib/errors"; const { defaults } = getConfig(); const extractOnspdVal = csvExtractor( require("../../../data/onspd_schema.json") ); export interface PostcodeInterface { postcode: string; quality: number; eastings: number | null; northings: number | null; country: string; nhs_ha: string | null; longitude: number | null; latitude: number | null; european_electoral_region: string | null; primary_care_trust: string | null; region: string | null; lsoa: string | null; msoa: string | null; incode: string; outcode: string; parliamentary_constituency: string | null; admin_district: string | null; parish: string | null; admin_county: string | null; admin_ward: string | null; ced: string | null; ccg: string | null; nuts: string | null; codes: { admin_district: string; admin_county: string; admin_ward: string; parish: string; parliamentary_constituency: string; ccg: string; ccg_id: string; ced: string; nuts: string; lsoa: string | null; msoa: string | null; lau2: string | null; }; } export interface PostcodeTuple { id: number; postcode: string; pc_compact: string; quality: number; eastings: number; northings: number; country: string; nhs_ha: string; admin_county_id: string; admin_district_id: string; admin_ward_id: string; longitude: number; latitude: number; location: string; european_electoral_region: string; primary_care_trust: string; region: string; parish_id: string; lsoa: string; lsoa_id: string; msoa: string; msoa_id: string; nuts_id: string; nuts_code: string; incode: string; outcode: string; ccg_code: string; ced_id: string; ccg_id: string; constituency_id: string; parliamentary_constituency: string; admin_district: string; parish: string; admin_county: string; admin_ward: string; ced: string; ccg: string; nuts: string; } const relation: Relation = { relation: "postcodes", schema: { id: "SERIAL PRIMARY KEY", postcode: `VARCHAR(10) COLLATE "C"`, // C Provides desirable ordering pc_compact: `VARCHAR(9) COLLATE "C"`, // for pc autocomplete & partials quality: "INTEGER", eastings: "INTEGER", northings: "INTEGER", country: "VARCHAR(255)", nhs_ha: "VARCHAR(255)", admin_county_id: "VARCHAR(32)", admin_district_id: "VARCHAR(32)", admin_ward_id: "VARCHAR(32)", longitude: "DOUBLE PRECISION", latitude: "DOUBLE PRECISION", location: "GEOGRAPHY(Point, 4326)", european_electoral_region: "VARCHAR(255)", primary_care_trust: "VARCHAR(255)", region: "VARCHAR(255)", parish_id: "VARCHAR(32)", lsoa_id: "VARCHAR(32)", msoa_id: "VARCHAR(32)", nuts_id: "VARCHAR(32)", incode: "VARCHAR(5)", outcode: "VARCHAR(5)", ccg_id: "VARCHAR(32)", ced_id: "VARCHAR(32)", constituency_id: "VARCHAR(32)", }, indexes: [ { unique: true, column: "postcode", }, { unique: true, column: "pc_compact", }, { unique: true, column: "pc_compact", opClass: "varchar_pattern_ops", }, { type: "GIST", column: "location", }, { column: "outcode", }, ], }; const methods = generateMethods(relation); const relationships: Relationship[] = [ { table: "districts", key: "admin_district_id", foreignKey: "code", }, { table: "parishes", key: "parish_id", foreignKey: "code", }, { table: "counties", key: "admin_county_id", foreignKey: "code", }, { table: "wards", key: "admin_ward_id", foreignKey: "code", }, { table: "ceds", key: "ced_id", foreignKey: "code", }, { table: "ccgs", key: "ccg_id", foreignKey: "code", }, { table: "constituencies", key: "constituency_id", foreignKey: "code", }, { table: "nuts", key: "nuts_id", foreignKey: "code", }, { table: "msoa", key: "msoa_id", foreignKey: "code", }, { table: "lsoa", key: "lsoa_id", foreignKey: "code", }, ]; const joinString: string = Object.freeze( relationships .map((r) => { return ` LEFT OUTER JOIN ${r.table} ON postcodes.${r.key}=${r.table}.${r.foreignKey} `; }) .join(" ") ); const foreignColumns: ForeignColumn[] = [ { field: "constituencies.name", as: "parliamentary_constituency", }, { field: "districts.name", as: "admin_district", }, { field: "parishes.name", as: "parish", }, { field: "counties.name", as: "admin_county", }, { field: "lsoa.name", as: "lsoa", }, { field: "msoa.name", as: "msoa", }, { field: "wards.name", as: "admin_ward", }, { field: "ceds.name", as: "ced", }, { field: "ccgs.ccg19cdh", as: "ccg_code", }, { field: "ccgs.name", as: "ccg", }, { field: "nuts.name", as: "nuts", }, { field: "nuts.nuts_code", as: "nuts_code", }, ]; const columnString: string = foreignColumns .map((elem) => `${elem.field} as ${elem.as}`) .join(","); const idCache: Record<string, number[]> = {}; const findQuery = ` SELECT postcodes.*, ${columnString} FROM postcodes ${joinString} WHERE pc_compact=$1 `; const find = async (postcode: string): Promise<PostcodeTuple | null> => { if (postcode == null) postcode = ""; postcode = postcode.trim().toUpperCase(); if (!isValid(postcode)) return null; const result = await query<PostcodeTuple>(findQuery, [ postcode.replace(/\s/g, ""), ]); if (result.rows.length === 0) return null; return result.rows[0]; }; const loadPostcodeIds = async (outcode?: string): Promise<any> => { const client = await getClient(); const params: string[] = []; let countQuery = "SELECT count(id) FROM postcodes"; let idQuery = "SELECT id FROM postcodes"; if (outcode) { countQuery += " WHERE outcode = $1"; idQuery += " WHERE outcode = $1"; params.push(outcode.replace(/\s/g, "").toUpperCase()); } let count: number; try { const result = await client.query<{ count: number }>(countQuery, params); count = result.rows[0].count; if (count === 0) return null; } catch (error) { client.release(); throw error; } return new Promise((resolve, reject) => { let i = 0; const idStore = new Array(count); client .query(new QueryStream(idQuery, params)) .on("end", () => { idCache[outcode] = idStore; client.release(); resolve(idStore); }) .on("error", (error) => { client.release(); reject(error); }) .on("data", (data) => { idStore[i] = data.id; i++; }); }); }; const random = async (outcode?: string): Promise<PostcodeTuple | null> => { let ids = idCache[outcode]; if (!ids) ids = await loadPostcodeIds(outcode); return randomFromIds(ids); }; const findByIdQuery = ` SELECT postcodes.*, ${columnString} FROM postcodes ${joinString} WHERE id=$1 `; // Use an in memory array of IDs to retrieve random postcode const randomFromIds = async (ids: number[]): Promise<PostcodeTuple> => { const length = ids.length; const randomId = ids[Math.floor(Math.random() * length)]; const result = await query<PostcodeTuple>(findByIdQuery, [randomId]); if (result.rows.length === 0) return null; return result.rows[0]; }; interface SearchOptions { limit?: string; postcode: string; } // Parses postcode search options, returns object with limit const parseSearchOptions = (options: SearchOptions): { limit: number } => { let limit = parseInt(options.limit, 10); if (isNaN(limit) || limit < 1) limit = defaults.search.limit.DEFAULT; if (limit > defaults.search.limit.MAX) limit = defaults.search.limit.MAX; return { limit }; }; const whitespaceRe = /\s+/g; /* * Search for partial/complete postcode matches * Search Methodology below: * 1) Check if string is feasible outcode, then search by that outcode * 2) Check if string is space separated, then perform space-sensitive search * 3) If above fail, perform space-insensitive search */ export const search = async ( options: SearchOptions ): Promise<PostcodeTuple[]> => { const postcode = options.postcode.toUpperCase().trim(); const pcCompact = postcode.replace(whitespaceRe, ""); // Returns substring matches on postcode const extractPartialMatches = (r: PostcodeTuple[]): PostcodeTuple[] => r.filter((p) => p.pc_compact.includes(pcCompact)); // Parses and formats results, includes: // - returns null if empty array // - filters for partial postcode matches // - if full match detected, only return full match const parse = ({ rows }: QueryResult<PostcodeTuple>) => { const matches = extractPartialMatches(rows); if (matches.length === 0) return null; const exactMatches = matches.filter((r) => r.pc_compact === pcCompact); if (exactMatches.length > 0) return exactMatches; return matches; }; if (validOutcode(postcode)) { const r = await searchPostcode({ ...options, query: `${postcode} ` }); if (extractPartialMatches(r.rows).length > 0) return parse(r); } if (postcode.match(/^\w+\s+\w+$/)) { const r = await searchPostcode({ ...options, query: postcode.split(/\s+/).join(" "), }); if (extractPartialMatches(r.rows).length > 0) return parse(r); } const result = await searchPcCompact({ ...options, query: postcode }); return parse(result); }; interface PrivateSearchOptions extends SearchOptions { query: string; } const searchQuery = ` SELECT postcodes.*, ${columnString} FROM postcodes ${joinString} WHERE postcode >= $1 ORDER BY postcode ASC LIMIT $2 `; // Space sensitive search for postcode (uses postcode column/btree) const searchPostcode = async (options: PrivateSearchOptions) => { const postcode = options.query; const { limit } = parseSearchOptions(options); return query<PostcodeTuple>(searchQuery, [postcode, limit]); }; const pccompactSearchQuery = ` SELECT postcodes.*, ${columnString} FROM postcodes ${joinString} WHERE pc_compact >= $1 ORDER BY pc_compact ASC LIMIT $2 `; // Space insensitive search for postcode (uses pc_compact column/btree) const searchPcCompact = (options: PrivateSearchOptions) => { const postcode = options.query; const { limit } = parseSearchOptions(options); return query<PostcodeTuple>(pccompactSearchQuery, [postcode, limit]); }; const nearestPostcodeQuery = ` SELECT postcodes.*, ST_Distance( location, ST_GeographyFromText('POINT(' || $1 || ' ' || $2 || ')') ) AS distance, ${columnString} FROM postcodes ${joinString} WHERE ST_DWithin( location, ST_GeographyFromText('POINT(' || $1 || ' ' || $2 || ')'), $3 ) ORDER BY distance ASC, postcode ASC LIMIT $4 `; export interface NearestPostcodeTuple extends PostcodeTuple { distance: number; } export interface NearestPostcodesOptions { longitude: string; latitude: string; limit?: string; radius?: string; widesearch?: boolean; wideSearch?: boolean; } const nearestPostcodes = async ( options: NearestPostcodesOptions ): Promise<NearestPostcodeTuple[]> => { const DEFAULT_RADIUS = defaults.nearest.radius.DEFAULT; const MAX_RADIUS = defaults.nearest.radius.MAX; const DEFAULT_LIMIT = defaults.nearest.limit.DEFAULT; const MAX_LIMIT = defaults.nearest.limit.MAX; let limit = DEFAULT_LIMIT; if (options.limit) { limit = parseInt(options.limit, 10); if (isNaN(limit)) throw new InvalidLimitError(); } if (limit > MAX_LIMIT) limit = MAX_LIMIT; const longitude = parseFloat(options.longitude); if (isNaN(longitude)) throw new InvalidGeolocationError(); const latitude = parseFloat(options.latitude); if (isNaN(latitude)) throw new InvalidGeolocationError(); let radius = DEFAULT_RADIUS; if (options.radius) { radius = parseFloat(options.radius); if (isNaN(radius)) throw new InvalidRadiusError(); } if (radius > MAX_RADIUS) radius = MAX_RADIUS; // If a wideSearch query is requested, derive a suitable range which // guarantees postcode results over a much wider area if (options.wideSearch || options.widesearch) { if (limit > DEFAULT_LIMIT) limit = DEFAULT_LIMIT; const maxRange = await deriveMaxRange(options); const { rows } = await query<NearestPostcodeTuple>(nearestPostcodeQuery, [ longitude, latitude, maxRange, limit, ]); if (rows.length === 0) return null; return rows; } const result = await query<NearestPostcodeTuple>(nearestPostcodeQuery, [ longitude, latitude, radius, limit, ]); if (result.rows.length === 0) return null; return result.rows; }; const nearestPostcodeCount = ` SELECT ST_Distance( location, ST_GeographyFromText('POINT(' || $1 || ' ' || $2 || ')') ) AS distance FROM postcodes WHERE ST_DWithin( location, ST_GeographyFromText('POINT(' || $1 || ' ' || $2 || ')'), $3 ) LIMIT $4 `; const START_RANGE = 500; // 0.5km const MAX_RANGE = 20000; // 20km const SEARCH_LIMIT = 10; const INCREMENT = 1000; interface QueryBoundOptions extends NearestPostcodesOptions { lowerBound?: number; upperBound?: number; } const deriveMaxRange = async ( options: NearestPostcodesOptions ): Promise<number> => { const queryBound = async ( { longitude, latitude }: QueryBoundOptions, range: number ): Promise<number> => { const result = await query<NearestPostcodeTuple>(nearestPostcodeCount, [ longitude, latitude, range, SEARCH_LIMIT, ]); return result.rowCount; }; const params: QueryBoundOptions = { ...options }; if (!params.lowerBound) { params.lowerBound = START_RANGE; const count = await queryBound(params, START_RANGE); if (count < SEARCH_LIMIT) return deriveMaxRange(params); return params.lowerBound; } if (!params.upperBound) { params.upperBound = MAX_RANGE; const count = await queryBound(params, MAX_RANGE); if (count === 0) return null; return deriveMaxRange(params); } params.lowerBound += INCREMENT; if (params.lowerBound > MAX_RANGE) return null; const c = await queryBound(params, params.lowerBound); if (c < SEARCH_LIMIT) return deriveMaxRange(params); return params.lowerBound; }; const attributesQuery = []; attributesQuery.push(` array( SELECT DISTINCT districts.name FROM postcodes LEFT OUTER JOIN districts ON postcodes.admin_district_id = districts.code WHERE outcode=$1 AND districts.name IS NOT NULL ) as admin_district `); attributesQuery.push(` array( SELECT DISTINCT parishes.name FROM postcodes LEFT OUTER JOIN parishes ON postcodes.parish_id = parishes.code WHERE outcode=$1 AND parishes.name IS NOT NULL ) as parish `); attributesQuery.push(` array( SELECT DISTINCT counties.name FROM postcodes LEFT OUTER JOIN counties ON postcodes.admin_county_id = counties.code WHERE outcode=$1 AND counties.name IS NOT NULL ) as admin_county `); attributesQuery.push(` array( SELECT DISTINCT wards.name FROM postcodes LEFT OUTER JOIN wards ON postcodes.admin_ward_id = wards.code WHERE outcode=$1 AND wards.name IS NOT NULL ) as admin_ward `); attributesQuery.push(` array( SELECT DISTINCT country FROM postcodes WHERE outcode=$1 ) as country `); const outcodeQuery = ` SELECT outcode, avg(northings) as northings, avg(eastings) as eastings, avg(ST_X(location::geometry)) as longitude, avg(ST_Y(location::geometry)) as latitude, ${attributesQuery.join(",")} FROM postcodes WHERE outcode=$1 GROUP BY outcode `; const outcodeAttributes = [ "admin_district", "parish", "admin_county", "admin_ward", ]; const toArray = (i: string[] | [null]) => { if (i.length === 1 && i[0] === null) return []; return i; }; interface OutcodeTupleOutput { outcode: string; longitude: number | null; latitude: number | null; northings: number; eastings: number; admin_district: string[] | [null]; parish: string[] | [null]; admin_county: string[] | [null]; admin_ward: string[] | [null]; country: string[] | [null]; } const findOutcode = async (o: string): Promise<OutcodeInterface | null> => { const outcode = o.trim().toUpperCase(); if (!validOutcode(outcode) && outcode !== "GIR") return null; const { rows } = await query<OutcodeTupleOutput>(outcodeQuery, [outcode]); if (rows.length === 0) return null; const result = rows[0]; result.admin_county = toArray(result.admin_county); result.admin_district = toArray(result.admin_district); result.parish = toArray(result.parish); result.admin_ward = toArray(result.admin_ward); result.country = toArray(result.country); return result; }; const toJson = function ( p: PostcodeTuple ): PostcodeInterface | NearestPostcodeTuple { return { postcode: p.postcode, quality: p.quality, eastings: p.eastings, northings: p.northings, country: p.country, nhs_ha: p.nhs_ha, longitude: p.longitude, latitude: p.latitude, european_electoral_region: p.european_electoral_region, primary_care_trust: p.primary_care_trust, region: p.region, lsoa: p.lsoa, msoa: p.msoa, incode: p.incode, outcode: p.outcode, parliamentary_constituency: p.parliamentary_constituency, admin_district: p.admin_district, parish: p.parish, admin_county: p.admin_county, admin_ward: p.admin_ward, ced: p.ced, ccg: p.ccg, nuts: p.nuts, codes: { admin_district: p.admin_district_id, admin_county: p.admin_county_id, admin_ward: p.admin_ward_id, parish: p.parish_id, parliamentary_constituency: p.constituency_id, ccg: p.ccg_id, ccg_id: p.ccg_code, ced: p.ced_id, nuts: p.nuts_code, lsoa: p.lsoa_id, msoa: p.msoa_id, lau2: p.nuts_id, }, // Insert distance if present //@ts-ignore ...(p.distance !== undefined && { distance: p.distance }), }; }; const setupTable = async (filepath: string) => { await methods.createRelation(); await methods.clear(); await seedPostcodes(filepath); await methods.populateLocation(); await methods.createIndexes(); }; const seedPostcodes = async (filepath: string) => { const pcts = require("../../../data/pcts.json"); const nhsHa = require("../../../data/nhsHa.json"); const regions = require("../../../data/regions.json"); const countries = require("../../../data/countries.json"); const european_registers = require("../../../data/european_registers.json"); const ONSPD_COL_MAPPINGS = Object.freeze([ { column: "postcode", method: (row: RowExtract) => row.extract("pcds") }, { column: "pc_compact", method: (row) => row.extract("pcds").replace(/\s/g, ""), }, { column: "eastings", method: (row) => row.extract("oseast1m") }, { column: "northings", method: (row) => row.extract("osnrth1m") }, { column: "longitude", method: (row) => { const eastings = row.extract("oseast1m"); return eastings === "" ? null : row.extract("long"); }, }, { column: "latitude", method: (row) => { const northings = row.extract("osnrth1m"); return northings === "" ? null : row.extract("lat"); }, }, { column: "country", method: (row) => countries[row.extract("ctry")] }, { column: "nhs_ha", method: (row) => nhsHa[row.extract("oshlthau")] }, { column: "admin_county_id", method: (row) => row.extract("oscty") }, { column: "admin_district_id", method: (row) => row.extract("oslaua") }, { column: "admin_ward_id", method: (row) => row.extract("osward") }, { column: "parish_id", method: (row) => row.extract("parish") }, { column: "quality", method: (row) => row.extract("osgrdind") }, { column: "constituency_id", method: (row) => row.extract("pcon") }, { column: "european_electoral_region", method: (row) => european_registers[row.extract("eer")], }, { column: "region", method: (row) => regions[row.extract("rgn")] }, { column: "primary_care_trust", method: (row) => pcts[row.extract("pct")] }, { column: "lsoa_id", method: (row) => row.extract("lsoa11") }, { column: "msoa_id", method: (row) => row.extract("msoa11") }, { column: "nuts_id", method: (row) => row.extract("nuts") }, { column: "incode", method: (row) => row.extract("pcds").split(" ")[1] }, { column: "outcode", method: (row) => row.extract("pcds").split(" ")[0] }, { column: "ced_id", method: (row) => row.extract("ced") }, { column: "ccg_id", method: (row) => row.extract("ccg") }, ]); await methods.csvSeed({ filepath: [filepath], transform: (row: RowExtract) => { row.extract = (code: string) => extractOnspdVal(row, code); // Append csv extraction logic if (row.extract("pcd") === "pcd") return null; // Skip if header if (row.extract("doterm") && row.extract("doterm").length !== 0) return null; // Skip row if terminated return ONSPD_COL_MAPPINGS.map((elem) => elem.method(row)); }, columns: ONSPD_COL_MAPPINGS.map((elem) => elem.column), }); }; export const Postcode = { ...methods, find, random, search, searchPostcode, searchPcCompact, deriveMaxRange, findOutcode, toJson, setupTable, seedPostcodes, nearestPostcodes, loadPostcodeIds, randomFromIds, idCache, };
the_stack
import * as vscode from "vscode"; import type { Argument, Input, InputOr, RegisterOr, SetInput } from "."; import { Context, Direction, moveWhile, Positions, prompt, SelectionBehavior, Selections, switchRun } from "../api"; import { PerEditorState } from "../state/editors"; import { Mode } from "../state/modes"; import type { Register } from "../state/registers"; import { CharSet, getCharacters } from "../utils/charset"; import { AutoDisposable } from "../utils/disposables"; import { ArgumentError, EmptySelectionsError } from "../utils/errors"; import { unsafeSelections } from "../utils/misc"; import { SettingsValidator } from "../utils/settings-validator"; import { TrackedSelection } from "../utils/tracked-selection"; /** * Interacting with selections. */ declare module "./selections"; /** * Copy selections text. * * @keys `y` (normal) */ export function saveText( document: vscode.TextDocument, selections: readonly vscode.Selection[], register: RegisterOr<"dquote", Register.Flags.CanWrite>, ) { register.set(selections.map(document.getText.bind(document))); } /** * Save selections. * * @keys `s-z` (normal) */ export function save( _: Context, document: vscode.TextDocument, selections: readonly vscode.Selection[], register: RegisterOr<"caret", Register.Flags.CanWriteSelections>, style?: Argument<object>, until?: Argument<AutoDisposable.Event[]>, untilDelay: Argument<number> = 100, ) { const trackedSelections = TrackedSelection.fromArray(selections, document); let trackedSelectionSet: TrackedSelection.Set; if (typeof style === "object") { const validator = new SettingsValidator(), renderOptions = Mode.decorationObjectToDecorationRenderOptions(style, validator); validator.throwErrorIfNeeded(); renderOptions.rangeBehavior = vscode.DecorationRangeBehavior.ClosedOpen; trackedSelectionSet = new TrackedSelection.StyledSet(trackedSelections, _.getState(), renderOptions); trackedSelectionSet.flags |= TrackedSelection.Flags.EmptyMoves; } else { trackedSelectionSet = new TrackedSelection.Set(trackedSelections, document); } const disposable = _.extension .createAutoDisposable() .addNotifyingDisposable(trackedSelectionSet) .addDisposable(new vscode.Disposable(() => { if (register.canReadSelections() && register.getSelectionSet() === trackedSelectionSet) { register.replaceSelectionSet()!.dispose(); } })); if (Array.isArray(until)) { if (untilDelay <= 0) { until.forEach((until) => disposable.disposeOnUserEvent(until, _)); } else { setTimeout(() => { try { _.getState(); } catch { // Editor has gone out of view. return disposable.dispose(); } until.forEach((until) => disposable.disposeOnUserEvent(until, _)); }, untilDelay); } } register.replaceSelectionSet(trackedSelectionSet)?.dispose(); } /** * Restore selections. * * @keys `z` (normal) */ export function restore( _: Context, register: RegisterOr<"caret", Register.Flags.CanReadSelections>, ) { const selectionSet = register.getSelectionSet(); if (selectionSet === undefined) { throw new EmptySelectionsError(`no selections are saved in register "${register.name}"`); } return _.switchToDocument(selectionSet.document, /* alsoFocusEditor= */ true) .then(() => _.selections = selectionSet.restore()); } /** * Combine register selections with current ones. * * @keys `a-z` (normal) * * The following keybinding is also available: * * | Keybinding | Command | * | ---------------- | -------------------------------------------------------- | * | `s-a-z` (normal) | `[".selections.restore.withCurrent", { reverse: true }]` | * * See https://github.com/mawww/kakoune/blob/master/doc/pages/keys.asciidoc#marks */ export async function restore_withCurrent( _: Context, document: vscode.TextDocument, register: RegisterOr<"caret", Register.Flags.CanReadSelections>, reverse: Argument<boolean> = false, ) { const savedSelections = register.getSelections(); EmptySelectionsError.throwIfRegisterIsEmpty(savedSelections, register.name); let from = savedSelections, add = _.selections; if (reverse) { from = _.selections; add = savedSelections; } const type = await prompt.one([ ["a", "Append lists"], ["u", "Union"], ["i", "Intersection"], ["<", "Select leftmost cursor"], [">", "Select rightmost cursor"], ["+", "Select longest"], ["-", "Select shortest"], ]); if (typeof type === "string") { return; } if (type === 0) { _.selections = from.concat(add); return; } if (from.length !== add.length) { throw new Error("the current and register selections have different sizes"); } const selections = [] as vscode.Selection[]; for (let i = 0; i < from.length; i++) { const a = from[i], b = add[i]; switch (type) { case 1: { const anchor = a.start.isBefore(b.start) ? a.start : b.start, active = a.end.isAfter(b.end) ? a.end : b.end; selections.push(new vscode.Selection(anchor, active)); break; } case 2: { const anchor = a.start.isAfter(b.start) ? a.start : b.start, active = a.end.isBefore(b.end) ? a.end : b.end; selections.push(new vscode.Selection(anchor, active)); break; } case 3: if (a.active.isBeforeOrEqual(b.active)) { selections.push(a); } else { selections.push(b); } break; case 4: if (a.active.isAfterOrEqual(b.active)) { selections.push(a); } else { selections.push(b); } break; case 5: { const aLength = document.offsetAt(a.end) - document.offsetAt(a.start), bLength = document.offsetAt(b.end) - document.offsetAt(b.start); if (aLength > bLength) { selections.push(a); } else { selections.push(b); } break; } case 6: { const aLength = document.offsetAt(a.end) - document.offsetAt(a.start), bLength = document.offsetAt(b.end) - document.offsetAt(b.start); if (aLength < bLength) { selections.push(a); } else { selections.push(b); } break; } } } _.selections = selections; } const pipeHistory: string[] = []; /** * Pipe selections. * * Run the specified command or code with the contents of each selection, and * save the result to a register. * * @keys `a-|` (normal) * * See https://github.com/mawww/kakoune/blob/master/doc/pages/keys.asciidoc#changes-through-external-programs * * #### Additional commands * * | Title | Identifier | Keybinding | Commands | * | ------------------- | -------------- | -------------- | --------------------------------------------------------------------------- | * | Pipe and replace | `pipe.replace` | `|` (normal) | `[".selections.pipe"], [".edit.insert", { register: "|" }]` | * | Pipe and append | `pipe.append` | `!` (normal) | `[".selections.pipe"], [".edit.insert", { register: "|", where: "end" }]` | * | Pipe and prepend | `pipe.prepend` | `a-!` (normal) | `[".selections.pipe"], [".edit.insert", { register: "|", where: "start" }]` | */ export async function pipe( _: Context, register: RegisterOr<"pipe", Register.Flags.CanWrite>, inputOr: InputOr<string>, ) { const input = await inputOr(() => prompt({ prompt: "Expression", validateInput(value) { try { switchRun.validate(value); } catch (e) { return e?.message ?? `${e}`; } }, history: pipeHistory, }, _)); const selections = _.selections, document = _.document, selectionsStrings = selections.map((selection) => document.getText(selection)); const results = await Promise.all(_.run((_) => selectionsStrings.map((string, i, strings) => switchRun(input!, { $: string, $$: strings, i, n: strings.length }), ))); const strings = results.map((result) => { if (result === null) { return "null"; } if (result === undefined) { return ""; } if (typeof result === "string") { return result; } if (typeof result === "number" || typeof result === "boolean") { return result.toString(); } if (typeof result === "object") { return JSON.stringify(result); } throw new Error("invalid returned value by expression"); }); await register.set(strings); } const filterHistory: string[] = []; /** * Filter selections. * * @keys `$` (normal) * * #### Variants * * | Title | Identifier | Keybinding | Commands | * | -------------------------- | ----------------------- | ------------------ | -------------------------------------------------------------- | * | Keep matching selections | `filter.regexp` | `a-k` (normal) | `[".selections.filter", { defaultInput: "/" }]` | * | Clear matching selections | `filter.regexp.inverse` | `s-a-k` (normal) | `[".selections.filter", { defaultInput: "/", inverse: true }]` | * | Clear secondary selections | `clear.secondary` | `space` (normal) | `[".selections.filter", { input: "i === count" }]` | * | Clear main selections | `clear.main` | `a-space` (normal) | `[".selections.filter", { input: "i !== count" }]` | */ export function filter( _: Context, input: Input<string>, setInput: SetInput<string>, defaultInput?: Argument<string>, inverse: Argument<boolean> = false, interactive: Argument<boolean> = true, count: number = 0, ) { const document = _.document, strings = _.selections.map((selection) => document.getText(selection)); return prompt.manipulateSelectionsInteractively(_, input, setInput, interactive, { prompt: "Expression", validateInput(value) { try { switchRun.validate(value); } catch (e) { return e?.message ?? `${e}`; } }, value: defaultInput, valueSelection: defaultInput ? [defaultInput.length, defaultInput.length] : undefined, history: filterHistory, }, (input, selections) => { return Selections.filter.byIndex(async (i) => { const context = { $: strings[i], $$: strings, i, n: strings.length, count }; try { return !!(await switchRun(input, context)) !== inverse; } catch { return inverse; } }, selections).then(Selections.set).then(() => input); }); } /** * Select within selections. * * @keys `s` (normal) */ export function select( _: Context, interactive: Argument<boolean> = true, input: Input<string | RegExp>, setInput: SetInput<RegExp>, ) { return prompt.manipulateSelectionsInteractively( _, input, setInput, interactive, prompt.regexpOpts("mu"), (input, selections) => { if (typeof input === "string") { input = new RegExp(input, "mu"); } Selections.set(Selections.bottomToTop(Selections.selectWithin(input, selections))); return Promise.resolve(input); }, ); } /** * Split selections. * * @keys `s-s` (normal) */ export function split( _: Context, excludeEmpty: Argument<boolean> = false, interactive: Argument<boolean> = true, input: Input<string | RegExp>, setInput: SetInput<RegExp>, ) { return prompt.manipulateSelectionsInteractively( _, input, setInput, interactive, prompt.regexpOpts("mu"), (input, selections) => { if (typeof input === "string") { input = new RegExp(input, "mu"); } let split = Selections.split(input, selections); if (excludeEmpty) { split = split.filter((s) => !s.isEmpty); } Selections.set(Selections.bottomToTop(split)); return Promise.resolve(input); }, ); } /** * Split selections at line boundaries. * * @keys `a-s` (normal) */ export function splitLines( _: Context, document: vscode.TextDocument, selections: readonly vscode.Selection[], repetitions: number, excludeEol: Argument<boolean> = false, ) { const newSelections = [] as vscode.Selection[], lineEnd = excludeEol ? Positions.lineEnd : Positions.lineBreak; for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i], start = selection.start, end = selection.end, startLine = start.line, endLine = end.line, isReversed = selection.isReversed; if (startLine === endLine) { newSelections.push(selection); return; } // Add start line. newSelections.push( Selections.fromStartEnd(start, lineEnd(startLine, document), isReversed, document), ); // Add intermediate lines. for (let line = startLine + repetitions; line < endLine; line += repetitions) { const start = Positions.lineStart(line), end = lineEnd(line, document); newSelections.push(Selections.fromStartEnd(start, end, isReversed, document)); } // Add end line. if (endLine % repetitions === 0 && end.character > 0) { newSelections.push( Selections.fromStartEnd(Positions.lineStart(endLine), end, isReversed, document), ); } } Selections.set(Selections.bottomToTop(newSelections)); } /** * Expand to lines. * * Expand selections to contain full lines (including end-of-line characters). * * @keys `a-x` (normal) */ export function expandToLines(_: Context) { return Selections.update.byIndex((_, selection, document) => { const start = selection.start, end = selection.end; // Move start to line start and end to include line break. const newStart = start.with(undefined, 0); let newEnd: vscode.Position; if (end.character === 0) { // End is next line start, which means the selection already includes the // line break of last line. newEnd = end; } else if (end.line + 1 < document.lineCount) { // Move end to the next line start to include the line break. newEnd = new vscode.Position(end.line + 1, 0); } else { // End is at the last line, so try to include all text. const textLen = document.lineAt(end.line).text.length; newEnd = end.with(undefined, textLen); } // After expanding, the selection should be in the same direction as before. return Selections.fromStartEnd(newStart, newEnd, selection.isReversed); }); } /** * Trim lines. * * Trim selections to only contain full lines (from start to line break). * * @keys `s-a-x` (normal) */ export function trimLines(_: Context) { return Selections.update.byIndex((_, selection) => { const start = selection.start, end = selection.end; // If start is not at line start, move it to the next line start. const newStart = start.character === 0 ? start : new vscode.Position(start.line + 1, 0); // Move end to the line start, so that the selection ends with a line break. const newEnd = new vscode.Position(end.line, 0); if (newStart.isAfterOrEqual(newEnd)) { return undefined; // No full line contained. } // After trimming, the selection should be in the same direction as before. // Except when selecting only one empty line in non-directional mode, prefer // to keep the selection facing forward. if (selection.isReversed && newStart.line + 1 !== newEnd.line) { return new vscode.Selection(newEnd, newStart); } else { return new vscode.Selection(newStart, newEnd); } }); } /** * Trim whitespace. * * Trim whitespace at beginning and end of selections. * * @keys `_` (normal) */ export function trimWhitespace(_: Context) { const blank = getCharacters(CharSet.Blank, _.document), isBlank = (character: string) => blank.includes(character); return Selections.update.byIndex((_, selection, document) => { const firstCharacter = selection.start, lastCharacter = selection.end; const start = moveWhile.forward(isBlank, firstCharacter, document), end = moveWhile.backward(isBlank, lastCharacter, document); if (start.isAfter(end)) { return undefined; } return Selections.fromStartEnd(start, end, selection.isReversed); }); } /** * Reduce selections to their cursor. * * @param where Which edge each selection should be reduced to; defaults to * "active". * * @keys `;` (normal) * * #### Variant * * | Title | Identifier | Keybinding | Command | * | ------------------------------- | -------------- | ---------------- | --------------------------------------------------------- | * | Reduce selections to their ends | `reduce.edges` | `s-a-s` (normal) | `[".selections.reduce", { where: "both", empty: false }]` | */ export function reduce( _: Context, where: Argument<"active" | "anchor" | "start" | "end" | "both"> = "active", empty: Argument<boolean> = true, ) { ArgumentError.validate( "where", ["active", "anchor", "start", "end", "both"].includes(where), `"where" must be "active", "anchor", "start", "end", "both", or undefined`, ); if (empty && _.selectionBehavior !== SelectionBehavior.Character) { if (where !== "both") { Selections.update.byIndex((_, selection) => Selections.empty(selection[where])); } else { Selections.set(_.selections.flatMap((selection) => { if (selection.isEmpty) { return [selection]; } return [ Selections.empty(selection.active), Selections.empty(selection.anchor), ]; })); } return; } const takeWhere = (selection: vscode.Selection, prop: Exclude<typeof where, "both">) => { if (selection.isEmpty) { return selection; } let start = selection[prop], end: vscode.Position; if (start === selection.end && !start.isEqual(selection.start)) { end = start; start = Positions.previous(start)!; } else { end = Positions.next(start) ?? start; } return Selections.from(start, end); }; if (where !== "both") { Selections.update.byIndex((_, selection) => takeWhere(selection, where)); return; } Selections.set(_.selections.flatMap((selection) => { if (selection.isEmpty || Selections.isNonDirectional(selection)) { return [selection]; } return [ takeWhere(selection, "active"), takeWhere(selection, "anchor"), ]; })); } /** * Change direction of selections. * * @param direction If unspecified, flips each direction. Otherwise, ensures * that all selections face the given direction. * * @keys `a-;` (normal) * * #### Variants * * | Title | Identifier | Keybinding | Command | * | ------------------- | -------------- | -------------- | ---------------------------------------------------- | * | Forward selections | `faceForward` | `a-:` (normal) | `[".selections.changeDirection", { direction: 1 }]` | * | Backward selections | `faceBackward` | | `[".selections.changeDirection", { direction: -1 }]` | */ export function changeDirection(_: Context, direction?: Direction) { switch (direction) { case Direction.Backward: Selections.update.byIndex((_, selection) => selection.isReversed || selection.isEmpty || Selections.isNonDirectional(selection) ? selection : new vscode.Selection(selection.end, selection.start)); break; case Direction.Forward: Selections.update.byIndex((_, selection) => selection.isReversed ? new vscode.Selection(selection.start, selection.end) : selection); break; default: Selections.update.byIndex((_, selection) => selection.isEmpty || Selections.isNonDirectional(selection) ? selection : new vscode.Selection(selection.active, selection.anchor)); break; } } /** * Copy selections below. * * @keys `s-c` (normal) * * #### Variant * * | Title | Identifier | Keybinding | Command | * | --------------------- | ------------ | ---------------- | ----------------------------------------- | * | Copy selections above | `copy.above` | `s-a-c` (normal) | `[".selections.copy", { direction: -1 }]` | */ export function copy( _: Context, document: vscode.TextDocument, selections: readonly vscode.Selection[], repetitions: number, direction = Direction.Forward, ) { const newSelections = [] as vscode.Selection[], lineCount = document.lineCount; for (const selection of selections) { const activeLine = Selections.activeLine(selection); let currentLine = activeLine + direction; for (let i = 0; i < repetitions;) { if (currentLine < 0 || currentLine >= lineCount) { break; } const copiedSelection = tryCopySelection(document, selection, currentLine); if (copiedSelection === undefined) { currentLine += direction; continue; } newSelections.push(copiedSelection); i++; currentLine = direction === Direction.Backward ? copiedSelection.end.line - 1 : copiedSelection.start.line + 1; } } newSelections.push(...selections); Selections.set(newSelections); } /** * Merge contiguous selections. * * @keys `a-_` (normal) */ export function merge(_: Context) { Selections.set(Selections.mergeConsecutive(Selections.current)); } /** * Open selected file. */ export async function open(_: Context) { const basePath = vscode.Uri.joinPath(_.document.uri, ".."); await Promise.all( Selections.map((text) => vscode.workspace .openTextDocument(vscode.Uri.joinPath(basePath, text)) .then(vscode.window.showTextDocument), ), ); } const indicesToken = PerEditorState.registerState<AutoDisposable>(/* isDisposable= */ true); /** * Toggle selection indices. * * @keys `enter` (normal) * * #### Variants * * | Title | Identifier | Command | * | ---------------------- | ------------- | --------------------------------------------------- | * | Show selection indices | `showIndices` | `[".selections.toggleIndices", { display: true }]` | * | Hide selection indices | `hideIndices` | `[".selections.toggleIndices", { display: false }]` | */ export function toggleIndices( _: Context, display: Argument<boolean | undefined> = undefined, until: Argument<AutoDisposable.Event[]> = [], ) { const editorState = _.getState(); let disposable = editorState.get(indicesToken); if (disposable !== undefined) { // Indices already exist; remove them. if (display !== true) { editorState.store(indicesToken, undefined); disposable.dispose(); } return; } // Indices do not exist yet; add them. if (display === false) { return; } const indicesDecorationType = vscode.window.createTextEditorDecorationType({ after: { color: new vscode.ThemeColor("textLink.activeForeground"), margin: "0 0 0 20px", }, isWholeLine: true, }); function onDidChangeSelection(editor: vscode.TextEditor) { // Collect selection indices for each line; keep the column of the cursor in // memory for later. const selections = unsafeSelections(editor), selectionsPerLine = new Map<number, [activeColumn: number, selectionIndex: number][]>(); for (let i = 0; i < selections.length; i++) { const selection = selections[i], active = selection.active, activeLine = Selections.activeLine(selection), activeCharacter = activeLine === active.line ? active.character : Number.MAX_SAFE_INTEGER, // We were at the end of the line. selectionsForLine = selectionsPerLine.get(activeLine); if (selectionsForLine === undefined) { selectionsPerLine.set(activeLine, [[activeCharacter, i]]); } else { selectionsForLine.push([activeCharacter, i]); } } // For each line with selections, add a new decoration. const ranges = [] as vscode.DecorationOptions[]; for (const [line, selectionsForLine] of selectionsPerLine) { // Sort selection indices by their column to make sure they match the // order seen by the user. selectionsForLine.sort((a, b) => a[0] - b[0]); const rangePosition = new vscode.Position(line, 0), range = new vscode.Range(rangePosition, rangePosition); ranges.push({ range, renderOptions: { after: { contentText: "#" + selectionsForLine.map((x) => x[1]).join(", #"), }, }, }); } editor.setDecorations(indicesDecorationType, ranges); } disposable = _.extension .createAutoDisposable() .addDisposable(indicesDecorationType) .addDisposable(vscode.window.onDidChangeTextEditorSelection((e) => e.textEditor === editorState.editor && onDidChangeSelection(e.textEditor), )) .addDisposable(editorState.onVisibilityDidChange((e) => e.isVisible && onDidChangeSelection(e.editor), )); editorState.store(indicesToken, disposable); if (Array.isArray(until)) { until.forEach((until) => disposable!.disposeOnUserEvent(until, _)); } onDidChangeSelection(editorState.editor); } function tryCopySelection( document: vscode.TextDocument, selection: vscode.Selection, newActiveLine: number, ) { const active = selection.active, anchor = selection.anchor, activeLine = Selections.activeLine(selection), endCharacter = Selections.endCharacter(selection, document); let activeCharacter = selection.end === active ? endCharacter : active.character, anchorCharacter = selection.end === anchor ? endCharacter : anchor.character; if (activeLine === anchor.line) { const newLineLength = document.lineAt(newActiveLine).text.length; if (endCharacter > newLineLength) { if (endCharacter !== newLineLength + 1) { return undefined; } return selection.end === active ? new vscode.Selection(newActiveLine, anchorCharacter, newActiveLine + 1, 0) : new vscode.Selection(newActiveLine + 1, 0, newActiveLine, activeCharacter); } return new vscode.Selection(newActiveLine, anchorCharacter, newActiveLine, activeCharacter); } let newAnchorLine = newActiveLine + anchor.line - activeLine; if (newAnchorLine < 0 || newAnchorLine >= document.lineCount) { return undefined; } const newAnchorLineLength = document.lineAt(newAnchorLine).text.length; if (anchorCharacter > newAnchorLineLength) { if (anchorCharacter !== newAnchorLineLength + 1) { return undefined; } newAnchorLine++; anchorCharacter = 0; } const newActiveLineLength = document.lineAt(newActiveLine).text.length; if (active.character > newActiveLineLength) { if (activeCharacter !== newActiveLineLength + 1) { return undefined; } newActiveLine++; activeCharacter = 0; } const newSelection = new vscode.Selection(newAnchorLine, anchorCharacter, newActiveLine, activeCharacter); if (Selections.overlap(selection, newSelection)) { return undefined; } return newSelection; }
the_stack
module labelling_tool { /* Box label model */ interface OrientedEllipseLabelModel extends AbstractLabelModel { // Note that orientation rotates clockwise from positive X-axis (right) to the positive Y-axis (down) // If the orientation is 0, then radius1 and radius2 correspond to the radii in the X and Y axes respectively centre: Vector2; radius1: number; radius2: number; orientation_radians: number; } function new_OrientedEllipseLabelModel(centre: Vector2, radius1: number, radius2: number, orientation_radians: number, label_class: string, source: string): OrientedEllipseLabelModel { return {label_type: 'oriented_ellipse', label_class: label_class, source: source, anno_data: {}, centre: centre, radius1: radius1, radius2: radius2, orientation_radians: orientation_radians}; } function OrientedEllipseLabel_box(label: OrientedEllipseLabelModel): AABox { // The solution to this problem was obtained from here: // https://stackoverflow.com/questions/87734/how-do-you-calculate-the-axis-aligned-bounding-box-of-an-ellipse // https://gist.github.com/smidm/b398312a13f60c24449a2c7533877dc0 // Note that this approach is correct: // irrespective of the direction of orientation; it works for both CW and CCW var tan_orient = Math.tan(label.orientation_radians); var s0 = Math.atan(-label.radius2 * tan_orient / label.radius1); var s1 = s0 + Math.PI; var t0; if (tan_orient != 0.0) { t0 = Math.atan((label.radius2 / tan_orient) / label.radius1); } else { t0 = Math.PI * 0.5; } var t1 = t0 + Math.PI; var max_x = label.centre.x + label.radius1 * Math.cos(s0) * Math.cos(label.orientation_radians) - label.radius2 * Math.sin(s0) * Math.sin(label.orientation_radians); var min_x = label.centre.x + label.radius1 * Math.cos(s1) * Math.cos(label.orientation_radians) - label.radius2 * Math.sin(s1) * Math.sin(label.orientation_radians); var max_y = label.centre.y + label.radius2 * Math.sin(t0) * Math.cos(label.orientation_radians) + label.radius1 * Math.cos(t0) * Math.sin(label.orientation_radians); var min_y = label.centre.y + label.radius2 * Math.sin(t1) * Math.cos(label.orientation_radians) + label.radius1 * Math.cos(t1) * Math.sin(label.orientation_radians); var lower = {x: min_x, y: min_y}; var upper = {x: max_x, y: max_y}; return new AABox(lower, upper); } function ellipseClosestPoint(rad1: number, rad2: number, p: Vector2): Vector2 { // Converted from: // https://stackoverflow.com/questions/22959698/distance-from-given-point-to-given-ellipse var px = Math.abs(p.x); var py = Math.abs(p.y); var tx = Math.sqrt(0.5); var ty = Math.sqrt(0.5); var a, b; if (rad1 > rad2) { a = rad1; b = rad2; } else { a = rad2; b = rad1; } for (var i = 0; i < 3; i++) { var x = a * tx; var y = b * ty; var ex = (a*a - b*b) * tx*tx*tx / a; var ey = (b*b - a*a) * ty*ty*ty / b; var rx = x - ex; var ry = y - ey; var qx = px - ex; var qy = py - ey; var r = Math.sqrt(ry*ry + rx*rx); var q = Math.sqrt(qy*qy + qx*qx); tx = Math.min(1, Math.max(0, (qx * r / q + ex) / a)); ty = Math.min(1, Math.max(0, (qy * r / q + ey) / b)); var t = Math.sqrt(ty*ty + tx*tx); tx /= t ty /= t } return {x: Math.abs(a*tx) * (p.x >= 0.0 ? 1.0 : -1.0), y: Math.abs(b*ty) * (p.y >= 0.0 ? 1.0 : -1.0)}; } function OrientedEllipseLabel_containsPoint(label: OrientedEllipseLabelModel, point: Vector2): boolean { var c = Math.cos(label.orientation_radians); var s = Math.sin(label.orientation_radians); var m = [[c, s], [-s, c]]; // Point relative to centre var p_c: Vector2 = {x: point.x - label.centre.x, y: point.y - label.centre.y}; // Point rotated to ellipse frame; multiply by transpose of m var p_e: Vector2 = { x: p_c.x * m[0][0] + p_c.y * m[0][1], y: p_c.x * m[1][0] + p_c.y * m[1][1], }; // Point relative to unit circle var p_u: Vector2 = {x: p_e.x / label.radius1, y: p_e.y / label.radius2}; return Math.sqrt(p_u.x*p_u.x + p_u.y*p_u.y) <= 1.0; } function OrientedEllipseLabel_closestPoint(label: OrientedEllipseLabelModel, point: Vector2): Vector2 { var c = Math.cos(label.orientation_radians); var s = Math.sin(label.orientation_radians); var m = [[c, s], [-s, c]]; // Point relative to centre var p_c: Vector2 = {x: point.x - label.centre.x, y: point.y - label.centre.y}; // Point rotated to ellipse frame; multiply by transpose of m var p_e: Vector2 = { x: p_c.x * m[0][0] + p_c.y * m[0][1], y: p_c.x * m[1][0] + p_c.y * m[1][1], }; // Compute closes point var cp_e = ellipseClosestPoint(label.radius1, label.radius2, p_e); // Rotate to relative to centre var cp_c: Vector2 = { x: cp_e.x * m[0][0] + cp_e.y * m[1][0], y: cp_e.x * m[0][1] + cp_e.y * m[1][1], }; return {x: cp_c.x + label.centre.x, y: cp_c.y + label.centre.y}; } /* Box label entity */ export class OrientedEllipseLabelEntity extends AbstractLabelEntity<OrientedEllipseLabelModel> { _ellipse: any; constructor(view: RootLabelView, model: OrientedEllipseLabelModel) { super(view, model); } attach() { super.attach(); this._ellipse = this.root_view.world.append("ellipse") .attr("rx", 0).attr("ry", 0) .attr("transform", "translate(0 0), rotate(0)"); this.update(); var self = this; this._ellipse.on("mouseover", function() { self._on_mouse_over_event(); }).on("mouseout", function() { self._on_mouse_out_event(); }); this._update_style(); }; detach() { this._ellipse.remove(); this._ellipse = null; super.detach(); } _on_mouse_over_event() { for (var i = 0; i < this._event_listeners.length; i++) { this._event_listeners[i].on_mouse_in(this); } } _on_mouse_out_event() { for (var i = 0; i < this._event_listeners.length; i++) { this._event_listeners[i].on_mouse_out(this); } } update() { var centre = this.model.centre; var orient_deg = this.model.orientation_radians * 180.0 / Math.PI; var transform = "translate(" + centre.x + " " + centre.y + "), rotate(" + orient_deg + ")"; this._ellipse .attr('rx', this.model.radius1).attr('ry', this.model.radius2) .attr('transform', transform); } commit() { this.root_view.commit_model(this.model); } _update_style() { if (this._attached) { var stroke_colour: Colour4 = this._outline_colour(); var vis: LabelVisibility = this.get_visibility(); if (vis == LabelVisibility.HIDDEN) { this._ellipse.attr("visibility", "hidden"); } else if (vis == LabelVisibility.FAINT) { stroke_colour = stroke_colour.with_alpha(0.2); this._ellipse.attr("style", "fill:none;stroke:" + stroke_colour.to_rgba_string() + ";stroke-width:1"); this._ellipse.attr("visibility", "visible"); } else if (vis == LabelVisibility.FULL) { var circle_fill_colour = this.root_view.view.colour_for_label_class(this.model.label_class); if (this._hover) { circle_fill_colour = circle_fill_colour.lighten(0.4); } circle_fill_colour = circle_fill_colour.with_alpha(0.35); stroke_colour = stroke_colour.with_alpha(0.5); this._ellipse.attr("style", "fill:" + circle_fill_colour.to_rgba_string() + ";stroke:" + stroke_colour.to_rgba_string() + ";stroke-width:1"); this._ellipse.attr("visibility", "visible"); } } } compute_centroid(): Vector2 { return this.model.centre; }; compute_bounding_box(): AABox { return OrientedEllipseLabel_box(this.model); }; contains_pointer_position(point: Vector2): boolean { return OrientedEllipseLabel_containsPoint(this.model, point); } distance_to_point(point: Vector2): number { var closest = OrientedEllipseLabel_closestPoint(this.model, point); return Math.sqrt(compute_sqr_dist(closest, point)); } } register_entity_factory('oriented_ellipse', (root_view: RootLabelView, model: AbstractLabelModel) => { return new OrientedEllipseLabelEntity(root_view, model as OrientedEllipseLabelModel); }); /* Draw box tool */ export class DrawOrientedEllipseTool extends AbstractTool { entity: OrientedEllipseLabelEntity; _points: Vector2[]; constructor(view: RootLabelView, entity: OrientedEllipseLabelEntity) { super(view); this.entity = entity; this._points = []; } on_init() { }; on_shutdown() { }; on_switch_in(pos: Vector2) { this.add_point(pos); }; on_switch_out(pos: Vector2) { this.remove_last_point(); }; on_cancel(pos: Vector2): boolean { if (this.entity !== null) { if (this._points.length > 0) { this.remove_last_point(); } if (this._points.length <= 1) { this.destroy_entity(); } } else { this._view.unselect_all_entities(); this._view.view.set_current_tool(new SelectEntityTool(this._view)); } return true; }; on_left_click(pos: Vector2, event: any) { if (this.entity === null) { this.create_entity(pos); } this.add_point(pos); if (this._points.length >= 4) { this.update_ellipse(); this.entity.commit(); this._points = [pos]; this.entity = null; } }; on_move(pos: Vector2) { this.update_last_point(pos); }; add_point(pos: Vector2) { this._points.push(pos); this.update_ellipse(); }; update_last_point(pos: Vector2) { this._points[this._points.length - 1] = pos; this.update_ellipse(); }; remove_last_point() { if (this._points.length > 0) { this._points.splice(this._points.length - 1, 1); this.update_ellipse(); } }; create_entity(pos: Vector2) { var label_class = this._view.view.get_label_class_for_new_label(); var model = new_OrientedEllipseLabelModel(pos, 0.0, 0.0, 0.0, label_class, "manual"); var entity = this._view.get_or_create_entity_for_model(model); this.entity = entity; // Freeze to prevent this temporary change from being sent to the backend this._view.view.freeze(); this._view.add_child(entity); this._view.select_entity(entity, false, false); this._view.view.thaw(); }; destroy_entity() { // Freeze to prevent this temporary change from being sent to the backend this._view.view.freeze(); this.entity.destroy(); this.entity = null; this._view.view.thaw(); }; update_ellipse() { if (this.entity !== null) { var centre: Vector2 = {x: 0.0, y: 0.0}; var orientation: number = 0.0; var rad1: number = 10.0; var rad2: number = 10.0; if (this._points.length === 1) { centre = this._points[0]; } else if (this._points.length >= 2) { var u = sub_Vector2(this._points[1], this._points[0]); centre = mul_Vector2(add_Vector2(this._points[0], this._points[1]), 0.5); rad1 = Math.sqrt(compute_sqr_length(u)) * 0.5; rad2 = rad1 * 0.1; // Clockwise from +ve X-axis orientation = Math.atan2(u.y, u.x); if (this._points.length >= 3) { var u_nrm = mul_Vector2(u, 1.0 / Math.sqrt(compute_sqr_length(u))); var n: Vector2 = {x: u_nrm.y, y: -u_nrm.x}; var d: number = dot_Vector2(n, this._points[0]); var d2: number = dot_Vector2(n, this._points[2]) rad2 = Math.abs(d2-d); } } this.entity.model.centre = centre; this.entity.model.orientation_radians = orientation; this.entity.model.radius1 = rad1; this.entity.model.radius2 = rad2; this.entity.update(); } }; } }
the_stack
import { TextEncoder } from "util"; import { FileType, Uri, workspace, WorkspaceConfiguration, window } from 'vscode'; import { localize } from '../i18n'; import { ASMTYPE, Config, SRCFILE, settingsStrReplacer } from '../ASM/configration'; import { Logger } from '../ASM/outputChannel'; import { ASMPREPARATION, ASSEMBLERMSG, EMURUN, MSGProcessor } from "../ASM/runcode"; import { inDirectory } from "../ASM/util"; import { writeBoxconfig } from './dosbox_conf'; import { DOSBox as dosboxCore, WINCONSOLEOPTION, DOSBoxStd } from './dosbox_core'; const fs = workspace.fs; /**the limit of commands can be exec in dosbox, over this limit the commands will be write to a file*/ const DOSBOX_CMDS_LIMIT = 5; /**the time interval between launch dosbox and read asmlog file*/ const WAIT_AFTER_LAUNCH_DOSBOX = 8000; /**the file name of dosbox conf file for use */ const DOSBOX_CONF_FILENAME = 'VSC-ExtUse.conf'; /**the file name of log of assembler */ const ASM_LOG_FILE = 'ASM.LOG'; /**the file name of log of linker */ const LINK_LOG_FILE = 'LINK.LOG'; const DELAY = (timeout: number): Promise<void> => new Promise((resolve) => { setTimeout(resolve, timeout); }); /**interface for configurations from vscode settings */ interface DosboxAction { open: string[]; masm: string[]; tasm: string[]; tasm_debug: string[]; masm_debug: string[]; run: string[]; after_action: string[]; } /**class for configurations from VSCode settings */ class BoxVSCodeConfig { private get _target(): WorkspaceConfiguration { return workspace.getConfiguration('masmtasm.dosbox'); }; get config(): { [id: string]: string } | undefined { return this._target.get('config'); } get run(): string | undefined { return this._target.get('run'); } get console(): string { return this._target.get('console') as string; } get command(): string | undefined { const output = this._target.get('command'); if (typeof output !== 'string') { return undefined; } return output; } getAction(scope: keyof DosboxAction): string[] { const id = 'masmtasm.dosbox.more'; const a = this._target.get('more') as DosboxAction; if (a === null || a === undefined) { window.showErrorMessage(`${a} is not allowed in ${id}`); } else { let output = a[scope]; if (Array.isArray(output)) { if (this.replacer) { output = output.map(this.replacer); } return output; } else { window.showErrorMessage(`action ${scope} is undefined or not a array in ${id}`); } } throw new Error(`no ${scope} in ${id}:${JSON.stringify(a)}`); } replacer?: (str: string) => string; public runDebugCmd(runOrDebug: boolean, ASM: ASMTYPE): string[] { if (runOrDebug) { return this.getAction('run'); } else { switch (ASM) { case ASMTYPE.MASM: return this.getAction('masm_debug'); case ASMTYPE.TASM: return this.getAction('tasm_debug'); } } } public AsmLinkRunDebugCmd(runOrDebug: boolean, ASM: ASMTYPE): string[] { let asmlink: string[]; switch (ASM) { case ASMTYPE.MASM: asmlink = this.getAction('masm'); break; case ASMTYPE.TASM: asmlink = this.getAction('tasm'); break; } return asmlink.concat(this.runDebugCmd(runOrDebug, ASM)); } } export class DOSBox extends dosboxCore implements EMURUN { //private dosboxChannel: OutputChannel = window.createOutputChannel('DOSBox console'); private _BOXrun: string | undefined; private _conf: Config; private vscConfig: BoxVSCodeConfig; constructor(conf: Config) { const vscConf = new BoxVSCodeConfig(); let boxconsole: WINCONSOLEOPTION | undefined = undefined; if (vscConf.command === undefined || vscConf.command.length === 0) { switch (vscConf.console) { case "min": boxconsole = WINCONSOLEOPTION.min; break; case "normal": boxconsole = WINCONSOLEOPTION.normal; break; case "noconsole": case "redirect(show)": case "redirect": default: boxconsole = WINCONSOLEOPTION.noconsole; break; } } super(conf.Uris.dosbox.fsPath, vscConf.command, boxconsole); this.forceCopy = false; this._conf = conf; this.vscConfig = vscConf; this._BOXrun = vscConf.run; if (this.redirect) { this.stdoutHander = (message: string, text: string, code: number): void => { Logger.send({ title: localize('dosbox.console.stdout', '[dosbox console stdout] No.{0}', code.toString()), content: message }); if (vscConf.console === 'redirect(show)') { Logger.OutChannel.show(true); } else if (vscConf.console === 'redirect(hide)') { Logger.OutChannel.hide(); } }; this.stderrHander = (message: string, _text: string, code: number): void => { Logger.send({ title: localize('dosbox.console.stderr', '[dosbox console stderr] No.{0}', code.toString()), content: message }); }; } } //implement the interface forceCopy: boolean; async prepare(opt?: ASMPREPARATION): Promise<boolean> { //write the config file for extension this.confFile = Uri.joinPath(this._conf.Uris.globalStorage, DOSBOX_CONF_FILENAME); await writeBoxconfig(this.confFile, this.vscConfig.config); if (opt) { this.forceCopy = !opt.src.dosboxFsReadable; }; this.vscConfig.replacer = (val: string): string => settingsStrReplacer(val, this._conf, opt ? opt.src : undefined); return true; } openEmu(folder: Uri): Promise<unknown> { return this.runDosbox(folder, []); } async Run(src: SRCFILE, msgprocessor?: MSGProcessor): Promise<void> { const { all, race } = await this.runDebug(src, true); const asm = await race; if (msgprocessor) { msgprocessor(asm, { preventWarn: true }); } await all; } async Debug(src: SRCFILE, msgprocessor?: MSGProcessor): Promise<void> { const { all, race } = await this.runDebug(src, false); const asm = await race; if (msgprocessor) { msgprocessor(asm, { preventWarn: true }); } await all; } /** * A function to run or debug ASM codes in DOSBox * @param runOrDebug true for run ASM code,false for debug * @param file the Uri of the file * @returns the Assembler's output */ public async runDebug(src: SRCFILE, runOrDebug: boolean): Promise<{ all: Promise<ASSEMBLERMSG | undefined>; race: Promise<ASSEMBLERMSG> }> { //clean logs file for asm and link const dirs = await fs.readDirectory(this._conf.Uris.globalStorage); let dir = inDirectory(dirs, [ASM_LOG_FILE, FileType.File]); if (dir) { const asmloguri = Uri.joinPath(this._conf.Uris.globalStorage, dir[0]); await fs.delete(asmloguri); } dir = inDirectory(dirs, [LINK_LOG_FILE, FileType.File]); if (dir) { const asmloguri = Uri.joinPath(this._conf.Uris.globalStorage, dir[0]); await fs.delete(asmloguri); } //launch dosbox and read logs /**read logs file and make sure asm log is not empty*/ const readMsg = async (): Promise<undefined | { asm: string; link: string }> => { const dirs = await fs.readDirectory(this._conf.Uris.globalStorage); const asmlog = inDirectory(dirs, [ASM_LOG_FILE, FileType.File]); const linklog = inDirectory(dirs, [LINK_LOG_FILE, FileType.File]); if (asmlog && linklog) { const asmloguri = Uri.joinPath(this._conf.Uris.globalStorage, asmlog[0]); const linkloguri = Uri.joinPath(this._conf.Uris.globalStorage, linklog[0]); const asm = (await fs.readFile(asmloguri)).toString(); const link = (await fs.readFile(linkloguri)).toString(); if (asm.trim().length > 0) { return { asm, link }; } } return undefined; }; /**read logs after DOSBox exit*/ const exitRead: Promise<{ asm: string; link: string } | undefined> = new Promise( async (resolve) => { await this.runDosbox(src.folder, this.vscConfig.AsmLinkRunDebugCmd(runOrDebug, this._conf.MASMorTASM), { exitwords: true }); const msg = await readMsg(); resolve(msg); } ); /**read logs at two time * 1. WAIT_AFTER_LAUNCH_DOSBOX ms after launch DOSBox * 2. after DOSBox exit */ const race: Promise<{ asm: string; link: string }> = new Promise( async (resolve, reject) => { await DELAY(WAIT_AFTER_LAUNCH_DOSBOX); let msg = await readMsg(); if (msg) { resolve(msg); } else { msg = await exitRead; if (msg) { resolve(msg); } else { reject('no log readed'); } } } ); return { all: exitRead, race }; } /**open dosbox and do things about it * this function will mount the tools as `C:` and the workspace as `D:` * set paths for masm and tasm and switch to the disk * @param folder The uri of the folder needed to mount to disk `d` * @param more The commands needed to exec in dosbox */ public async runDosbox(folder: Uri, more?: string[], opt?: { exitwords: boolean }): Promise<DOSBoxStd> { const boxcmd: string[] = this.vscConfig.getAction('open'); boxcmd.push( `@mount c \\\"${this._conf.Uris.tools.fsPath}\\\"`,//mount the tools folder as disk C `@mount d \\\"${folder.fsPath}\\\"`,//mount the folder of source file as disk D `@mount X \\\"${this._conf.Uris.globalStorage.fsPath}\\\"`,//mount a separate space as X for the extension to read logs "d:"//switch to the disk of source code file ); if (more) { boxcmd.push(...more); } if (opt?.exitwords) { boxcmd.push(...this.boxruncmd); } //Logger.log(boxcmd); if (boxcmd.length > DOSBOX_CMDS_LIMIT) { const omit = boxcmd.slice(DOSBOX_CMDS_LIMIT - 1); const unit8 = new TextEncoder().encode(omit.join('\n')); const dst = Uri.joinPath(this._conf.Uris.globalStorage, 'more.bat'); await fs.writeFile(dst, unit8); boxcmd.splice(DOSBOX_CMDS_LIMIT - 1, omit.length); boxcmd.push('@x:\\more.bat'); } return this.run(boxcmd); } /** the command need to run in DOSBox after run the ASM code*/ public get boxruncmd(): string[] { switch (this._BOXrun) { case "keep": return []; case "exit": return (['exit']); case 'pause': return ['pause', 'exit']; case "choose": default: return this.vscConfig.getAction('after_action'); } } }
the_stack
import { FocusTrap } from "@a11y/focus-trap"; import { customElement, html, property, query, TemplateResult } from "lit-element"; import "../backdrop"; import { Backdrop } from "../backdrop/backdrop"; import { IOverlayBehaviorBaseProperties, IOverlayBehaviorProperties, OverlayBehavior } from "../behavior/overlay/overlay-behavior"; import { AriaRole } from "../util/aria"; import { cssResult } from "../util/css"; import { queryParentRoots, renderAttributes, setProperty } from "../util/dom"; import { addClickAwayListener, addListener, EventListenerSubscription, removeListeners } from "../util/event"; import { areStrategiesEqual, computeAnchorPosition, computeFallbackStrategy, computeMaxDimensions, computeTransformOrigin, IAnchorPosition, IPositionStrategy, OriginX, OriginY } from "../util/position"; import { getOpacity, getScale } from "../util/style"; import styles from "./popover.scss"; /** * Base properties of the popover. */ export interface IPopoverBaseProperties extends IPositionStrategy, IOverlayBehaviorBaseProperties { closeOnClick: boolean; role: AriaRole; noFallback: boolean; anchor?: Element | string; } /** * Properties of the popover. */ export interface IPopoverProperties extends IPopoverBaseProperties, IOverlayBehaviorProperties { anchorOpenEvents?: string[]; anchorCloseEvents?: string[]; } /** * Configuration for the popover. */ export interface IPopoverConfig extends Partial<IPopoverBaseProperties> {} /** * Default configuration for the popover. */ export const defaultPopoverConfig: IPopoverConfig = { transformOriginX: OriginX.LEFT, transformOriginY: OriginY.TOP, anchorOriginX: OriginX.LEFT, anchorOriginY: OriginY.TOP, backdrop: false, persistent: false, duration: 300, closeOnClick: false, fixed: true }; /** * Contextual anchored elements. * @slot - Default content. * @cssprop --popover-z-index - z-index. */ @customElement("wl-popover") export class Popover<R = unknown> extends OverlayBehavior<R, IPopoverConfig> implements IPopoverProperties { static styles = [...OverlayBehavior.styles, cssResult(styles)]; /** * Makes the popover close when it is clicked upon. * @attr */ @property({ type: Boolean }) closeOnClick: boolean = false; /** * Whether a fallback strategy for the positioning should be used when there are no room for the popover. * @attr */ @property({ type: Boolean }) noFallback: boolean = false; /** * X origin of the transform. * @attr */ @property({ type: String, reflect: true }) transformOriginX: OriginX = OriginX.LEFT; /** * Y origin of the transform. * @attr */ @property({ type: String, reflect: true }) transformOriginY: OriginY = OriginY.TOP; /** * X origin of the anchored point. * @attr */ @property({ type: String, reflect: true }) anchorOriginX: OriginX = OriginX.LEFT; /** * Y origin of the anchored point. * @attr */ @property({ type: String, reflect: true }) anchorOriginY: OriginY = OriginY.TOP; /** * Role of the popover. * @attr */ @property({ type: String, reflect: true }) role: AriaRole = "menu"; /** * Anchor element or query. * @attr */ @property({ type: String }) anchor?: Element | string; /** * Events on the anchor that makes the popover open itself. * @attr */ @property({ type: Array }) anchorOpenEvents?: string[]; /** * Events on the anchor that makes the popover close itself. * @attr */ @property({ type: Array }) anchorCloseEvents?: string[]; /** * Content of the popover. */ @query("#content") protected $content!: FocusTrap; /** * Container element. */ @query("#container") protected $container!: HTMLElement; /** * Backdrop element. */ @query("#backdrop") protected $backdrop!: Backdrop; /** * Listeners that reacts when the user clicks outside the popover. * Attached when when opened. */ private clickAwayListeners: EventListenerSubscription[] = []; /** * Listeners that opens the popover when event happens on the anchor. */ private anchorOpenEventListeners: EventListenerSubscription[] = []; /** * Listeners that closes the popover when event happens on the anchor. */ private anchorCloseEventListeners: EventListenerSubscription[] = []; /** * Position of the anchor. */ private anchorPosition?: IAnchorPosition; /** * Focus trap. */ get $focusTrap() { return this.$content; } /** * Tears down the component. */ disconnectedCallback() { super.disconnectedCallback(); this.detachClickAwayListeners(); removeListeners(this.anchorOpenEventListeners); removeListeners(this.anchorCloseEventListeners); } /** * Reacts on the properties changed. * @param props */ protected updated(props: Map<keyof IPopoverProperties, unknown>) { super.updated(<Map<keyof IOverlayBehaviorProperties, unknown>>props); // Attach auto open events to anchor if (props.has("anchorOpenEvents") && this.anchorOpenEvents != null) { this.attachEventListenersToAnchor(this.anchorOpenEventListeners, this.anchorOpenEvents, () => !this.open && this.show()); } // Attach auto close events to anchor if (props.has("anchorCloseEvents") && this.anchorCloseEvents != null) { this.attachEventListenersToAnchor(this.anchorCloseEventListeners, this.anchorCloseEvents, () => this.open && this.hide()); } } /** * Shows the popover at a specified screen position. * @param position * @param config */ showAtPosition(position: IAnchorPosition, config?: IPopoverConfig): Promise<R | null> { this.anchorPosition = position; return this.show(config); } /** * The current position strategy of the popover. * @returns {IPositionStrategy} */ protected getPositionStrategy(): IPositionStrategy { return { transformOriginX: this.transformOriginX, transformOriginY: this.transformOriginY, anchorOriginX: this.anchorOriginX, anchorOriginY: this.anchorOriginY }; } /** * Adds event listeners and focuses the first element after the popover has been shown. */ protected didShow() { super.didShow(); // Focus the first element this.$focusTrap.focusFirstElement(); // Attach click away listeners this.attachClickAwayListeners(); } /** * Resets the component after the popover has been hidden. */ protected didHide(result?: R) { super.didHide(result); this.anchorPosition = undefined; } /** * Attaches events listeners to the anchor. * @param listeners * @param events * @param cb */ protected attachEventListenersToAnchor(listeners: EventListenerSubscription[], events: string[], cb: (e: Event) => void) { // Detach the previous event listeners and attach the new ones. removeListeners(listeners); // Ensure that an anchor exists const $anchor = this.getAnchor(); if ($anchor == null) { return this.throwNoAnchorError(); } // Add the listeners to the anchor listeners.push(addListener($anchor, events, cb)); } /** * Throws an error that no anchor exists. */ protected throwNoAnchorError() { throw new Error(`No anchor could be found for the popover. "${this.anchor}" provided as anchor.`); } /** * Attaches the click away listeners. */ protected attachClickAwayListeners() { this.clickAwayListeners.push( addClickAwayListener([this.$container], this.clickAway.bind(this)), addListener(this.$container, "click", this.onContainerClick.bind(this)) ); } /** * Detaches the click away listeners. */ protected detachClickAwayListeners() { removeListeners(this.clickAwayListeners); } /** * Animates the popover in. */ protected animateIn() { // Callback for cleaning up the component and the animation let ready = false; const setup = () => { if (ready) return; ready = true; this.didShow(); }; // Animate the backdrop in const backdropAnimation = this.$backdrop.animate( <PropertyIndexedKeyframes>{ opacity: [getOpacity(window.getComputedStyle(this.$backdrop)).toString(), `1`] }, this.animationConfig ); // Animate the popover in and take the intermediate stake into account const contentComputedStyle = window.getComputedStyle(this.$content); const contentScale = getScale(contentComputedStyle, this.$content.getBoundingClientRect()); const contentOpacity = getOpacity(contentComputedStyle); const contentAnimation = this.$content.animate( <PropertyIndexedKeyframes>{ transform: [`scale(${contentScale.x}, ${contentScale.y})`, `scale(1)`], opacity: [`${contentOpacity > 0.5 ? contentOpacity : 0}`, 1] }, this.animationConfig ); contentAnimation.onfinish = setup; backdropAnimation.onfinish = setup; this.activeInAnimations.push(contentAnimation, backdropAnimation); this.updatePosition(); } /** * Animates the popover out. * @param result */ protected animateOut(result: R) { // Callback for cleaning up the component and the animation let cleaned = false; const cleanup = () => { if (cleaned) return; cleaned = true; this.resolve(result); this.didHide(result); }; // Animate the backdrop out const backdropAnimation = this.$backdrop.animate( <PropertyIndexedKeyframes>{ opacity: [getOpacity(window.getComputedStyle(this.$backdrop)).toString(), `0`] }, this.animationConfig ); // Animate the content out const contentComputedStyle = window.getComputedStyle(this.$content); const contentScale = getScale(contentComputedStyle, this.$content.getBoundingClientRect()); const contentOpacity = getOpacity(contentComputedStyle); const contentAnimation = this.$content.animate( <PropertyIndexedKeyframes>{ opacity: [contentOpacity.toString(), 0], transform: [`scale(${contentScale.x}, ${contentScale.y})`, `scale(0)`] }, this.animationConfig ); backdropAnimation.onfinish = cleanup; contentAnimation.onfinish = cleanup; this.detachClickAwayListeners(); this.activeOutAnimations.push(backdropAnimation, contentAnimation); } /** * Updates the position of the popover. */ protected updatePosition() { super.updatePosition(); requestAnimationFrame(() => { // Compute the anchor position and transform origin const anchor = this.getAnchor(); let strategy = this.getPositionStrategy(); let isUsingFallbackStrategy = false; let position!: IAnchorPosition; let anchorRect: ClientRect | DOMRect | null = null; // Always prioritize the anchor position set explicitly if (this.anchorPosition != null) { position = this.anchorPosition; } else if (anchor != null) { anchorRect = anchor!.getBoundingClientRect(); position = computeAnchorPosition(strategy, anchorRect); } else { return this.throwNoAnchorError(); } // Compute a fallback strategy. Will not change if there are no need for a fallback. if (!this.noFallback) { const containerRect = this.$container.getBoundingClientRect(); const fallbackStrategy = computeFallbackStrategy(strategy, position, containerRect); // Check whether the fallback strategy should be used isUsingFallbackStrategy = areStrategiesEqual(strategy, fallbackStrategy); if (isUsingFallbackStrategy) { strategy = fallbackStrategy; position = computeAnchorPosition(fallbackStrategy, anchorRect || position); } } // Compute the transform of the popover const transform = computeTransformOrigin(strategy); this.$content.style.transformOrigin = `${strategy.transformOriginX} ${strategy.transformOriginY}`; Object.assign(this.$container.style, { top: `${position.top}px`, left: `${position.left}px`, transform: `translate(${transform.x}, ${transform.y})` }); // Render the actual strategy as data attributes. This is used for the arrow in the wl-popover-card. renderAttributes(this.$container, { "data-fallback-strategy": isUsingFallbackStrategy, "data-anchor-origin-x": strategy.anchorOriginX, "data-anchor-origin-y": strategy.anchorOriginY, "data-transform-origin-x": strategy.transformOriginX, "data-transform-origin-y": strategy.transformOriginY }); // Set the maximum height and width as CSS variables so the children can pick it up. const { maxWidth, maxHeight } = computeMaxDimensions(strategy, position); setProperty(`--popover-container-max-width`, `${maxWidth}px`, this.$container); setProperty(`--popover-container-max-height`, `${maxHeight}px`, this.$container); }); } /** * Returns the origin of the bounding box. */ private getAnchor(): Element | undefined { let anchor = this.anchor; // Check if the anchor is an ID. if (typeof anchor === "string" || anchor instanceof String) { const matches = queryParentRoots<Element>(this, <string>anchor); anchor = matches.length > 0 ? matches[0] : undefined; } return anchor; } /** * Handles the click event on the popover. */ private onContainerClick() { if (this.open && this.closeOnClick) { this.hide(); } } /** * Renders the content. */ protected renderContent(): TemplateResult { return html` <slot></slot> `; } /** * Returns the template for the element. */ protected render(): TemplateResult { return html` <wl-backdrop id="backdrop" @click="${this.clickAway}"></wl-backdrop> <div id="container" aria-expanded="${this.open.toString() as "true" | "false"}"> <focus-trap id="content" ?inactive="${!this.open || this.disableFocusTrap}"> ${this.renderContent()} </focus-trap> </div> `; } } declare global { interface HTMLElementTagNameMap { "wl-popover": Popover; } }
the_stack
import { WebApiTeam } from 'TFS/Core/Contracts'; import * as Calendar_Contracts from '../Contracts'; import * as Calendar_DateUtils from '../Utils/Date'; import * as Calendar_ColorUtils from '../Utils/Color'; import * as Contributions_Contracts from 'VSS/Contributions/Contracts'; import * as FreeForm_Enhancer from '../Enhancers/FreeFormEnhancer'; import * as Services_ExtensionData from 'VSS/SDK/Services/ExtensionData'; import * as Utils_Date from 'VSS/Utils/Date'; import * as Utils_String from 'VSS/Utils/String'; export class FreeFormEventsSource implements Calendar_Contracts.IEventSource { public id = "freeForm"; public name = "Event"; public order = 10; private _enhancer: FreeForm_Enhancer.FreeFormEnhancer; private _teamId: string; private _categoryId: string; private _events: Calendar_Contracts.CalendarEvent[]; private _categories: Calendar_Contracts.IEventCategory[]; constructor(context?: any) { this.updateTeamContext(context.team); } public updateTeamContext(newTeam: WebApiTeam) { this._teamId = newTeam.id; this._categoryId = Utils_String.format("{0}-categories", this._teamId); } public load(): PromiseLike<Calendar_Contracts.CalendarEvent[]> { return this.getCategories().then((categories: Calendar_Contracts.IEventCategory[]) => { return this.getEvents().then((events: Calendar_Contracts.CalendarEvent[]) => { const updatedEvents: Calendar_Contracts.CalendarEvent[] = []; for (const event of events) { // For now, skip events with date strngs we can't parse. if (Date.parse(event.startDate) && Date.parse(event.endDate)) { // update legacy events to match new contract event.movable = true; const category = event.category; if (!category || typeof category === "string") { event.category = <Calendar_Contracts.IEventCategory>{ title: category || "Uncategorized", id: this.id + "." + category || "Uncategorized", }; this._updateCategoryForEvents([event]); } // fix times const start = Utils_Date.shiftToUTC(new Date(event.startDate)); const end = Utils_Date.shiftToUTC(new Date(event.endDate)); if (start.getHours() !== 0) { // Set dates back to midnight start.setHours(0); end.setHours(0); // update the event in the list event.startDate = Utils_Date.shiftToLocal(start).toISOString(); event.endDate = Utils_Date.shiftToLocal(end).toISOString(); this.updateEvent(null, event); } updatedEvents.push(event); } } return updatedEvents; }); }); } public getEnhancer(): PromiseLike<Calendar_Contracts.IEventEnhancer> { if (!this._enhancer) { this._enhancer = new FreeForm_Enhancer.FreeFormEnhancer(); } return Promise.resolve(this._enhancer); } public getEvents(query?: Calendar_Contracts.IEventQuery): PromiseLike<Calendar_Contracts.CalendarEvent[]> { return VSS.getService( "ms.vss-web.data-service", ).then((extensionDataService: Services_ExtensionData.ExtensionDataService) => { return extensionDataService.queryCollectionNames([this._teamId]).then( (collections: Contributions_Contracts.ExtensionDataCollection[]) => { if (collections[0] && collections[0].documents) { this._events = collections[0].documents; } else { this._events = []; } return this._events; }, (e: Error) => { this._events = []; return this._events; }, ); }); } public getCategories(query?: Calendar_Contracts.IEventQuery): PromiseLike<Calendar_Contracts.IEventCategory[]> { return VSS.getService( "ms.vss-web.data-service", ).then((extensionDataService: Services_ExtensionData.ExtensionDataService) => { return extensionDataService.queryCollectionNames([this._categoryId]).then( (collections: Contributions_Contracts.ExtensionDataCollection[]) => { this._categories = []; if (collections[0] && collections[0].documents) { this._categories = collections[0].documents; } return this._filterCategories(query); }, (e: Error) => { return []; }, ); }); } public addEvent(event: Calendar_Contracts.CalendarEvent): PromiseLike<Calendar_Contracts.CalendarEvent> { return VSS.getService( "ms.vss-web.data-service", ).then((extensionDataService: Services_ExtensionData.ExtensionDataService) => { return extensionDataService .createDocument(this._teamId, event) .then((addedEvent: Calendar_Contracts.CalendarEvent) => { // update category for event addedEvent.category.id = this.id + "." + addedEvent.category.title; this._updateCategoryForEvents([addedEvent]); // add event this._events.push(addedEvent); return addedEvent; }); }); } public addCategory(category: Calendar_Contracts.IEventCategory): PromiseLike<Calendar_Contracts.IEventCategory> { return VSS.getService( "ms.vss-web.data-service", ).then((extensionDataService: Services_ExtensionData.ExtensionDataService) => { return extensionDataService .createDocument(this._categoryId, category) .then((addedCategory: Calendar_Contracts.IEventCategory) => { this._categories.push(addedCategory); return addedCategory; }); }); } public removeEvent(event: Calendar_Contracts.CalendarEvent): PromiseLike<Calendar_Contracts.CalendarEvent[]> { return VSS.getService( "ms.vss-web.data-service", ).then((extensionDataService: Services_ExtensionData.ExtensionDataService) => { return extensionDataService.deleteDocument(this._teamId, event.id).then(() => { // update category for event event.category = null; this._updateCategoryForEvents([event]); // remove event const eventInArray: Calendar_Contracts.CalendarEvent = $.grep( this._events, (e: Calendar_Contracts.CalendarEvent) => { return e.id === event.id; }, )[0]; //better check here const index = this._events.indexOf(eventInArray); if (index > -1) { this._events.splice(index, 1); } return this._events; }); }); } public removeCategory(category: Calendar_Contracts.IEventCategory): PromiseLike<Calendar_Contracts.IEventCategory[]> { return VSS.getService( "ms.vss-web.data-service", ).then((extensionDataService: Services_ExtensionData.ExtensionDataService) => { return extensionDataService.deleteDocument(this._categoryId, category.id).then(() => { const categoryInArray: Calendar_Contracts.IEventCategory = $.grep( this._categories, (cat: Calendar_Contracts.IEventCategory) => { return cat.id === category.id; }, )[0]; const index = this._categories.indexOf(categoryInArray); if (index > -1) { this._categories.splice(index, 1); } return this._categories; }); }); } public updateEvent( oldEvent: Calendar_Contracts.CalendarEvent, newEvent: Calendar_Contracts.CalendarEvent, ): PromiseLike<Calendar_Contracts.CalendarEvent> { return VSS.getService<Services_ExtensionData.ExtensionDataService>( "ms.vss-web.data-service", ).then(extensionDataService => { newEvent.category.id = `${this.id}.${newEvent.category.title}`; return extensionDataService.updateDocument(this._teamId, newEvent).then(updatedEvent => { const eventInArray = this._events.filter(e => e.id === updatedEvent.id)[0]; const index = this._events.indexOf(eventInArray); if (index >= 0) { this._events.splice(index, 1); } if (oldEvent && newEvent.category.id !== oldEvent.category.id) { return this._updateCategoryForEvents([newEvent]).then(categories => { this._events.push(updatedEvent); return updatedEvent; }); } else { this._events.push(updatedEvent); return updatedEvent; } }); }); } public updateCategories(categories: Calendar_Contracts.IEventCategory[]): PromiseLike<Calendar_Contracts.IEventCategory[]> { return VSS.getService( "ms.vss-web.data-service", ).then((extensionDataService: Services_ExtensionData.ExtensionDataService) => { const updatedCategoriesPromises: PromiseLike<Calendar_Contracts.IEventCategory>[] = []; let index = 0; for (const category of categories) { if (category.events.length === 0) { updatedCategoriesPromises.push(this.removeCategory(category)[0]); } else if (this._categories.filter(cat => cat.id === category.id).length === 0) { updatedCategoriesPromises.push(this.addCategory(category)); } else { updatedCategoriesPromises.push( extensionDataService .updateDocument(this._categoryId, categories[index++]) .then((updatedCategory: Calendar_Contracts.IEventCategory) => { const categoryInArray: Calendar_Contracts.IEventCategory = $.grep( this._categories, (cat: Calendar_Contracts.IEventCategory) => { return cat.id === category.id; }, )[0]; const index = this._categories.indexOf(categoryInArray); if (index > -1) { this._categories.splice(index, 1); } this._categories.push(updatedCategory); return updatedCategory; }), ); } } return Promise.all(updatedCategoriesPromises); }); } public getTitleUrl(webContext: WebContext): PromiseLike<string> { return Promise.resolve(""); } private _updateCategoryForEvents( events: Calendar_Contracts.CalendarEvent[], ): PromiseLike<Calendar_Contracts.IEventCategory[]> { const categoryMap: { [id: string]: boolean } = {}; const updatedCategories = []; // remove event from current category for (const event of events) { const categoryForEvent = $.grep(this._categories, (cat: Calendar_Contracts.IEventCategory) => { return cat.events.indexOf(event.id) > -1; })[0]; if (categoryForEvent) { // Do nothing if category hasn't changed if (event.category && event.category.title === categoryForEvent.title) { event.category = categoryForEvent; return; } const index = categoryForEvent.events.indexOf(event.id); categoryForEvent.events.splice(index, 1); const count = categoryForEvent.events.length; categoryForEvent.subTitle = Utils_String.format("{0} event{1}", count, count > 1 ? "s" : ""); if (!categoryMap[categoryForEvent.id]) { categoryMap[categoryForEvent.id] = true; updatedCategories.push(categoryForEvent); } } // add event to new category if (event.category) { let newCategory = $.grep(this._categories, (cat: Calendar_Contracts.IEventCategory) => { return cat.id === event.category.id; })[0]; if (newCategory) { // category already exists newCategory.events.push(event.id); const count = newCategory.events.length; newCategory.subTitle = Utils_String.format("{0} event{1}", count, count > 1 ? "s" : ""); event.category = newCategory; } else { // category doesn't exist yet newCategory = event.category; newCategory.events = [event.id]; newCategory.subTitle = event.title; newCategory.color = Calendar_ColorUtils.generateColor(event.category.title); } if (!categoryMap[newCategory.id]) { categoryMap[newCategory.id] = true; updatedCategories.push(newCategory); } } } // update categories return this.updateCategories(updatedCategories); } private _filterCategories(query?: Calendar_Contracts.IEventQuery): Calendar_Contracts.IEventCategory[] { if (!this._events) { return []; } if (!query) { return this._categories; } return $.grep(this._categories, (category: Calendar_Contracts.IEventCategory) => { const categoryAdded: boolean = false; return category.events.some((event: string, eventIndex: number) => { const eventInList: Calendar_Contracts.CalendarEvent = $.grep( this._events, (e: Calendar_Contracts.CalendarEvent) => { return e.id === event; }, )[0]; return eventInList && Calendar_DateUtils.eventIn(eventInList, query); }); }); } }
the_stack
import * as chai from 'chai' // @ts-ignore import chaiAsPromised from 'chai-as-promised' import { WebCryptoEncryptionMaterial, WebCryptoDecryptionMaterial, WebCryptoDefaultCryptographicMaterialsManager, importForWebCryptoEncryptionMaterial, importForWebCryptoDecryptionMaterial, } from '../src/index' import { KeyringWebCrypto, WebCryptoAlgorithmSuite, AlgorithmSuiteIdentifier, KeyringTraceFlag, EncryptedDataKey, CommitmentPolicy, } from '@aws-crypto/material-management' import { ENCODED_SIGNER_KEY } from '@aws-crypto/serialize' import { toBase64 } from '@aws-sdk/util-base64-browser' import { synchronousRandomValues } from '@aws-crypto/web-crypto-backend' chai.use(chaiAsPromised) const { expect } = chai describe('WebCryptoDefaultCryptographicMaterialsManager', () => { class TestKeyring extends KeyringWebCrypto { async _onEncrypt(): Promise<WebCryptoEncryptionMaterial> { throw new Error('I should never see this error') } async _onDecrypt(): Promise<WebCryptoDecryptionMaterial> { throw new Error('I should never see this error') } } it('constructor sets keyring', () => { const keyring = new TestKeyring() const test = new WebCryptoDefaultCryptographicMaterialsManager(keyring) expect(test).to.be.instanceOf(WebCryptoDefaultCryptographicMaterialsManager) expect(test).to.haveOwnPropertyDescriptor('keyring', { value: keyring, writable: false, enumerable: true, configurable: false, }) }) it('Precondition: keyrings must be a KeyringWebCrypto.', () => { expect( () => new WebCryptoDefaultCryptographicMaterialsManager({} as any) ).to.throw() }) it('set a signatureKey and the compress point on the encryption context', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const test = await cmm._initializeEncryptionMaterial(suite, { some: 'context', }) expect(test).to.be.instanceOf(WebCryptoEncryptionMaterial) const { signatureKey, encryptionContext } = test if (!signatureKey) throw new Error('I should never see this error') expect(Object.keys(encryptionContext)).lengthOf(2) expect(encryptionContext) .to.have.haveOwnProperty(ENCODED_SIGNER_KEY) .and.to.equal(toBase64(signatureKey.compressPoint)) expect(encryptionContext) .to.have.haveOwnProperty('some') .and.to.equal('context') }) it('Check for early return (Postcondition): The WebCryptoAlgorithmSuite specification must support a signatureCurve to generate a signing key.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const { encryptionContext } = await cmm._initializeEncryptionMaterial( suite, { some: 'context' } ) expect(Object.keys(encryptionContext)).lengthOf(1) expect(encryptionContext) .to.have.haveOwnProperty('some') .and.to.equal('context') }) it('set a verificationKey from encryption context', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const context = { some: 'context', [ENCODED_SIGNER_KEY]: 'A29gmBT/NscB90u6npOulZQwAAiKVtoShudOm2J2sCgC', } const test = await cmm._initializeDecryptionMaterial(suite, context) expect(test).to.be.instanceOf(WebCryptoDecryptionMaterial) const { verificationKey } = test if (!verificationKey) throw new Error('I should never see this error') expect(verificationKey.signatureCurve).to.equal(suite.signatureCurve) }) it('Check for early return (Postcondition): The WebCryptoAlgorithmSuite specification must support a signatureCurve to extract a verification key.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const context = { some: 'context' } const test = await cmm._initializeDecryptionMaterial(suite, context) expect(test.verificationKey).to.equal(undefined) }) it('Precondition: WebCryptoDefaultCryptographicMaterialsManager If the algorithm suite specification requires a signatureCurve a context must exist.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) await expect(cmm._initializeDecryptionMaterial(suite, {})).to.rejectedWith( Error ) }) it('Precondition: The context must not contain a public key for a non-signing algorithm suite.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const context = { some: 'context', [ENCODED_SIGNER_KEY]: 'A29gmBT/NscB90u6npOulZQwAAiKVtoShudOm2J2sCgC', } await expect( cmm._initializeDecryptionMaterial(suite, context) ).to.be.rejectedWith( Error, 'Encryption context contains public verification key for unsigned algorithm suite.' ) }) it('Precondition: WebCryptoDefaultCryptographicMaterialsManager The context must contain the public key.', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const context = { missing: 'signer key' } await expect( cmm._initializeDecryptionMaterial(suite, context) ).to.rejectedWith(Error) }) it('can return a encryption material', async () => { const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) class TestKeyring extends KeyringWebCrypto { async _onEncrypt( material: WebCryptoEncryptionMaterial ): Promise<WebCryptoEncryptionMaterial> { const udk = synchronousRandomValues(suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } const edk = new EncryptedDataKey({ providerId: ' keyNamespace', providerInfo: 'keyName', encryptedDataKey: new Uint8Array(5), }) material .setUnencryptedDataKey(udk, trace) .addEncryptedDataKey( edk, KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY ) return importForWebCryptoEncryptionMaterial(material) } async _onDecrypt(): Promise<WebCryptoDecryptionMaterial> { throw new Error('I should never see this error') } } const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const encryptionContext = { some: 'context', } const material = await cmm.getEncryptionMaterials({ suite, encryptionContext, commitmentPolicy: CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, }) expect(Object.keys(material.encryptionContext)).lengthOf(2) if (!material.signatureKey) throw new Error('I should never see this error') expect(material.encryptionContext) .to.have.haveOwnProperty(ENCODED_SIGNER_KEY) .and.to.equal(toBase64(material.signatureKey.compressPoint)) expect(material.encryptionContext) .to.have.haveOwnProperty('some') .and.to.equal('context') }) it('will pick a default Algorithm Suite', async () => { class TestKeyring extends KeyringWebCrypto { async _onEncrypt( material: WebCryptoEncryptionMaterial ): Promise<WebCryptoEncryptionMaterial> { const udk = synchronousRandomValues(material.suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } const edk = new EncryptedDataKey({ providerId: ' keyNamespace', providerInfo: 'keyName', encryptedDataKey: new Uint8Array(5), }) material .setUnencryptedDataKey(udk, trace) .addEncryptedDataKey( edk, KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY ) return importForWebCryptoEncryptionMaterial(material) } async _onDecrypt(): Promise<WebCryptoDecryptionMaterial> { throw new Error('I should never see this error') } } const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const encryptionContext = { some: 'context', } const material = await cmm.getEncryptionMaterials({ encryptionContext, commitmentPolicy: CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, }) expect(Object.keys(material.encryptionContext)).lengthOf(2) if (!material.signatureKey) throw new Error('I should never see this error') expect(material.encryptionContext) .to.have.haveOwnProperty(ENCODED_SIGNER_KEY) .and.to.equal(toBase64(material.signatureKey.compressPoint)) expect(material.encryptionContext) .to.have.haveOwnProperty('some') .and.to.equal('context') }) it('Precondition: WebCryptoDefaultCryptographicMaterialsManager must reserve the ENCODED_SIGNER_KEY constant from @aws-crypto/serialize.', async () => { const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const encryptionContext = { [ENCODED_SIGNER_KEY]: 'context', } await expect( cmm.getEncryptionMaterials({ encryptionContext, commitmentPolicy: CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, }) ).to.rejectedWith(Error, 'Reserved encryptionContext value') }) it('Postcondition: The WebCryptoEncryptionMaterial must contain a valid dataKey.', async () => { class TestKeyring extends KeyringWebCrypto { async _onEncrypt( material: WebCryptoEncryptionMaterial ): Promise<WebCryptoEncryptionMaterial> { const udk = synchronousRandomValues(material.suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } const edk = new EncryptedDataKey({ providerId: ' keyNamespace', providerInfo: 'keyName', encryptedDataKey: new Uint8Array(5), }) return material .setUnencryptedDataKey(udk, trace) .addEncryptedDataKey( edk, KeyringTraceFlag.WRAPPING_KEY_ENCRYPTED_DATA_KEY ) } async _onDecrypt(): Promise<WebCryptoDecryptionMaterial> { throw new Error('I should never see this error') } } const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const encryptionContext = { some: 'context', } await expect( cmm.getEncryptionMaterials({ encryptionContext, commitmentPolicy: CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, }) ).to.rejectedWith(Error) }) it('Postcondition: The WebCryptoEncryptionMaterial must contain at least 1 EncryptedDataKey.', async () => { class TestKeyring extends KeyringWebCrypto { async _onEncrypt( material: WebCryptoEncryptionMaterial ): Promise<WebCryptoEncryptionMaterial> { const udk = synchronousRandomValues(material.suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_GENERATED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) return importForWebCryptoEncryptionMaterial(material) } async _onDecrypt(): Promise<WebCryptoDecryptionMaterial> { throw new Error('I should never see this error') } } const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const encryptionContext = { some: 'context', } await expect( cmm.getEncryptionMaterials({ encryptionContext, commitmentPolicy: CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT, }) ).to.rejectedWith(Error) }) it('can return decryption material', async () => { class TestKeyring extends KeyringWebCrypto { async _onEncrypt(): Promise<WebCryptoEncryptionMaterial> { throw new Error('I should never see this error') } async _onDecrypt( material: WebCryptoDecryptionMaterial ): Promise<WebCryptoDecryptionMaterial> { const udk = synchronousRandomValues(material.suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } material.setUnencryptedDataKey(udk, trace) return importForWebCryptoDecryptionMaterial(material) } } const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const encryptionContext = { some: 'context', [ENCODED_SIGNER_KEY]: 'A29gmBT/NscB90u6npOulZQwAAiKVtoShudOm2J2sCgC', } const edk = new EncryptedDataKey({ providerId: ' keyNamespace', providerInfo: 'keyName', encryptedDataKey: new Uint8Array(5), }) const material = await cmm.decryptMaterials({ suite, encryptionContext, encryptedDataKeys: [edk], }) if (!material.verificationKey) throw new Error('I should never see this error') expect(material.encryptionContext).to.deep.equal(encryptionContext) expect(material.verificationKey.signatureCurve).to.equal( suite.signatureCurve ) }) it('Postcondition: The WebCryptoDecryptionMaterial must contain a valid dataKey.', async () => { class TestKeyring extends KeyringWebCrypto { async _onEncrypt(): Promise<WebCryptoEncryptionMaterial> { throw new Error('I should never see this error') } async _onDecrypt( material: WebCryptoDecryptionMaterial ): Promise<WebCryptoDecryptionMaterial> { const udk = synchronousRandomValues(material.suite.keyLengthBytes) const trace = { keyName: 'keyName', keyNamespace: 'keyNamespace', flags: KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY, } /* This is intentionally trickery. * An unencrypted data key *without* a cryptoKey, should not be valid. */ return material.setUnencryptedDataKey(udk, trace) } } const suite = new WebCryptoAlgorithmSuite( AlgorithmSuiteIdentifier.ALG_AES128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 ) const keyring = new TestKeyring() const cmm = new WebCryptoDefaultCryptographicMaterialsManager(keyring) const encryptionContext = { some: 'context', [ENCODED_SIGNER_KEY]: 'A29gmBT/NscB90u6npOulZQwAAiKVtoShudOm2J2sCgC', } const edk = new EncryptedDataKey({ providerId: ' keyNamespace', providerInfo: 'keyName', encryptedDataKey: new Uint8Array(5), }) await expect( cmm.decryptMaterials({ suite, encryptionContext, encryptedDataKeys: [edk], }) ).to.rejectedWith(Error) }) })
the_stack
'use strict'; import { Logger, LogLevel } from 'chord/platform/log/common/log'; import { filenameToNodeName } from 'chord/platform/utils/common/paths'; const loggerWarning = new Logger(filenameToNodeName(__filename), LogLevel.Warning); import { querystringify } from 'chord/base/node/url'; import { request, IRequestOptions } from 'chord/base/node/_request'; import { IListOption } from 'chord/music/api/listOption'; import { IAudio } from 'chord/music/api/audio'; import { IEpisode } from 'chord/sound/api/episode'; import { IPodcast } from 'chord/sound/api/podcast'; import { IRadio } from 'chord/sound/api/radio'; import { TSoundItems } from 'chord/sound/api/items'; import { ESize, resizeImageUrl } from 'chord/music/common/size'; import { makeEpisode, makeEpisodes, makePodcast, makePodcasts, } from 'chord/sound/himalaya/parser'; export class HimalayaApi { static readonly SERVER = 'https://api.himalaya.com/'; static readonly HEADERS = { 'Referer': 'https://www.himalaya.com/', 'Radio-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }; static readonly NODE_MAP = { demoAudio: 'mobile/track/pay', audio: 'revision/play/tracks', episode: 'himalaya-portal/v1/share/track/detail/', podcast: 'himalaya-portal/v1/share/album/', podcastEpisodes: 'himalaya-portal/v1/share/track/', search: 'himalaya-portal/v2/search/keyword', radioBasic: 'revision/user/basic', radioAddons: 'revision/user', radioEpisodes: 'revision/user/track', radioPodcasts: 'revision/user/pub', radioFavoritePodcasts: 'revision/user/sub', radioFollowers: 'revision/user/fans', radioFollowings: 'revision/user/following', podcastListOptions: 'revision/category/allCategoryInfo', podcastOptionSubs: 'revision/category/detailCategoryPageInfo', podcastList: 'revision/category/queryCategoryPageAlbums', }; constructor() { } public async request(uri: string, params?: object, timeout?: number): Promise<any> { let paramstr = params ? '?' + querystringify(params) : ''; let url = HimalayaApi.SERVER + uri + paramstr; let headers = { ...HimalayaApi.HEADERS }; let options: IRequestOptions = { method: 'GET', url, headers, gzip: true, timeout, resolveWithFullResponse: false, }; let result: any = await request(options); let json = JSON.parse(result.trim()); if (json.ret && json.ret != 200 && json.ret != 0) { loggerWarning.warning('[HimalayaApi.request] [Error]: (params, response):', options, json); } return json; } public async audios(episodeId: string, supKbps?: number): Promise<Array<IAudio>> { let episode = await this.episode(episodeId); return episode.audios; } public async episode(episodeId: string): Promise<IEpisode> { let json = await this.request( HimalayaApi.NODE_MAP.episode + episodeId, ); return makeEpisode(json.data); } public async podcast(podcastId: string): Promise<IPodcast> { let json = await this.request( HimalayaApi.NODE_MAP.podcast + podcastId, ); return makePodcast(json.data); } public async podcastEpisodeCount(podcastId: string): Promise<number> { let json = await this.request( HimalayaApi.NODE_MAP.podcastEpisodes + podcastId, { pageIndex: 1, pageSize: 1, orderField: 1, }, ); return json.data.totalCount; } // order: // 0 正序 // 1 倒序 public async podcastEpisodes(podcastId: string, page: number = 1, size: number = 30, order: string = '1'): Promise<Array<IEpisode>> { let json = await this.request( HimalayaApi.NODE_MAP.podcastEpisodes + podcastId, { pageIndex: page, pageSize: size, orderField: order, }, ); return makeEpisodes(json.data.list); } public async search(type: string, keyword: string, page: number = 1, size: number = 10): Promise<any> { let json = await this.request( HimalayaApi.NODE_MAP.search, { keyword, core: type, pageId: page, pageSize: size, }, 5000, ); return json; } public async searchEpisodes(keyword: string, page: number = 1, size: number = 10): Promise<Array<IEpisode>> { let json; try { json = await this.search('track', keyword, page, size); } catch { return []; } return makeEpisodes(json.list.map(i => (i.track.nickname = i.user.nickname, i.track))); } public async searchPodcasts(keyword: string, page: number = 1, size: number = 10): Promise<Array<IPodcast>> { let json; try { json = await this.search('album', keyword, page, size); } catch { return []; } return makePodcasts(json.list.map(i => (i.album.nickname = i.user.nickname, i.album))); } public async searchRadios(keyword: string, page: number = 1, size: number = 10): Promise<Array<IRadio>> { let json = await this.search('user', keyword, page, size); return makeRadios(json.data.result.response.docs); } public async radio(radioId: string): Promise<IRadio> { let json = await this.request( HimalayaApi.NODE_MAP.radioBasic, { uid: radioId, }, ); let radio = makeRadio(json.data); json = await this.request( HimalayaApi.NODE_MAP.radioAddons, { uid: radioId, }, ); return { ...radio, episodeCount: json.data.trackPageInfo.totalCount, followingCount: json.data.followingPageInfo.totalCount, podcastCount: json.data.pubPageInfo.totalCount, favoritePodcastCount: json.data.subscriptionPageInfo.totalCount, }; } public async radioEpisodeCount(radioId: string, keyword: string = ''): Promise<number> { let json = await this.request( HimalayaApi.NODE_MAP.radioEpisodes, { page: 1, pageSize: 1, keyWord: keyword || '', uid: radioId, orderType: 2, }, ); return json.data.totalCount; } /** * Episodes the radio created * * order: * 1 正序 * 2 倒序 */ public async radioEpisodes( radioId: string, page: number = 1, size: number = 10, order: number = 2, keyword: string = '' ): Promise<Array<IEpisode>> { let json = await this.request( HimalayaApi.NODE_MAP.radioEpisodes, { page: page, pageSize: size, keyWord: '', uid: radioId, orderType: order, }, ); return makeEpisodes(json.data.trackList); } public async radioFavoritePodcastCount(radioId: string, keyword: string = ''): Promise<number> { let json = await this.request( HimalayaApi.NODE_MAP.radioFavoritePodcasts, { page: 1, pageSize: 1, keyWord: keyword || '', uid: radioId, subType: 1, }, ); return json.data.totalCount; } /** * Podcasts the radio liked * * order: * 1 综合排序 * 2 最近更新 * 3 最近订阅 */ public async radioFavoritePodcasts( radioId: string, page: number = 1, size: number = 10, order: number = 1, keyword: string = '' ): Promise<Array<IPodcast>> { let json = await this.request( HimalayaApi.NODE_MAP.radioFavoritePodcasts, { page: page, pageSize: size, keyWord: keyword || '', uid: radioId, subType: order, }, ); return makePodcasts(json.data.albumsInfo); } public async radioPodcastCount(radioId: string, keyword: string = ''): Promise<number> { let json = await this.request( HimalayaApi.NODE_MAP.radioPodcasts, { page: 1, pageSize: 1, keyWord: keyword || '', uid: radioId, orderType: 2, }, ); return json.data.totalCount; } /** * Podcasts the radio created * * order: * 1 正序 * 2 倒序 */ public async radioPodcasts( radioId: string, page: number = 1, size: number = 10, order: number = 2, keyword: string = '' ): Promise<Array<IPodcast>> { let json = await this.request( HimalayaApi.NODE_MAP.radioPodcasts, { page: page, pageSize: size, keyWord: keyword || '', uid: radioId, orderType: order, }, ); return makePodcasts(json.data.albumList); } public async radioFollowerCount(radioId: string): Promise<number> { let json = await this.request( HimalayaApi.NODE_MAP.radioFollowers, { page: 1, pageSize: 1, keyWord: '', uid: radioId, }, ); return json.data.totalCount; } public async radioFollowers(radioId: string, page: number = 0, size: number = 10): Promise<Array<IRadio>> { let json = await this.request( HimalayaApi.NODE_MAP.radioFollowers, { page: page, pageSize: size, keyWord: '', uid: radioId, }, ); return makeRadios(json.data.fansPageInfo); } public async radioFollowingCount(radioId: string): Promise<number> { let json = await this.request( HimalayaApi.NODE_MAP.radioFollowings, { page: 1, pageSize: 1, keyWord: '', uid: radioId, }, ); return json.data.totalCount; } public async radioFollowings(radioId: string, page: number = 1, size: number = 10): Promise<Array<IRadio>> { let json = await this.request( HimalayaApi.NODE_MAP.radioFollowings, { page: page, pageSize: size, keyWord: '', uid: radioId, }, ); return makeRadios(json.data.followingsPageInfo); } public async podcastListOptions(): Promise<Array<IListOption>> { let json = await this.request( HimalayaApi.NODE_MAP.podcastListOptions, {}, ); return makePodcastListOptions(json.data); } public async podcastOptionSubs(category: string, subCategory: string): Promise<Array<IListOption>> { let json = await this.request( HimalayaApi.NODE_MAP.podcastOptionSubs, { category, subcategory: subCategory, }, ); let option = { id: null, name: '排序', type: 'sort', items: [ { id: '0', name: '综合排序', type: 'sort', }, { id: '2', name: '播放最多', type: 'sort', }, { id: '1', name: '最近更新', type: 'sort', } ], }; let options = makePodcastOptionSubs(json.data); options.push(option); return options; } public async podcastListCount( category: string, subCategory: string, meta: string = '' ): Promise<number> { let json = await this.request( HimalayaApi.NODE_MAP.podcastList, { category, subcategory: subCategory, meta, sort: '0', page: 1, perPage: 1, }, ); return json.data.total; } public async podcastList( category: string, subCategory: string, meta: string = '', sort: string = '0', page: number = 1, size: number = 10): Promise<Array<IPodcast>> { let json = await this.request( HimalayaApi.NODE_MAP.podcastList, { category, subcategory: subCategory, meta, sort, page, perPage: size, }, ); return makePodcasts(json.data.albums); } public resizeImageUrl(url: string, size: ESize | number): string { if (!url) return null; return resizeImageUrl( '', size, (_, size) => { if (url.includes('source')) { return url.replace(/source\/.+/, 'source/' + size + 'x' + size + 'bb.jpg'); } else if (url.includes('-oss-')) { return url.replace(/w_\d+/, 'w_' + size).replace(/h_\d+/, 'h_' + size); } else { return url; } }); } public async fromURL(input: string): Promise<Array<TSoundItems>> { let chunks = input.split(' '); let items = []; for (let chunk of chunks) { let m; let originId; let type; let matchList = [ // radio [/zhubo\/(\d+)/, 'radio'], // episode [/-podcasts\/[^\/]+\d+\/[^\/]+?(\d+)$/, 'episode'], // podcast [/-podcasts\/[^\/]+?(\d+)$/, 'podcast'], ]; for (let [re, tp] of matchList) { m = (re as RegExp).exec(chunk); if (m) { type = tp; originId = m[1]; break; } } if (originId) { let item; switch (type) { case 'episode': item = await this.episode(originId); items.push(item); break; case 'podcast': item = await this.podcast(originId); items.push(item); break; case 'radio': item = await this.radio(originId); items.push(item); break; default: break; } } } return items; } }
the_stack
export interface EngravingDefaults { arrowShaftThickness: number; barlineSeparation: number; beamSpacing: number; beamThickness: number; bracketThickness: number; dashedBarlineDashLength: number; dashedBarlineGapLength: number; dashedBarlineThickness: number; hairpinThickness: number; legerLineExtension: number; legerLineThickness: number; lyricLineThickness: number; octaveLineThickness: number; pedalLineThickness: number; repeatBarlineDotSeparation: number; repeatEndingLineThickness: number; slurEndpointThickness: number; slurMidpointThickness: number; staffLineThickness: number; stemThickness: number; subBracketThickness: number; textEnclosureThickness: number; thickBarlineThickness: number; thinBarlineThickness: number; tieEndpointThickness: number; tieMidpointThickness: number; tupletBracketThickness: number; } export interface VerovioOptions { /********************** * Base short options * **********************/ /** * Select input format from: "abc", "darms", "humdrum", "mei", "pae", "xml" (musicxml) * * default: "mei" */ inputFrom?: string; /** * (int) Scale of the output in percent * * default: 100 * * max: 1000 * * min: 1 */ scale?: number; /** * (int) Seed the random number generator for XML IDs (default is random) * * default: 0 * * max: 0 * * min: 0 */ xmlIdSeed?: number; /********************************* * Input and page layout options * *********************************/ /** * Adjust the page height to the height of the content * * default: false */ adjustPageHeight?: boolean; /** * Adjust the page width to the width of the content * * default: false */ adjustPageWidth?: boolean; /** * Define page and system breaks layout * * default: "auto" */ breaks?: "none" | "auto" | "line" | "smart" | "encoded"; /** * (double) In smart breaks mode, the portion of system width usage at which an encoded sb will be used * * default: 0.66 * * max: 1 * * min: 0 */ breaksSmartSb?: number; /** * Control condensed score layout * * default: "auto" */ condense?: "none" | "auto" | "encoded"; /** * When condensing a score also condense the first page * * default: false */ condenseFirstPage?: boolean; /** * When condensing a score also condense pages with a tempo change * * default: false */ condenseTempoPages?: boolean; /** * Specify the linear spacing factor * * default: false */ evenNoteSpacing?: boolean; /** * Expand all referenced elements in the expansion <xml:id> * * default: "" */ expand?: string; /** * Control footer layout * * default: "auto" */ footer?: "none" | "auto" | "encoded" | "always"; /** * Control header layout * * default: "auto" */ header?: "none" | "auto" | "encoded"; /** * Include type attributes when importing from Humdrum * * default: false */ humType?: boolean; /** * Justify spacing vertically to fill the page * * default: false */ justifyVertically?: boolean; /** * The landscape paper orientation flag * * default: false */ landscape?: boolean; /** * Render ligatures as bracket instead of original notation * * default: false */ ligatureAsBracket?: boolean; /** * Convert mensural sections to measure-based MEI * * default: false */ mensuralToMeasure?: boolean; /** * (double) The last system is only justified if the unjustified width is greater than this percent * * default: 0.8 * * max: 1 * * min: 0 */ minLastJustification?: number; /** * Specify that the output in the SVG is given in mm (default is px) * * default: false */ mmOutput?: boolean; /** * Do not justify the system * * default: false */ noJustification?: boolean; /** * Render open control events * * default: false */ openControlEvents?: boolean; /** * Writes MEI out with no line indenting or non-content newlines. * * default: false */ outputFormatRaw?: boolean; /** * (int) Output indentation value for MEI and SVG * * default: 3 * * max: 10 * * min: 1 */ outputIndent?: number; /** * Output indentation with tabulation for MEI and SVG * * default: false */ outputIndentTab?: boolean; /** * Output SMuFL characters as XML entities instead of hex byte codes * * default: false */ outputSmuflXmlEntities?: boolean; /** * (int) The page height * * default: 2970 * * max: 60000 * * min: 100 */ pageHeight?: number; /** * (int) The page bottom margin * * default: 50 * * max: 500 * * min: 0 */ pageMarginBottom?: number; /** * (int) The page left margin * * default: 50 * * max: 500 * * min: 0 */ pageMarginLeft?: number; /** * (int) The page right margin * * default: 50 * * max: 500 * * min: 0 */ pageMarginRight?: number; /** * (int) The page top margin * * default: 50 * * max: 500 * * min: 0 */ pageMarginTop?: number; /** * (int) The page width * * default: 2100 * * max: 60000 * * min: 100 */ pageWidth?: number; /** * Preserves the analytical markup in MEI * * default: false */ preserveAnalyticalMarkup?: boolean; /** * Remove XML IDs in the MEI output that are not referenced * * default: false */ removeIds?: boolean; /** * Scale down page content to fit the page height if needed * * default: false */ shrinkToFit?: boolean; /** * Include bounding boxes in SVG output * * default: false */ svgBoundingBoxes?: boolean; /** * Writes SVG out with no line indenting or non-content newlines. * * default: false */ svgFormatRaw?: boolean; /** * Write data-id and data-class attributes for JS usage and id clash avoidance. * * default: false */ svgHtml5?: boolean; /** * Removes the xlink: prefix on href attributes for compatibility with some newer browsers. * * default: false */ svgRemoveXlink?: boolean; /** * Use viewBox on svg root element for easy scaling of document * * default: false */ svgViewBox?: boolean; /** * (int) The MEI unit (1⁄2 of the distance between the staff lines) * * default: 9 * * max: 20 * * min: 6 */ unit?: number; /** * Use brace glyph from current font * * default: false */ useBraceGlyph?: boolean; /** * Use information in the <facsimile> element to control the layout * * default: false */ useFacsimile?: boolean; /** * Use the pgFooter for all pages * * default: false */ usePgFooterForAll?: boolean; /** * Use the pgHeader for all pages * * default: false */ usePgHeaderForAll?: boolean; /************************** * General layout options * **************************/ /** * (double) The default distance between multiple barlines when locked together * * default: 0.8 * * max: 2 * * min: 0.5 */ barLineSeparation?: number; /** * (double) The barLine width * * default: 0.3 * * max: 0.8 * * min: 0.1 */ barLineWidth?: number; /** * (int) The maximum beam slope * * default: 10 * * max: 20 * * min: 1 */ beamMaxSlope?: number; /** * (int) The minimum beam slope * * default: 0 * * max: 0 * * min: 0 */ beamMinSlope?: number; /** * (double) The thickness of the system bracket * * default: 1 * * max: 2 * * min: 0.5 */ bracketThickness?: number; /** * Prevent single measures on the last page by fitting it into previous system * * default: false */ breaksNoWidow?: boolean; /** * (double) Set the ratio of normal clefs to changing clefs * * default: 0.66 * * max: 1 * * min: 0.25 */ clefChangeFactor?: number; /** * (double) The default distance from the staff for dynamic marks * * default: 1 * * max: 16 * * min: 0.5 */ dynamDist?: number; /** * Json describing defaults for engraving SMuFL elements */ engravingDefaults?: EngravingDefaults; /** * Set the music font * * default: "Leipzig" */ font?: string; /** * (double) The grace size ratio numerator * * default: 0.75 * * max: 1 * * min: 0.5 */ graceFactor?: number; /** * Align grace notes rhythmically with all staves * * default: false */ graceRhythmAlign?: boolean; /** * Align the right position of a grace group with all staves * * default: false */ graceRightAlign?: boolean; /** * (double) The haripin size in MEI units * * default: 3 * * max: 8 * * min: 1 */ hairpinSize?: number; /** * (double) The thickness of the hairpin * * default: 0.2 * * max: 0.8 * * min: 0.1 */ hairpinThickness?: number; /** * (double) The default distance from the staff of harmonic indications * * default: 1 * * max: 16 * * min: 0.5 */ harmDist?: number; /** * (double) Space between staves inside a braced group justification * * default: 1 * * max: 10 * * min: 0 */ justificationBraceGroup?: number; /** * (double) Space between staves inside a bracketed group justification * * default: 1 * * max: 10 * * min: 0 */ justificationBracketGroup?: number; /** * (double) The staff justification * * default: 1 * * max: 10 * * min: 0 */ justificationStaff?: number; /** * (double) The system spacing justification * * default: 1 * * max: 10 * * min: 0 */ justificationSystem?: number; /** * (double) The amount by which a ledger line should extend either side of a notehead * * default: 0.54 * * max: 1 * * min: 0.2 */ ledgerLineExtension?: number; /** * (double) The thickness of the ledger lines * * default: 0.25 * * max: 0.5 * * min: 0.1 */ ledgerLineThickness?: number; /** * (double) The lyric hyphen and dash length * * default: 1.2 * * max: 3 * * min: 0.5 */ lyricHyphenLength?: number; /** * (double) The lyric extender line thickness * * default: 0.25 * * max: 0.5 * * min: 0.1 */ lyricLineThickness?: number; /** * Do not show hyphens at the beginning of a system * * default: false */ lyricNoStartHyphen?: boolean; /** * (double) The lyrics size in MEI units * * default: 4.5 * * max: 8 * * min: 2 */ lyricSize?: number; /** * (double) The minmal margin above the lyrics in MEI units * * default: 2 * * max: 8 * * min: 0 */ lyricTopMinMargin?: number; /** * Collapse empty verse lines in lyrics * * default: false */ lyricVerseCollapse?: boolean; /** * (double) The lyric word space length * * default: 1.2 * * max: 3 * * min: 0.5 */ lyricWordSpace?: number; /** * (double) The MIDI tempo adjustment factor * * default: 1 * * max: 4 * * min: 0.2 */ midiTempoAdjustment?: number; /** * (int) The minimal measure width in MEI units * * default: 15 * * max: 30 * * min: 1 */ minMeasureWidth?: number; /** * (int) How frequently to place measure numbers * * default: 0 * * max: 64 * * min: 0 */ mnumInterval?: number; /** * Rendering style of multiple measure rests * * default: "auto" */ multiRestStyle?: "auto" | "default" | "block" | "symbols"; /** * Use alternative symbols for displaying octaves * * default: false */ octaveAlternativeSymbols?: boolean; /** * (double) The thickness of the line used for an octave line * * default: 0.2 * * max: 1 * * min: 0.1 */ octaveLineThickness?: number; /** * (double) The thickness of the line used for piano pedaling * * default: 0.2 * * max: 1 * * min: 0.1 */ pedalLineThickness?: number; /** * (double) The default horizontal distance between the dots and the inner barline of a repeat barline * * default: 0.3 * * max: 1 * * min: 0.1 */ repeatBarLineDotSeparation?: number; /** * (double) Repeat and ending line thickness * * default: 0.15 * * max: 2 * * min: 0.1 */ repeatEndingLineThickness?: number; /** * (int) Slur control points - higher value means more curved at the end * * default: 5 * * max: 10 * * min: 1 */ slurControlPoints?: number; /** * (int) Slur curve factor - high value means rounder slurs * * default: 10 * * max: 100 * * min: 1 */ slurCurveFactor?: number; /** * (double) The Endpoint slur thickness in MEI units * * default: 0.1 * * max: 0.25 * * min: 0.05 */ slurEndpointThickness?: number; /** * (int) Slur height factor - high value means flatter slurs * * default: 5 * * max: 100 * * min: 1 */ slurHeightFactor?: number; /** * (double) The maximum slur height in MEI units * * default: 3 * * max: 6 * * min: 2 */ slurMaxHeight?: number; /** * (int) The maximum slur slope in degrees * * default: 20 * * max: 60 * * min: 0 */ slurMaxSlope?: number; /** * (double) The midpoint slur thickness in MEI units * * default: 0.6 * * max: 1.2 * * min: 0.2 */ slurMidpointThickness?: number; /** * (double) The minimum slur height in MEI units * * default: 1.2 * * max: 2 * * min: 0.3 */ slurMinHeight?: number; /** * (int) Minimum space between staves inside a braced group in MEI units * * default: 12 * * max: 48 * * min: 0 */ spacingBraceGroup?: number; /** * (int) Minimum space between staves inside a bracketed group in MEI units * * default: 12 * * max: 48 * * min: 0 */ spacingBracketGroup?: number; /** * Detect long duration for adjusting spacing * * default: false */ spacingDurDetection?: boolean; /** * (double) Specify the linear spacing factor * * default: 0.25 * * max: 1 * * min: 0 */ spacingLinear?: number; /** * (double) Specify the non-linear spacing factor * * default: 0.6 * * max: 1 * * min: 0 */ spacingNonLinear?: number; /** * (int) The staff minimal spacing in MEI units * * default: 12 * * max: 48 * * min: 0 */ spacingStaff?: number; /** * (int) The system minimal spacing in MEI units * * default: 12 * * max: 48 * * min: 0 */ spacingSystem?: number; /** * (double) The staff line width in unit * * default: 0.15 * * max: 0.3 * * min: 0.1 */ staffLineWidth?: number; /** * (double) The stem width * * default: 0.2 * * max: 0.5 * * min: 0.1 */ stemWidth?: number; /** * (double) The thickness of system sub-bracket * * default: 0.2 * * max: 2 * * min: 0.1 */ subBracketThickness?: number; /** * The display of system dividers * * default: "auto" */ systemDivider?: "none" | "auto" | "left" | "left-right"; /** * (int) Maximun number of systems per page * * default: 0 * * max: 24 * * min: 0 */ systemMaxPerPage?: number; /** * (double) The thickness of the line text enclosing box * * default: 0.2 * * max: 0.8 * * min: 0.1 */ textEnclosureThickness?: number; /** * (double) The thickness of the thick barline * * default: 1 * * max: 2 * * min: 0.5 */ thickBarlineThickness?: number; /** * (double) The Endpoint tie thickness in MEI units * * default: 0.1 * * max: 0.25 * * min: 0.05 */ tieEndpointThickness?: number; /** * (double) The midpoint tie thickness in MEI units * * default: 0.5 * * max: 1 * * min: 0.2 */ tieMidpointThickness?: number; /** * (double) The thickness of the tuplet bracket * * default: 0.2 * * max: 0.8 * * min: 0.1 */ tupletBracketThickness?: number; /** * Placement of tuplet number on the side of the note head * * default: false */ tupletNumHead?: boolean; /************************************ * Element selectors and processing * ************************************/ /** * Set the xPath query for selecting <app> child elements, for example: "./rdg[contains(@source, 'source-id')]"; by default the <lem> or the first <rdg> is selected * * default: [] */ appXPathQuery?: string[]; /** * Set the xPath query for selecting <choice> child elements, for example: "./orig"; by default the first child is selected * * default: [] */ choiceXPathQuery?: string[]; /** * Set the xPath query for selecting the <mdiv> to be rendered; only one <mdiv> can be rendered * * default: "" */ mdivXPathQuery?: string; /** * Set the xPath query for selecting <subst> child elements, for example: "./del"; by default the first child is selected * * default: [] */ substXPathQuery?: string[]; /** * SUMMARY * * default: "" */ transpose?: string; /** * Transpose only the selected content and ignore unselected editorial content * * default: false */ transposeSelectedOnly?: boolean; /******************* * Element margins * *******************/ /** * (double) The margin for artic in MEI units * * default: 0.75 * * max: 10 * * min: 0 */ bottomMarginArtic?: number; /** * (double) The margin for harm in MEI units * * default: 1 * * max: 10 * * min: 0 */ bottomMarginHarm?: number; /** * (double) The margin for header in MEI units * * default: 8 * * max: 24 * * min: 0 */ bottomMarginHeader?: number; /** * (double) The default bottom margin * * default: 0.5 * * max: 5 * * min: 0 */ defaultBottomMargin?: number; /** * (double) The default left margin * * default: 0 * * max: 2 * * min: 0 */ defaultLeftMargin?: number; /** * (double) The default right margin * * default: 0 * * max: 2 * * min: 0 */ defaultRightMargin?: number; /** * (double) The default top margin * * default: 0.5 * * max: 6 * * min: 0 */ defaultTopMargin?: number; /** * (double) The margin for accid in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginAccid?: number; /** * (double) The margin for barLine in MEI units * * default: 0 * * max: 2 * * min: 0 */ leftMarginBarLine?: number; /** * (double) The margin for beatRpt in MEI units * * default: 2 * * max: 2 * * min: 0 */ leftMarginBeatRpt?: number; /** * (double) The margin for chord in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginChord?: number; /** * (double) The margin for clef in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginClef?: number; /** * (double) The margin for keySig in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginKeySig?: number; /** * (double) The margin for left barLine in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginLeftBarLine?: number; /** * (double) The margin for mRest in MEI units * * default: 0 * * max: 2 * * min: 0 */ leftMarginMRest?: number; /** * (double) The margin for mRpt2 in MEI units * * default: 0 * * max: 2 * * min: 0 */ leftMarginMRpt2?: number; /** * (double) The margin for mensur in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginMensur?: number; /** * (double) The margin for meterSig in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginMeterSig?: number; /** * (double) The margin for multiRest in MEI units * * default: 0 * * max: 2 * * min: 0 */ leftMarginMultiRest?: number; /** * (double) The margin for multiRpt in MEI units * * default: 0 * * max: 2 * * min: 0 */ leftMarginMultiRpt?: number; /** * (double) The margin for note in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginNote?: number; /** * (double) The margin for rest in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginRest?: number; /** * (double) The margin for right barLine in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginRightBarLine?: number; /** * (double) The margin for tabDurSym in MEI units * * default: 1 * * max: 2 * * min: 0 */ leftMarginTabDurSym?: number; /** * (double) The right margin for accid in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginAccid?: number; /** * (double) The right margin for barLine in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginBarLine?: number; /** * (double) The right margin for beatRpt in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginBeatRpt?: number; /** * (double) The right margin for chord in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginChord?: number; /** * (double) The right margin for clef in MEI units * * default: 1 * * max: 2 * * min: 0 */ rightMarginClef?: number; /** * (double) The right margin for keySig in MEI units * * default: 1 * * max: 2 * * min: 0 */ rightMarginKeySig?: number; /** * (double) The right margin for left barLine in MEI units * * default: 1 * * max: 2 * * min: 0 */ rightMarginLeftBarLine?: number; /** * (double) The right margin for mRest in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginMRest?: number; /** * (double) The right margin for mRpt2 in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginMRpt2?: number; /** * (double) The right margin for mensur in MEI units * * default: 1 * * max: 2 * * min: 0 */ rightMarginMensur?: number; /** * (double) The right margin for meterSig in MEI units * * default: 1 * * max: 2 * * min: 0 */ rightMarginMeterSig?: number; /** * (double) The right margin for multiRest in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginMultiRest?: number; /** * (double) The right margin for multiRpt in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginMultiRpt?: number; /** * (double) The right margin for note in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginNote?: number; /** * (double) The right margin for rest in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginRest?: number; /** * (double) The right margin for right barLine in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginRightBarLine?: number; /** * (double) The right margin for tabDurSym in MEI units * * default: 0 * * max: 2 * * min: 0 */ rightMarginTabDurSym?: number; /** * (double) The margin for artic in MEI units * * default: 0.75 * * max: 10 * * min: 0 */ topMarginArtic?: number; /** * (double) The margin for harm in MEI units * * default: 1 * * max: 10 * * min: 0 */ topMarginHarm?: number; }
the_stack
let feature_params = false; interface VertexAttribs { [name: string]: number } const vertexAttribs: VertexAttribs = { "meshPosition": 0 }; const TRIANGLE_PAIR = 2; const TRIANGLE_VERTICIES = 3; const VEC2_COUNT = 2; const VEC2_X = 0; const VEC2_Y = 1; const CANVAS_WIDTH = 112; const CANVAS_HEIGHT = 112; function compileShaderSource(gl: WebGLRenderingContext, source: string, shaderType: GLenum): WebGLShader { function shaderTypeToString() { switch (shaderType) { case gl.VERTEX_SHADER: return 'Vertex'; case gl.FRAGMENT_SHADER: return 'Fragment'; default: return shaderType; } } const shader = gl.createShader(shaderType); if (shader === null) { throw new Error(`Could not create a new shader`); } gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { throw new Error(`Could not compile ${shaderTypeToString()} shader: ${gl.getShaderInfoLog(shader)}`); } return shader; } function linkShaderProgram(gl: WebGLRenderingContext, shaders: WebGLShader[], vertexAttribs: VertexAttribs): WebGLProgram { const program = gl.createProgram(); if (program === null) { throw new Error('Could not create a new shader program'); } for (let shader of shaders) { gl.attachShader(program, shader); } for (let vertexName in vertexAttribs) { gl.bindAttribLocation(program, vertexAttribs[vertexName], vertexName); } gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw new Error(`Could not link shader program: ${gl.getProgramInfoLog(program)}`); } return program; } function createTextureFromImage(gl: WebGLRenderingContext, image: TexImageSource): WebGLTexture { let textureId = gl.createTexture(); if (textureId === null) { throw new Error('Could not create a new WebGL texture'); } gl.bindTexture(gl.TEXTURE_2D, textureId); gl.texImage2D( gl.TEXTURE_2D, // target 0, // level gl.RGBA, // internalFormat gl.RGBA, // srcFormat gl.UNSIGNED_BYTE, // srcType image // image ); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); return textureId; } interface Uniforms { [name: string]: WebGLUniformLocation | null } interface CompiledFilter { id: WebGLProgram, uniforms: Uniforms, duration: Expr, transparent: string | null, paramsPanel: Tag } interface Snapshot { [name: string]: { uniform: WebGLUniformLocation | null, value: number | null } } // TODO(#54): pre-load all of the filters and just switch between them without loading/unloading them constantly function loadFilterProgram(gl: WebGLRenderingContext, filter: Filter, vertexAttribs: VertexAttribs): CompiledFilter { let vertexShader = compileShaderSource(gl, filter.vertex, gl.VERTEX_SHADER); let fragmentShader = compileShaderSource(gl, filter.fragment, gl.FRAGMENT_SHADER); let id = linkShaderProgram(gl, [vertexShader, fragmentShader], vertexAttribs); gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader); gl.useProgram(id); let uniforms: Uniforms = { "resolution": gl.getUniformLocation(id, 'resolution'), "time": gl.getUniformLocation(id, 'time'), "emoteSize": gl.getUniformLocation(id, 'emoteSize'), }; // TODO(#55): there no "reset to default" button in the params panel of a filter let paramsPanel = div().att$("class", "widget-element"); let paramsInputs: {[name: string]: Tag} = {}; for (let paramName in filter.params) { if (paramName in uniforms) { throw new Error(`Redefinition of existing uniform parameter ${paramName}`); } switch (filter.params[paramName].type) { case "float": { const valuePreview = span(filter.params[paramName].init.toString()); const valueInput = input("range"); if (filter.params[paramName].min !== undefined) { valueInput.att$("min", filter.params[paramName].min); } if (filter.params[paramName].max !== undefined) { valueInput.att$("max", filter.params[paramName].max); } if (filter.params[paramName].step !== undefined) { valueInput.att$("step", filter.params[paramName].step); } if (filter.params[paramName].init !== undefined) { valueInput.att$("value", filter.params[paramName].init); } paramsInputs[paramName] = valueInput; valueInput.oninput = function () { valuePreview.innerText = this.value; paramsPanel.dispatchEvent(new CustomEvent("paramsChanged")); }; const label: string = filter.params[paramName].label ?? paramName; paramsPanel.appendChild(div( span(`${label}: `), valuePreview, div(valueInput), )); } break; default: { throw new Error(`Filter parameters do not support type ${filter.params[paramName].type}`) } } uniforms[paramName] = gl.getUniformLocation(id, paramName); } paramsPanel.paramsSnapshot$ = function() { let snapshot: Snapshot = {}; for (let paramName in paramsInputs) { snapshot[paramName] = { "uniform": uniforms[paramName], "value": Number(paramsInputs[paramName].value) }; } return snapshot; }; return { "id": id, "uniforms": uniforms, "duration": compile_expr(filter.duration), "transparent": filter.transparent, "paramsPanel": paramsPanel, }; } function ImageSelector() { const imageInput = input("file"); const imagePreview = img("img/tsodinClown.png") .att$("class", "widget-element") .att$("width", CANVAS_WIDTH); const root = div( div(imageInput).att$("class", "widget-element"), imagePreview ).att$("class", "widget"); root.selectedImage$ = function() { return imagePreview; }; root.selectedFileName$ = function() { function removeFileNameExt(fileName: string): string { if (fileName.includes('.')) { return fileName.split('.').slice(0, -1).join('.'); } else { return fileName; } } const file = imageInput.files[0]; return file ? removeFileNameExt(file.name) : 'result'; }; root.updateFiles$ = function(files: FileList) { imageInput.files = files; imageInput.onchange(); } imagePreview.addEventListener('load', function(this: HTMLImageElement) { root.dispatchEvent(new CustomEvent("imageSelected", { detail: { imageData: this } })); }); imagePreview.addEventListener('error', function(this: HTMLImageElement) { imageInput.value = ''; this.src = 'img/error.png'; }); imageInput.onchange = function() { imagePreview.src = URL.createObjectURL(this.files[0]); }; return root; } function FilterList() { const root = select(); // Populating the FilterList for (let name in filters) { root.add(new Option(name)); } root.selectedFilter$ = function() { return filters[root.selectedOptions[0].value]; }; root.onchange = function() { root.dispatchEvent(new CustomEvent('filterChanged', { detail: { filter: root.selectedFilter$() } })); }; root.addEventListener('wheel', function(e: WheelEvent) { e.preventDefault(); if (e.deltaY < 0) { root.selectedIndex = Math.max(root.selectedIndex - 1, 0); } if (e.deltaY > 0) { root.selectedIndex = Math.min(root.selectedIndex + 1, root.length - 1); } root.onchange(); }); return root; } function FilterSelector() { const filterList_ = FilterList(); const filterPreview = canvas() .att$("width", CANVAS_WIDTH) .att$("height", CANVAS_HEIGHT); const root = div( div("Filter: ", filterList_) .att$("class", "widget-element"), filterPreview.att$("class", "widget-element"), ).att$("class", "widget"); const gl = filterPreview.getContext("webgl", {antialias: false, alpha: false}); if (!gl) { throw new Error("Could not initialize WebGL context"); } // Initialize GL { gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); // Mesh Position { let meshPositionBufferData = new Float32Array(TRIANGLE_PAIR * TRIANGLE_VERTICIES * VEC2_COUNT); for (let triangle = 0; triangle < TRIANGLE_PAIR; ++triangle) { for (let vertex = 0; vertex < TRIANGLE_VERTICIES; ++vertex) { const quad = triangle + vertex; const index = triangle * TRIANGLE_VERTICIES * VEC2_COUNT + vertex * VEC2_COUNT; meshPositionBufferData[index + VEC2_X] = (2 * (quad & 1) - 1); meshPositionBufferData[index + VEC2_Y] = (2 * ((quad >> 1) & 1) - 1); } } let meshPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, meshPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, meshPositionBufferData, gl.STATIC_DRAW); const meshPositionAttrib = vertexAttribs['meshPosition']; gl.vertexAttribPointer( meshPositionAttrib, VEC2_COUNT, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(meshPositionAttrib); } } // TODO(#49): FilterSelector does not handle loadFilterProgram() failures let emoteImage: HTMLImageElement | undefined = undefined; let emoteTexture: WebGLTexture | undefined = undefined; let program: CompiledFilter | undefined = undefined; function syncParams() { if (program) { const snapshot = program.paramsPanel.paramsSnapshot$(); for (let paramName in snapshot) { gl.uniform1f(snapshot[paramName].uniform, snapshot[paramName].value); } } } program = loadFilterProgram(gl, filterList_.selectedFilter$(), vertexAttribs); program.paramsPanel.addEventListener('paramsChanged', syncParams); if (feature_params) { root.appendChild(program.paramsPanel); } syncParams(); root.updateImage$ = function(newEmoteImage: HTMLImageElement) { emoteImage = newEmoteImage; if (emoteTexture) { gl.deleteTexture(emoteTexture); } emoteTexture = createTextureFromImage(gl, emoteImage); }; filterList_.addEventListener('filterChanged', function(e: any) { if (program) { gl.deleteProgram(program.id); program.paramsPanel.removeEventListener('paramsChanged', syncParams); if (feature_params) { root.removeChild(program.paramsPanel); } } program = loadFilterProgram(gl, e.detail.filter, vertexAttribs); program.paramsPanel.addEventListener('paramsChanged', syncParams); if (feature_params) { root.appendChild(program.paramsPanel); } syncParams(); }); root.render$ = function (filename: string): any | undefined { if (program === undefined) { console.warn('Could not rendering anything because the filter was not selected'); return undefined; } if (emoteImage == undefined) { console.warn('Could not rendering anything because the image was not selected'); return undefined; } // TODO(#74): gif.js typing are absolutely broken const gif = new GIF({ workers: 5, quality: 10, width: CANVAS_WIDTH, height: CANVAS_HEIGHT, transparent: program.transparent, }); const context: UserContext = { "vars": { "Math.PI": Math.PI } }; if (context.vars !== undefined) { const snapshot = program.paramsPanel.paramsSnapshot$(); for (let paramName in snapshot) { context.vars[paramName] = snapshot[paramName].value; } } const fps = 30; const dt = 1.0 / fps; // TODO(#59): come up with a reasonable way to handle malicious durations const duration = Math.min(run_expr(program.duration, context), 60); const renderProgress = document.getElementById("render-progress"); if (renderProgress === null) { throw new Error('Could not find "render-progress"'); } const renderSpinner = document.getElementById("render-spinner"); if (renderSpinner === null) { throw new Error('Could not find "render-spinner"'); } const renderPreview = document.getElementById("render-preview") as HTMLImageElement; if (renderPreview === null) { throw new Error('Could not find "render-preview"'); } const renderDownload = document.getElementById("render-download") as HTMLAnchorElement; if (renderDownload === null) { throw new Error('Could not find "render-download"'); } renderPreview.style.display = "none"; renderSpinner.style.display = "block"; let t = 0.0; while (t <= duration) { gl.uniform1f(program.uniforms.time, t); gl.uniform2f(program.uniforms.resolution, CANVAS_WIDTH, CANVAS_HEIGHT); gl.uniform2f(program.uniforms.emoteSize, emoteImage.width, emoteImage.height); gl.clearColor(0.0, 1.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, TRIANGLE_PAIR * TRIANGLE_VERTICIES); let pixels = new Uint8ClampedArray(4 * CANVAS_WIDTH * CANVAS_HEIGHT); gl.readPixels(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT, gl.RGBA, gl.UNSIGNED_BYTE, pixels); // Flip the image vertically { const center = Math.floor(CANVAS_HEIGHT / 2); for (let y = 0; y < center; ++y) { const row = 4 * CANVAS_WIDTH; for (let x = 0; x < row; ++x) { const ai = y * 4 * CANVAS_WIDTH + x; const bi = (CANVAS_HEIGHT - y - 1) * 4 * CANVAS_WIDTH + x; const a = pixels[ai]; const b = pixels[bi]; pixels[ai] = b; pixels[bi] = a; } } } gif.addFrame(new ImageData(pixels, CANVAS_WIDTH, CANVAS_HEIGHT), { delay: dt * 1000, dispose: 2, }); renderProgress.style.width = `${(t / duration) * 50}%`; t += dt; } gif.on('finished', (blob) => { renderPreview.src = URL.createObjectURL(blob); renderPreview.style.display = "block"; renderDownload.href = renderPreview.src; renderDownload.download = filename; renderDownload.style.display = "block"; renderSpinner.style.display = "none"; }); gif.on('progress', (p) => { renderProgress.style.width = `${50 + p * 50}%`; }); gif.render(); return gif; }; // Rendering Loop { const step = function(timestamp: number) { gl.clearColor(0.0, 1.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); if (program && emoteImage) { gl.uniform1f(program.uniforms.time, timestamp * 0.001); gl.uniform2f(program.uniforms.resolution, filterPreview.width, filterPreview.height); gl.uniform2f(program.uniforms.emoteSize, emoteImage.width, emoteImage.height); gl.drawArrays(gl.TRIANGLES, 0, TRIANGLE_PAIR * TRIANGLE_VERTICIES); } window.requestAnimationFrame(step); } window.requestAnimationFrame(step); } return root; } window.onload = () => { feature_params = new URLSearchParams(document.location.search).has("feature-params"); const filterSelectorEntry = document.getElementById('filter-selector-entry'); if (filterSelectorEntry === null) { throw new Error('Could not find "filter-selector-entry"'); } const imageSelectorEntry = document.getElementById('image-selector-entry'); if (imageSelectorEntry === null) { throw new Error('Could not find "image-selector-entry"'); } const imageSelector = ImageSelector(); const filterSelector = FilterSelector(); imageSelector.addEventListener('imageSelected', function(e: CustomEvent) { filterSelector.updateImage$(e.detail.imageData); }); filterSelectorEntry.appendChild(filterSelector); imageSelectorEntry.appendChild(imageSelector); // drag file from anywhere document.ondrop = function(event: DragEvent) { event.preventDefault(); imageSelector.updateFiles$(event.dataTransfer?.files); } document.ondragover = function(event) { event.preventDefault(); } // TODO(#50): extract "renderer" as a separate grecha.js component // Similar to imageSelector and filterSelector let gif: GIF | undefined = undefined; const renderButton = document.getElementById("render"); if (renderButton === null) { throw new Error('Could not find "render"'); } renderButton.onclick = function() { if (gif && gif.running) { gif.abort(); } const fileName = imageSelector.selectedFileName$(); gif = filterSelector.render$(`${fileName}.gif`); }; } // TODO(#75): run typescript compiler on CI
the_stack
import React, { FunctionComponent, useMemo } from "react"; import { CoinUtils, Coin } from "@keplr-wallet/unit"; import { AppCurrency } from "@keplr-wallet/types"; import yaml from "js-yaml"; import { CoinPrimitive } from "@keplr-wallet/stores"; import { Text } from "react-native"; import { useStyle } from "../../styles"; import { Bech32Address } from "@keplr-wallet/cosmos"; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import Hypher from "hypher"; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import english from "hyphenation.en-us"; const h = new Hypher(english); // https://zpl.fi/hyphenation-in-react-native/ function hyphen(text: string): string { return h.hyphenateText(text); } export interface MessageObj { readonly type: string; readonly value: unknown; } export interface MsgSend { value: { amount: [ { amount: string; denom: string; } ]; from_address: string; to_address: string; }; } export interface MsgTransfer { value: { source_port: string; source_channel: string; token: { denom: string; amount: string; }; sender: string; receiver: string; timeout_height: { revision_number: string | undefined; revision_height: string; }; }; } export interface MsgDelegate { value: { amount: { amount: string; denom: string; }; delegator_address: string; validator_address: string; }; } export interface MsgUndelegate { value: { amount: { amount: string; denom: string; }; delegator_address: string; validator_address: string; }; } export interface MsgWithdrawDelegatorReward { value: { delegator_address: string; validator_address: string; }; } export interface MsgBeginRedelegate { value: { amount: { amount: string; denom: string; }; delegator_address: string; validator_dst_address: string; validator_src_address: string; }; } export interface MsgVote { value: { proposal_id: string; voter: string; // In the stargate, option would be the enum (0: empty, 1: yes, 2: abstain, 3: no, 4: no with veto). option: string | number; }; } export interface MsgInstantiateContract { value: { // Admin field can be omitted. admin?: string; sender: string; code_id: string; label: string; // eslint-disable-next-line @typescript-eslint/ban-types init_msg: object; init_funds: [ { amount: string; denom: string; } ]; }; } // This message can be a normal cosmwasm message or a secret-wasm message. export interface MsgExecuteContract { value: { contract: string; // If message is for secret-wasm, msg will be the base64 encoded and encrypted string. // eslint-disable-next-line @typescript-eslint/ban-types msg: object | string; sender: string; sent_funds: [ { amount: string; denom: string; } ]; // The bottom two fields are for secret-wasm message. callback_code_hash?: string; callback_sig?: string | null; }; } export interface MsgLink { value: { links: [ { from: string; to: string; } ]; address: string; }; } // eslint-disable-next-line @typescript-eslint/ban-types export function renderUnknownMessage(msg: object) { return { icon: undefined, title: "Custom", content: <UnknownMsgView msg={msg} />, scrollViewHorizontal: true, }; } export function renderMsgSend( currencies: AppCurrency[], amount: CoinPrimitive[], toAddress: string ) { const receives: CoinPrimitive[] = []; for (const coinPrimitive of amount) { const coin = new Coin(coinPrimitive.denom, coinPrimitive.amount); const parsed = CoinUtils.parseDecAndDenomFromCoin(currencies, coin); receives.push({ amount: clearDecimals(parsed.amount), denom: parsed.denom, }); } return { title: "Send", content: ( <Text> <Text style={{ fontWeight: "bold" }}> {hyphen(Bech32Address.shortenAddress(toAddress, 20))} </Text> <Text>{" will receive "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen( receives .map((coin) => { return `${coin.amount} ${coin.denom}`; }) .join(",") )} </Text> </Text> ), }; } export function renderMsgTransfer( currencies: AppCurrency[], amount: CoinPrimitive, receiver: string, channelId: string ) { const coin = new Coin(amount.denom, amount.amount); const parsed = CoinUtils.parseDecAndDenomFromCoin(currencies, coin); amount = { amount: clearDecimals(parsed.amount), denom: parsed.denom, }; return { title: "IBC Transfer", content: ( <Text> <Text>{"Send "}</Text> <Text style={{ fontWeight: "bold", }} > {hyphen(`${amount.amount} ${amount.denom}`)} </Text> <Text>{" to "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(Bech32Address.shortenAddress(receiver, 20))} </Text> <Text>{" on "}</Text> <Text style={{ fontWeight: "bold" }}>{channelId}</Text> </Text> ), }; } export function renderMsgBeginRedelegate( currencies: AppCurrency[], amount: CoinPrimitive, validatorSrcAddress: string, validatorDstAddress: string ) { const parsed = CoinUtils.parseDecAndDenomFromCoin( currencies, new Coin(amount.denom, amount.amount) ); amount = { amount: clearDecimals(parsed.amount), denom: parsed.denom, }; return { title: "Switch Validator", content: ( <Text> <Text>{"Switch validator "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(`${amount.amount} ${amount.denom}`)} </Text> <Text>{" from "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(Bech32Address.shortenAddress(validatorSrcAddress, 24))} </Text> <Text>{" to "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(Bech32Address.shortenAddress(validatorDstAddress, 24))} </Text> </Text> ), }; } export function renderMsgUndelegate( currencies: AppCurrency[], amount: CoinPrimitive, validatorAddress: string ) { const parsed = CoinUtils.parseDecAndDenomFromCoin( currencies, new Coin(amount.denom, amount.amount) ); amount = { amount: clearDecimals(parsed.amount), denom: parsed.denom, }; return { title: "Unstake", content: ( <Text> <Text>{"Unstake "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(`${amount.amount} ${amount.denom}`)} </Text> <Text>{" from "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(Bech32Address.shortenAddress(validatorAddress, 24))} </Text> <Text>{`\n${hyphen( "Asset will be liquid after unbonding period" )}`}</Text> </Text> ), }; } export function renderMsgDelegate( currencies: AppCurrency[], amount: CoinPrimitive, validatorAddress: string ) { const parsed = CoinUtils.parseDecAndDenomFromCoin( currencies, new Coin(amount.denom, amount.amount) ); amount = { amount: clearDecimals(parsed.amount), denom: parsed.denom, }; // Delegate <b>{amount}</b> to <b>{validator}</b> return { title: "Stake", content: ( <Text> <Text>{"Stake "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(`${amount.amount} ${amount.denom}`)} </Text> <Text>{" to "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(Bech32Address.shortenAddress(validatorAddress, 24))} </Text> </Text> ), }; } export function renderMsgWithdrawDelegatorReward(validatorAddress: string) { return { title: "Claim Staking Reward", content: ( <Text> <Text>{"Claim pending staking reward from "}</Text> <Text style={{ fontWeight: "bold" }}> {hyphen(Bech32Address.shortenAddress(validatorAddress, 34))} </Text> </Text> ), }; } export function renderMsgVote(proposalId: string, option: string | number) { const textualOption = (() => { if (typeof option === "string") { return option; } switch (option) { case 0: return "Empty"; case 1: return "Yes"; case 2: return "Abstain"; case 3: return "No"; case 4: return "No with veto"; default: return "Unspecified"; } })(); // Vote <b>{option}</b> on <b>Proposal {id}</b> return { title: "Vote", content: ( <Text> <Text>{"Vote "}</Text> <Text style={{ fontWeight: "bold" }}>{textualOption}</Text> <Text>{" on "}</Text> <Text style={{ fontWeight: "bold" }}>{`Proposal ${proposalId}`}</Text> </Text> ), }; } /* export function renderMsgInstantiateContract( currencies: Currency[], intl: IntlShape, initFunds: CoinPrimitive[], admin: string | undefined, codeId: string, label: string, // eslint-disable-next-line @typescript-eslint/ban-types initMsg: object ) { const funds: { amount: string; denom: string }[] = []; for (const coinPrimitive of initFunds) { const coin = new Coin(coinPrimitive.denom, coinPrimitive.amount); const parsed = CoinUtils.parseDecAndDenomFromCoin(currencies, coin); funds.push({ amount: clearDecimals(parsed.amount), denom: parsed.denom, }); } return { icon: "fas fa-cog", title: intl.formatMessage({ id: "sign.list.message.wasm/MsgInstantiateContract.title", }), content: ( <React.Fragment> <FormattedMessage id="sign.list.message.wasm/MsgInstantiateContract.content" values={{ b: (...chunks: any[]) => <b>{chunks}</b>, br: <br />, admin: admin ? Bech32Address.shortenAddress(admin, 30) : "", ["only-admin-exist"]: (...chunks: any[]) => (admin ? chunks : ""), codeId: codeId, label: label, ["only-funds-exist"]: (...chunks: any[]) => funds.length > 0 ? chunks : "", funds: funds .map((coin) => { return `${coin.amount} ${coin.denom}`; }) .join(","), }} /> <br /> <WasmExecutionMsgView msg={initMsg} /> </React.Fragment> ), }; } export function renderMsgExecuteContract( currencies: Currency[], intl: IntlShape, sentFunds: CoinPrimitive[], callbackCodeHash: string | undefined, contract: string, // eslint-disable-next-line @typescript-eslint/ban-types msg: object | string ) { const sent: { amount: string; denom: string }[] = []; for (const coinPrimitive of sentFunds) { const coin = new Coin(coinPrimitive.denom, coinPrimitive.amount); const parsed = CoinUtils.parseDecAndDenomFromCoin(currencies, coin); sent.push({ amount: clearDecimals(parsed.amount), denom: parsed.denom, }); } const isSecretWasm = callbackCodeHash != null; return { icon: "fas fa-cog", title: intl.formatMessage({ id: "sign.list.message.wasm/MsgExecuteContract.title", }), content: ( <React.Fragment> <FormattedMessage id="sign.list.message.wasm/MsgExecuteContract.content" values={{ b: (...chunks: any[]) => <b>{chunks}</b>, br: <br />, address: Bech32Address.shortenAddress(contract, 26), ["only-sent-exist"]: (...chunks: any[]) => sent.length > 0 ? chunks : "", sent: sent .map((coin) => { return `${coin.amount} ${coin.denom}`; }) .join(","), }} /> {isSecretWasm ? ( <React.Fragment> <br /> <Badge color="primary" pill style={{ marginTop: "6px", marginBottom: "6px" }} > <FormattedMessage id="sign.list.message.wasm/MsgExecuteContract.content.badge.secret-wasm" /> </Badge> </React.Fragment> ) : ( <br /> )} <WasmExecutionMsgView msg={msg} /> </React.Fragment> ), }; } export const WasmExecutionMsgView: FunctionComponent<{ // eslint-disable-next-line @typescript-eslint/ban-types msg: object | string; }> = observer(({ msg }) => { const { chainStore, accountStore } = useStore(); const [isOpen, setIsOpen] = useState(true); const intl = useIntl(); const toggleOpen = () => setIsOpen((isOpen) => !isOpen); const [detailsMsg, setDetailsMsg] = useState(() => JSON.stringify(msg, null, 2) ); const [warningMsg, setWarningMsg] = useState(""); useEffect(() => { // If msg is string, it will be the message for secret-wasm. // So, try to decrypt. // But, if this msg is not encrypted via Keplr, Keplr cannot decrypt it. // TODO: Handle the error case. If an error occurs, rather than rejecting the signing, it informs the user that Kepler cannot decrypt it and allows the user to choose. if (typeof msg === "string") { (async () => { try { let cipherText = Buffer.from(Buffer.from(msg, "base64")); // Msg is start with 32 bytes nonce and 32 bytes public key. const nonce = cipherText.slice(0, 32); cipherText = cipherText.slice(64); const keplr = await accountStore .getAccount(chainStore.current.chainId) .getKeplr(); if (!keplr) { throw new Error("Can't get the keplr API"); } const enigmaUtils = keplr.getEnigmaUtils(chainStore.current.chainId); let plainText = Buffer.from( await enigmaUtils.decrypt(cipherText, nonce) ); // Remove the contract code hash. plainText = plainText.slice(64); setDetailsMsg( JSON.stringify(JSON.parse(plainText.toString()), null, 2) ); setWarningMsg(""); } catch { setWarningMsg( intl.formatMessage({ id: "sign.list.message.wasm/MsgExecuteContract.content.warning.secret-wasm.failed-decryption", }) ); } })(); } }, [chainStore, chainStore.current.chainId, intl, msg]); return ( <div> {isOpen ? ( <React.Fragment> <pre style={{ width: "280px" }}>{isOpen ? detailsMsg : ""}</pre> {warningMsg ? <div>{warningMsg}</div> : null} </React.Fragment> ) : null} <Button size="sm" style={{ float: "right", marginRight: "6px" }} onClick={(e) => { e.preventDefault(); e.stopPropagation(); toggleOpen(); }} > {isOpen ? intl.formatMessage({ id: "sign.list.message.wasm.button.close", }) : intl.formatMessage({ id: "sign.list.message.wasm.button.details", })} </Button> </div> ); }); */ // eslint-disable-next-line @typescript-eslint/ban-types export const UnknownMsgView: FunctionComponent<{ msg: object }> = ({ msg }) => { const style = useStyle(); const prettyMsg = useMemo(() => { try { return yaml.dump(msg); } catch (e) { console.log(e); return "Failed to decode the msg"; } }, [msg]); return ( <Text style={style.flatten(["body3", "color-text-black-low"])}> {prettyMsg} </Text> ); }; export function clearDecimals(dec: string): string { if (!dec.includes(".")) { return dec; } for (let i = dec.length - 1; i >= 0; i--) { if (dec[i] === "0") { dec = dec.slice(0, dec.length - 1); } else { break; } } if (dec.length > 0 && dec[dec.length - 1] === ".") { dec = dec.slice(0, dec.length - 1); } return dec; }
the_stack
* @module RpcInterface */ import { BentleyStatus } from "@itwin/core-bentley"; import { IModelError, IpcWebSocket, RpcEndpoint, RpcProtocol, RpcPushChannel, RpcPushConnection, RpcRequest, RpcRequestFulfillment, RpcSerializedValue, SerializedRpcRequest, } from "@itwin/core-common"; import { MobileEventLoop } from "./MobileEventLoop"; import { MobileIpcTransport } from "./MobileIpc"; import { MobilePushConnection, MobilePushTransport } from "./MobilePush"; import { MobileRpcConfiguration } from "./MobileRpcManager"; import { MobileRpcRequest } from "./MobileRpcRequest"; /** @beta */ export type MobileRpcChunks = Array<string | Uint8Array>; /** @beta */ export interface MobileRpcGateway { handler: (payload: ArrayBuffer | string, connectionId: number) => void; sendString: (message: string, connectionId: number) => void; sendBinary: (message: Uint8Array, connectionId: number) => void; port: number; connectionId: number; } /** RPC interface protocol for an Mobile-based application. * @beta */ export class MobileRpcProtocol extends RpcProtocol { public socket: WebSocket = (undefined as any); public requests: Map<string, MobileRpcRequest> = new Map(); private _pending: MobileRpcChunks[] = []; private _capacity: number = Number.MAX_SAFE_INTEGER; private _sendInterval: number | undefined = undefined; private _sendIntervalHandler = () => this.trySend(); public readonly requestType = MobileRpcRequest; private _partialRequest: SerializedRpcRequest | undefined = undefined; private _partialFulfillment: RpcRequestFulfillment | undefined = undefined; private _partialData: Uint8Array[] = []; private _port: number = 0; private _transport?: MobilePushTransport; private _ipc: MobileIpcTransport; public static obtainInterop(): MobileRpcGateway { throw new IModelError(BentleyStatus.ERROR, "Not implemented."); } public static async encodeRequest(request: MobileRpcRequest): Promise<MobileRpcChunks> { const serialized = await request.protocol.serialize(request); const data = serialized.parameters.data; serialized.parameters.data = data.map((v) => v.byteLength) as any[]; return [JSON.stringify(serialized), ...data]; } public static encodeResponse(fulfillment: RpcRequestFulfillment): MobileRpcChunks { const data = fulfillment.result.data; fulfillment.result.data = data.map((v) => v.byteLength) as any[]; const raw = fulfillment.rawResult; fulfillment.rawResult = undefined; const encoded = [JSON.stringify(fulfillment), ...data]; fulfillment.rawResult = raw; return encoded; } constructor(configuration: MobileRpcConfiguration, endPoint: RpcEndpoint) { super(configuration); if (endPoint === RpcEndpoint.Frontend) { this.initializeFrontend(); } else if (endPoint === RpcEndpoint.Backend) { this.initializeBackend(); } this._ipc = new MobileIpcTransport(this); IpcWebSocket.transport = this._ipc; } private initializeFrontend() { if (typeof (WebSocket) === "undefined") { throw new IModelError(BentleyStatus.ERROR, "MobileRpcProtocol on frontend require websocket to work"); } if (!MobileRpcConfiguration.args.port) { throw new IModelError(BentleyStatus.ERROR, "MobileRpcProtocol require 'port' parameter"); } this._port = MobileRpcConfiguration.args.port; this.connect(this._port, false); (window as any)._imodeljs_rpc_reconnect = (port: number) => { this.socket.close(); window.location.hash = window.location.hash.replace(`port=${this._port}`, `port=${port}`); this._port = port; this.connect(port, true); }; const transport = new MobilePushTransport(this); this._transport = transport; RpcPushChannel.setup(transport); } private connect(port: number, reset: boolean) { const socket = new WebSocket(`ws://localhost:${port}`); socket.binaryType = "arraybuffer"; this.connectMessageHandler(socket); this.connectOpenHandler(socket, reset); this.connectErrorHandler(socket); this.socket = socket; } private connectMessageHandler(socket: WebSocket) { socket.addEventListener("message", async (event) => { if (this.socket !== socket) { return; } this.handleMessageFromBackend(event.data); }); } private connectOpenHandler(socket: WebSocket, reset: boolean) { socket.addEventListener("open", (_event) => { if (this.socket !== socket) { return; } if (reset) { this.reset(); const requests = new Map(RpcRequest.activeRequests); requests.forEach((req) => { req.cancel(); // eslint-disable-next-line @typescript-eslint/no-floating-promises req.submit(); }); } this.scheduleSend(); }); } private connectErrorHandler(socket: WebSocket) { socket.addEventListener("error", (_event) => { if (this.socket !== socket) { return; } throw new IModelError(BentleyStatus.ERROR, "Socket error."); }); } private reset() { this.requests.clear(); this._pending.length = 0; this._capacity = Number.MAX_SAFE_INTEGER; if (typeof (this._sendInterval) !== "undefined") { window.clearInterval(this._sendInterval); this._sendInterval = undefined; } this._partialRequest = undefined; this._partialFulfillment = undefined; this._partialData.length = 0; } private scheduleSend() { if (!this._pending.length) { return; } this.trySend(); if (this._pending.length && typeof (this._sendInterval) === "undefined") { this._sendInterval = window.setInterval(this._sendIntervalHandler, 0); } } private trySend() { if (this.socket.readyState !== WebSocket.OPEN) { return; } while (this._capacity !== 0 && this._pending.length) { --this._capacity; const next = this._pending.shift()!; for (const chunk of next) { this.socket.send(chunk); } } if (!this._pending.length && typeof (this._sendInterval) !== "undefined") { window.clearInterval(this._sendInterval); this._sendInterval = undefined; } } private handleMessageFromBackend(data: string | ArrayBuffer) { if (typeof (data) === "string") { this.handleStringFromBackend(data); } else { this.handleBinaryFromBackend(data); } } private handleStringFromBackend(data: string) { if (this._partialFulfillment) { throw new IModelError(BentleyStatus.ERROR, "Invalid state (already receiving response)."); } const response = JSON.parse(data) as RpcRequestFulfillment; this._partialFulfillment = response; if (!response.result.data.length) { this.notifyResponse(); } } private handleBinaryFromBackend(data: ArrayBuffer) { const fulfillment = this._partialFulfillment; if (!fulfillment) { throw new IModelError(BentleyStatus.ERROR, "Invalid state (no response received)."); } this._partialData.push(new Uint8Array(data)); if (this._partialData.length === fulfillment.result.data.length) { this.notifyResponse(); } } private notifyResponse() { const response = this._partialFulfillment; if (!response) { throw new IModelError(BentleyStatus.ERROR, "Invalid state (no response exists)."); } ++this._capacity; this.consumePartialData(response.result); this._partialFulfillment = undefined; if (this._transport && this._transport.consume(response)) { return; } if (this._ipc.consumeResponse(response)) { return; } const request = this.requests.get(response.id) as MobileRpcRequest; this.requests.delete(response.id); request.notifyResponse(response); } private consumePartialData(value: RpcSerializedValue) { for (let i = 0, l = value.data.length; i !== l; ++i) { value.data[i] = this._partialData[i]; } this._partialData.length = 0; } private initializeBackend() { const mobilegateway = MobileRpcProtocol.obtainInterop(); if (mobilegateway === undefined || mobilegateway == null) { throw new IModelError(BentleyStatus.ERROR, "MobileRpcProtocol on backend require native bridge to be setup"); } mobilegateway.handler = (payload, connectionId) => this.handleMessageFromFrontend(payload, connectionId); RpcPushConnection.for = (channel, client) => new MobilePushConnection(channel, client, this); RpcPushChannel.enabled = true; } private handleMessageFromFrontend(data: string | ArrayBuffer, connectionId: number) { if (typeof (data) === "string") { this.handleStringFromFrontend(data, connectionId); } else { this.handleBinaryFromFrontend(data, connectionId); } } private handleStringFromFrontend(data: string, connection: number) { if (this._partialRequest) { throw new IModelError(BentleyStatus.ERROR, "Invalid state (already receiving request)."); } const request = JSON.parse(data) as SerializedRpcRequest; this._partialRequest = request; if (!request.parameters.data.length) { this.notifyRequest(connection); // eslint-disable-line @typescript-eslint/no-floating-promises } } private handleBinaryFromFrontend(data: ArrayBuffer, connection: number) { const request = this._partialRequest; if (!request) { throw new IModelError(BentleyStatus.ERROR, "Invalid state (no request received)."); } this._partialData.push(new Uint8Array(data)); if (this._partialData.length === request.parameters.data.length) { this.notifyRequest(connection); // eslint-disable-line @typescript-eslint/no-floating-promises } } private async notifyRequest(connection: number) { const request = this._partialRequest; if (!request) { throw new IModelError(BentleyStatus.ERROR, "Invalid state (no request exists)."); } this.consumePartialData(request.parameters); this._partialRequest = undefined; if (this._ipc.consumeRequest(request)) { return; } MobileEventLoop.addTask(); const fulfillment = await this.fulfill(request); MobileEventLoop.removeTask(); const response = MobileRpcProtocol.encodeResponse(fulfillment); this.sendToFrontend(response, connection); } public sendToBackend(message: MobileRpcChunks): void { this._pending.push(message); this.scheduleSend(); } public sendToFrontend(message: MobileRpcChunks, connection?: number): void { const mobilegateway = MobileRpcProtocol.obtainInterop(); for (const chunk of message) { if (typeof (chunk) === "string") { mobilegateway.sendString(chunk, connection || mobilegateway.connectionId); } else { mobilegateway.sendBinary(chunk, connection || mobilegateway.connectionId); } } } }
the_stack
import { Hardfork } from '@ethereumjs/common' import { BN } from 'ethereumjs-util' import { Peer } from '../net/peer/peer' import { short } from '../util' import { Event } from '../types' import { Synchronizer, SynchronizerOptions } from './sync' import { BlockFetcher } from './fetcher' import { VMExecution } from './execution/vmexecution' import { TxPool } from './txpool' import type { Block } from '@ethereumjs/block' interface HandledObject { hash: Buffer added: number } type PeerId = string /** * Implements an ethereum full sync synchronizer * @memberof module:sync */ export class FullSynchronizer extends Synchronizer { public execution: VMExecution public txPool: TxPool private newBlocksKnownByPeer: Map<PeerId, HandledObject[]> constructor(options: SynchronizerOptions) { super(options) this.newBlocksKnownByPeer = new Map() this.execution = new VMExecution({ config: options.config, stateDB: options.stateDB, chain: options.chain, }) this.txPool = new TxPool({ config: this.config, getPeerCount: () => this.pool.peers.length, }) this.config.events.on(Event.SYNC_EXECUTION_VM_ERROR, async () => { await this.stop() }) void this.chain.update() } /** * Returns synchronizer type */ get type() { return 'full' } /** * Open synchronizer. Must be called before sync() is called */ async open(): Promise<void> { await super.open() await this.chain.open() await this.execution.open() this.txPool.open() await this.pool.open() this.execution.syncing = true const { height: number, td } = this.chain.blocks const hash = this.chain.blocks.latest!.hash() this.startingBlock = number this.config.chainCommon.setHardforkByBlockNumber(number, td) this.config.logger.info( `Latest local block: number=${number} td=${td} hash=${short( hash )} hardfork=${this.config.chainCommon.hardfork()}` ) if (this.config.mine) { // Start the TxPool immediately if mining this.txPool.start() } } /** * Returns true if peer can be used for syncing */ syncable(peer: Peer): boolean { return peer.eth !== undefined } /** * Finds the best peer to sync with. We will synchronize to this peer's * blockchain. Returns null if no valid peer is found */ best(): Peer | undefined { let best const peers = this.pool.peers.filter(this.syncable.bind(this)) if (peers.length < this.config.minPeers && !this.forceSync) return for (const peer of peers) { if (peer.eth?.status) { const td = peer.eth.status.td if ( (!best && td.gte(this.chain.blocks.td)) || (best && best.eth && best.eth.status.td.lt(td)) ) { best = peer } } } return best } /** * Get latest header of peer */ async latest(peer: Peer) { const result = await peer.eth?.getBlockHeaders({ block: peer.eth!.status.bestHash, max: 1, }) return result ? result[1][0] : undefined } /** * Checks if tx pool should be started */ checkTxPoolState() { if (!this.syncTargetHeight || this.txPool.running) { return } // If height gte target, we are close enough to the // head of the chain that the tx pool can be started const target = this.syncTargetHeight.subn(this.txPool.BLOCKS_BEFORE_TARGET_HEIGHT_ACTIVATION) if (this.chain.headers.height.gte(target)) { this.txPool.start() } } /** * Sync all blocks and state from peer starting from current height. * @param peer remote peer to sync with * @return Resolves when sync completed */ async syncWithPeer(peer?: Peer): Promise<boolean> { // eslint-disable-next-line no-async-promise-executor return await new Promise(async (resolve, reject) => { if (!peer) return resolve(false) const latest = await this.latest(peer) if (!latest) return resolve(false) const height = latest.number if (!this.syncTargetHeight) { this.syncTargetHeight = height this.config.logger.info( `New sync target height number=${height} hash=${short(latest.hash())}` ) } const first = this.chain.blocks.height.addn(1) const count = height.sub(first).addn(1) if (count.lten(0)) return resolve(false) this.config.logger.debug(`Syncing with peer: ${peer.toString(true)} height=${height}`) this.fetcher = new BlockFetcher({ config: this.config, pool: this.pool, chain: this.chain, interval: this.interval, first, count, destroyWhenDone: false, }) this.config.events.on(Event.SYNC_FETCHER_FETCHED, async (blocks) => { if (this.config.chainCommon.gteHardfork(Hardfork.Merge)) { // If we are beyond the merge block we should stop the fetcher this.config.logger.info('Merge hardfork reached, stopping block fetcher') if (this.fetcher) { this.fetcher.clear() this.fetcher.destroy() this.fetcher = null } return } if (blocks.length === 0) { this.config.logger.warn('No blocks fetched are applicable for import') return } blocks = blocks as Block[] const first = new BN(blocks[0].header.number) const hash = short(blocks[0].hash()) const baseFeeAdd = this.config.chainCommon.gteHardfork(Hardfork.London) ? `baseFee=${blocks[0].header.baseFeePerGas} ` : '' this.config.logger.info( `Imported blocks count=${ blocks.length } number=${first} hash=${hash} ${baseFeeAdd}hardfork=${this.config.chainCommon.hardfork()} peers=${ this.pool.size }` ) this.txPool.removeNewBlockTxs(blocks) if (this.running || this.config.chainCommon.gteHardfork(Hardfork.Merge)) { await this.execution.run() this.checkTxPoolState() } }) this.config.events.on(Event.SYNC_SYNCHRONIZED, () => { resolve(true) }) try { if (this.fetcher) { await this.fetcher.fetch() } } catch (error: any) { reject(error) } }) } /** * Add newly broadcasted blocks to peer record * @param blockHash hash of block received in NEW_BLOCK message * @param peer * @returns true if block has already been sent to peer */ private addToKnownByPeer(blockHash: Buffer, peer: Peer): boolean { const knownBlocks = this.newBlocksKnownByPeer.get(peer.id) ?? [] if (knownBlocks.find((knownBlock) => knownBlock.hash.equals(blockHash))) { return true } knownBlocks.push({ hash: blockHash, added: Date.now() }) this.newBlocksKnownByPeer.set(peer.id, knownBlocks) return false } /** * Send (broadcast) a new block to connected peers. * @param Block * @param peers */ async sendNewBlock(block: Block, peers: Peer[]) { for (const peer of peers) { const alreadyKnownByPeer = this.addToKnownByPeer(block.hash(), peer) if (!alreadyKnownByPeer) { peer.eth?.send('NewBlock', [block, this.chain.blocks.td]) } } } /** * Handles `NEW_BLOCK` announcement from a peer and inserts into local chain if child of chain tip * @param blockData `NEW_BLOCK` received from peer * @param peer `Peer` that sent `NEW_BLOCK` announcement */ async handleNewBlock(block: Block, peer?: Peer) { if (peer) { // Don't send NEW_BLOCK announcement to peer that sent original new block message this.addToKnownByPeer(block.hash(), peer) } if (block.header.number.gt(this.chain.headers.height.addn(1))) { // If the block number exceeds one past our height we cannot validate it return } try { await block.header.validate(this.chain.blockchain) } catch (err) { this.config.logger.debug( `Error processing new block from peer ${ peer ? `id=${peer.id.slice(0, 8)}` : '(no peer)' } hash=${short(block.hash())}` ) this.config.logger.debug(err) return } // Send NEW_BLOCK to square root of total number of peers in pool // https://github.com/ethereum/devp2p/blob/master/caps/eth.md#block-propagation const numPeersToShareWith = Math.floor(Math.sqrt(this.pool.peers.length)) await this.sendNewBlock(block, this.pool.peers.slice(0, numPeersToShareWith)) if (this.chain.blocks.latest?.hash().equals(block.header.parentHash)) { // If new block is child of current chain tip, insert new block into chain await this.chain.putBlocks([block]) // Check if new sync target height can be set const blockNumber = block.header.number if (!this.syncTargetHeight || blockNumber.gt(this.syncTargetHeight)) { this.syncTargetHeight = blockNumber } } else { // Call handleNewBlockHashes to retrieve all blocks between chain tip and new block this.handleNewBlockHashes([[block.hash(), block.header.number]]) } for (const peer of this.pool.peers.slice(numPeersToShareWith)) { // Send `NEW_BLOCK_HASHES` message for received block to all other peers const alreadyKnownByPeer = this.addToKnownByPeer(block.hash(), peer) if (!alreadyKnownByPeer) { peer.eth?.send('NewBlockHashes', [[block.hash(), block.header.number]]) } } } /** * Chain was updated, new block hashes received * @param data new block hash announcements */ handleNewBlockHashes(data: [Buffer, BN][]) { if (!data.length) { return } if (!this.fetcher) { return } let min = new BN(-1) let newSyncHeight const blockNumberList: BN[] = [] data.forEach((value) => { const blockNumber = value[1] blockNumberList.push(blockNumber) if (min.eqn(-1) || blockNumber.lt(min)) { min = blockNumber } // Check if new sync target height can be set if (!this.syncTargetHeight || blockNumber.gt(this.syncTargetHeight)) { newSyncHeight = blockNumber } }) if (!newSyncHeight) { return } this.syncTargetHeight = newSyncHeight const [hash, height] = data[data.length - 1] this.config.logger.info(`New sync target height number=${height} hash=${short(hash)}`) this.fetcher.enqueueByNumberList(blockNumberList, min) } /** * Stop synchronization. Returns a promise that resolves once its stopped. */ async stop(): Promise<boolean> { this.execution.syncing = false await this.execution.stop() this.txPool.stop() if (!this.running) { return false } if (this.fetcher) { this.fetcher.destroy() this.fetcher = null } await super.stop() return true } /** * Close synchronizer. */ async close() { if (this.opened) { this.txPool.close() } await super.close() } }
the_stack
import Obniz from '../../../obniz'; import bleRemoteCharacteristic from '../../../obniz/libs/embeds/bleHci/bleRemoteCharacteristic'; import BleRemotePeripheral from '../../../obniz/libs/embeds/bleHci/bleRemotePeripheral'; import JsonBinaryConverter from '../../../obniz/libs/wscommand/jsonBinaryConverter'; import ObnizPartsBleInterface from '../../../obniz/ObnizPartsBleInterface'; import ObnizPartsInterface, { ObnizPartsInfo, } from '../../../obniz/ObnizPartsInterface'; export interface OMRON_2JCIEOptions {} export interface OMRON_2JCIE_Data { row_number: number; temperature: number; relative_humidity: number; light: number; uv_index: number; barometric_pressure: number; sound_noise: number; discomfort_index: number; heatstroke_risk_factor: number; battery_voltage: number; } export interface OMRON_2JCIE_USBSenData { seqence_number: number; temperature: number; relative_humidity: number; light: number; barometric_pressure: number; sound_noise: number; etvoc: number; eco2: number; } export interface OMRON_2JCIE_USBCalData { sequence_number: number; disconfort_index: number; heatstroke_risk_factor: number; vibration_information: number; si_value: number; pga: number; seismic_intensity: number; acceleration_x: number; acceleration_y: number; acceleration_z: number; } export interface OMRON_2JCIE_AdvData { temperature: number; relative_humidity: number; light: number; uv_index: number; barometric_pressure: number; sound_noise: number; acceleration_x: number; acceleration_y: number; acceleration_z: number; battery: number; } export interface OMRON_2JCIE_AdvSensorData { temperature: number; relative_humidity: number; light: number; barometric_pressure: number; sound_noise: number; etvoc: number; eco2: number; } export default class OMRON_2JCIE implements ObnizPartsBleInterface { public static info(): ObnizPartsInfo { return { name: '2JCIE', }; } public static isDevice(peripheral: BleRemotePeripheral) { return ( (peripheral.localName && peripheral.localName.indexOf('Env') >= 0) || (peripheral.localName && peripheral.localName.indexOf('IM') >= 0) || (peripheral.localName && peripheral.localName.indexOf('Rbt') >= 0) ); } /** * Get a datas from advertisement mode of OMRON 2JCIE */ public static getData( peripheral: BleRemotePeripheral ): OMRON_2JCIE_AdvData | OMRON_2JCIE_AdvSensorData | null { const adv_data = peripheral.adv_data; if (peripheral.localName && peripheral.localName.indexOf('IM') >= 0) { return { temperature: ObnizPartsBleInterface.signed16FromBinary(adv_data[9], adv_data[8]) * 0.01, relative_humidity: ObnizPartsBleInterface.signed16FromBinary( adv_data[11], adv_data[10] ) * 0.01, light: ObnizPartsBleInterface.signed16FromBinary( adv_data[13], adv_data[12] ) * 1, uv_index: ObnizPartsBleInterface.signed16FromBinary( adv_data[15], adv_data[14] ) * 0.01, barometric_pressure: ObnizPartsBleInterface.signed16FromBinary( adv_data[17], adv_data[16] ) * 0.1, sound_noise: ObnizPartsBleInterface.signed16FromBinary( adv_data[19], adv_data[18] ) * 0.01, acceleration_x: ObnizPartsBleInterface.signed16FromBinary( adv_data[21], adv_data[20] ), acceleration_y: ObnizPartsBleInterface.signed16FromBinary( adv_data[23], adv_data[22] ), acceleration_z: ObnizPartsBleInterface.signed16FromBinary( adv_data[25], adv_data[24] ), battery: (adv_data[26] + 100) / 100, }; } else if ( peripheral.localName && peripheral.localName.indexOf('Rbt') >= 0 && adv_data[6] === 0x02 && adv_data[6] === 0x02 && adv_data[7] === 0x01 ) { return { temperature: ObnizPartsBleInterface.signed16FromBinary(adv_data[10], adv_data[9]) * 0.01, relative_humidity: ObnizPartsBleInterface.signed16FromBinary( adv_data[12], adv_data[11] ) * 0.01, light: ObnizPartsBleInterface.signed16FromBinary( adv_data[14], adv_data[13] ) * 1, barometric_pressure: ObnizPartsBleInterface.signed32FromBinary( adv_data[18], adv_data[17], adv_data[16], adv_data[15] ) * 0.001, sound_noise: ObnizPartsBleInterface.signed16FromBinary( adv_data[20], adv_data[19] ) * 0.01, etvoc: ObnizPartsBleInterface.signed16FromBinary( adv_data[22], adv_data[21] ), eco2: ObnizPartsBleInterface.signed16FromBinary( adv_data[24], adv_data[23] ), }; } return null; } public _peripheral: BleRemotePeripheral | null = null; public obniz!: Obniz; public params: any; public ondisconnect?: (reason: any) => void; private vibrationState: { [index: number]: string } = { 0x00: 'NONE', 0x01: 'druing vibration (Earthquake judgment in progress)', 0x02: 'during earthquake', }; constructor(peripheral: BleRemotePeripheral | null) { if (peripheral && !OMRON_2JCIE.isDevice(peripheral)) { throw new Error('peripheral is not OMRON_2JCIE'); } this._peripheral = peripheral; } public wired(obniz: Obniz) { this.obniz = obniz; } public async findWait(): Promise<any> { const target: any = { localName: ['Env', 'Rbt'], }; await this.obniz.ble!.initWait(); this._peripheral = await this.obniz.ble!.scan.startOneWait(target); return this._peripheral; } public omron_uuid(uuid: string, type: string): string | any { if (type === 'BAG') { return `0C4C${uuid}-7700-46F4-AA96D5E974E32A54`; } else if (type === 'USB') { return `AB70${uuid}-0A3A-11E8-BA89-0ED5F89F718B`; } else { return undefined; } } public async connectWait() { if (!this._peripheral) { await this.findWait(); } if (!this._peripheral) { throw new Error('2JCIE not found'); } if (!this._peripheral.connected) { this._peripheral.ondisconnect = (reason: any) => { if (typeof this.ondisconnect === 'function') { this.ondisconnect(reason); } }; await this._peripheral.connectWait(); } } public async disconnectWait() { if (this._peripheral && this._peripheral.connected) { await this._peripheral.disconnectWait(); } } public signedNumberFromBinary(data: number[]) { // little adian let val: number = data[data.length - 1] & 0x7f; for (let i = data.length - 2; i >= 0; i--) { val = val * 256 + data[i]; } if ((data[data.length - 1] & 0x80) !== 0) { val = val - Math.pow(2, data.length * 8 - 1); } return val; } public unsignedNumberFromBinary(data: number[]) { // little adian let val: number = data[data.length - 1]; for (let i = data.length - 2; i >= 0; i--) { val = val * 256 + data[i]; } return val; } public async getLatestDataBAGWait(): Promise<OMRON_2JCIE_Data> { return this.getLatestDataWait(); } /** * @deprecated */ public getLatestData(): Promise<OMRON_2JCIE_Data> { return this.getLatestDataWait(); } public async getLatestDataWait(): Promise<OMRON_2JCIE_Data> { await this.connectWait(); const c = this._peripheral!.getService( this.omron_uuid('3000', 'BAG') )!.getCharacteristic(this.omron_uuid('3001', 'BAG'))!; const data: number[] = await c.readWait(); const json: any = { row_number: data[0], temperature: this.signedNumberFromBinary(data.slice(1, 3)) * 0.01, relative_humidity: this.signedNumberFromBinary(data.slice(3, 5)) * 0.01, light: this.signedNumberFromBinary(data.slice(5, 7)) * 1, uv_index: this.signedNumberFromBinary(data.slice(7, 9)) * 0.01, barometric_pressure: this.signedNumberFromBinary(data.slice(9, 11)) * 0.1, sound_noise: this.signedNumberFromBinary(data.slice(11, 13)) * 0.01, discomfort_index: this.signedNumberFromBinary(data.slice(13, 15)) * 0.01, heatstroke_risk_factor: this.signedNumberFromBinary(data.slice(15, 17)) * 0.01, battery_voltage: this.unsignedNumberFromBinary(data.slice(17, 19)) * 0.001, }; return json; } public getLatestSensorDataUSB(): Promise<OMRON_2JCIE_USBSenData> { return this.getLatestSensorDataUSBWait(); } public async getLatestSensorDataUSBWait(): Promise<OMRON_2JCIE_USBSenData> { await this.connectWait(); const c = this._peripheral!.getService( this.omron_uuid('5010', 'USB') )!.getCharacteristic(this.omron_uuid('5012', 'USB'))!; const data: number[] = await c.readWait(); const json: any = { seqence_number: data[0], temperature: this.signedNumberFromBinary(data.slice(1, 3)) * 0.01, relative_humidity: this.signedNumberFromBinary(data.slice(3, 5)) * 0.01, light: this.signedNumberFromBinary(data.slice(5, 7)) * 1, barometric_pressure: this.signedNumberFromBinary(data.slice(7, 11)) * 0.001, sound_noise: this.signedNumberFromBinary(data.slice(11, 13)) * 0.01, etvoc: this.signedNumberFromBinary(data.slice(13, 15)) * 1, eco2: this.signedNumberFromBinary(data.slice(15, 17)) * 1, }; return json; } /** * @deprecated */ public getLatestCalculationDataUSB(): Promise<OMRON_2JCIE_USBCalData> { return this.getLatestCalculationDataUSBWait(); } public async getLatestCalculationDataUSBWait(): Promise<OMRON_2JCIE_USBCalData> { await this.connectWait(); const c = this._peripheral!.getService( this.omron_uuid('5010', 'USB') )!.getCharacteristic(this.omron_uuid('5013', 'USB'))!; const data: number[] = await c.readWait(); const json: any = { sequence_number: data[0], disconfort_index: this.signedNumberFromBinary(data.slice(1, 3)) * 0.01, heatstroke_risk_factor: this.signedNumberFromBinary(data.slice(3, 5)) * 0.01, vibration_information: this.vibrationState[data[5]], si_value: this.unsignedNumberFromBinary(data.slice(6, 8)) * 0.1, pga: this.unsignedNumberFromBinary(data.slice(8, 10)) * 0.1, seismic_intensity: this.unsignedNumberFromBinary(data.slice(10, 12)) * 0.001, acceleration_x: this.signedNumberFromBinary(data.slice(12, 14)) * 1, acceleration_y: this.signedNumberFromBinary(data.slice(14, 16)) * 1, acceleration_z: this.signedNumberFromBinary(data.slice(16, 18)) * 1, }; return json; } }
the_stack
import * as arrayUtil from "dojo/_base/array"; import * as declare from "dojo/_base/declare"; import * as Deferred from "dojo/_base/Deferred"; import * as lang from "dojo/_base/lang"; import * as dom from "dojo/dom"; import * as html from "dojo/html"; import * as on from "dojo/on"; import * as topic from "dojo/topic"; import * as CheckedMenuItem from "dijit/CheckedMenuItem"; import * as Menu from "dijit/Menu"; import * as MenuItem from "dijit/MenuItem"; import * as MenuSeparator from "dijit/MenuSeparator"; import * as registry from "dijit/registry"; import * as entities from "dojox/html/entities"; // @ts-ignore import * as tree from "../dgrid/tree"; // @ts-ignore import * as _Widget from "hpcc/_Widget"; import * as ESPUtil from "./ESPUtil"; import * as ESPWorkunit from "./ESPWorkunit"; import nlsHPCC from "./nlsHPCC"; import * as Utility from "./Utility"; import * as WsWorkunits from "./WsWorkunits"; // @ts-ignore import * as template from "dojo/text!hpcc/templates/GraphTreeWidget.html"; import "dijit/Dialog"; import "dijit/form/Button"; import "dijit/form/DropDownButton"; import "dijit/form/NumberSpinner"; import "dijit/form/Select"; import "dijit/form/SimpleTextarea"; import "dijit/form/TextBox"; import "dijit/form/ToggleButton"; import "dijit/layout/BorderContainer"; import "dijit/layout/ContentPane"; import "dijit/layout/StackContainer"; import "dijit/layout/StackController"; import "dijit/layout/TabContainer"; import "dijit/Toolbar"; import "dijit/ToolbarSeparator"; import "hpcc/JSGraphWidget"; import "hpcc/TimingTreeMapWidget"; import { declareDecorator } from "./DeclareDecorator"; type _Widget = any; export interface GraphTreeWidget extends _Widget { } @declareDecorator("GraphTreeWidget", _Widget) export class GraphTreeWidget { templateString = template; baseClass = "GraphTreeWidget"; i18n = nlsHPCC; graphType = "JSGraphWidget"; graphName = ""; wu = null; global = null; main = null; subgraphsGrid = null; verticesGrid = null; edgesGrid = null; xgmmlDialog = null; infoDialog = null; findText = ""; found = []; foundIndex = 0; constructor() { } buildRendering(args) { this.inherited(arguments); } postCreate(args) { this.inherited(arguments); this._initGraphControls(); this._initTimings(); this._initActivitiesMap(); this._initDialogs(); const context = this; topic.subscribe(this.id + "OverviewTabContainer-selectChild", function (topic) { context.refreshActionState(); }); } startup(args) { this.inherited(arguments); this._initTree(); this._initSubgraphs(); this._initVertices(); this._initEdges(); let splitter = this.widget.BorderContainer.getSplitter("left"); this.main.watchSplitter(splitter); splitter = this.widget.SideBorderContainer.getSplitter("bottom"); this.main.watchSplitter(splitter); this.main.watchSelect(registry.byId(this.id + "AdvancedMenu")); this.refreshActionState(); } resize(args) { this.inherited(arguments); this.widget.BorderContainer.resize(); } layout(args) { this.inherited(arguments); } destroy(args) { this.xgmmlDialog.destroyRecursive(); this.infoDialog.destroyRecursive(); this.inherited(arguments); } // Implementation --- _initGraphControls() { const context = this; this.global = registry.byId(this.id + "GlobalGraphWidget"); this.main = registry.byId(this.id + "MainGraphWidget"); this.main.onSelectionChanged = function (items) { context.syncSelectionFrom(context.main); }; this.main.onDoubleClick = function (globalID, keyState) { if (keyState && context.main.KeyState_Shift) { context.main._onSyncSelection(); } else { context.main.centerOn(globalID); } context.syncSelectionFrom(context.main); }; } _initTimings() { const context = this; this.widget.TimingsTreeMap.onClick = function (value) { context.syncSelectionFrom(context.widget.TimingsTreeMap); }; } _initActivitiesMap() { const context = this; this.widget.ActivitiesTreeMap.onClick = function (value) { context.syncSelectionFrom(context.widget.ActivitiesTreeMap); }; } _initDialogs() { const context = this; this.infoDialog = registry.byId(this.id + "InfoDialog"); on(dom.byId(this.id + "InfoDialogCancel"), "click", function (event) { context.infoDialog.hide(); }); this.xgmmlDialog = registry.byId(this.id + "XGMMLDialog"); this.xgmmlTextArea = registry.byId(this.id + "XGMMLTextArea"); on(dom.byId(this.id + "XGMMLDialogApply"), "click", function (event) { context.xgmmlDialog.hide(); if (context.xgmmlDialog.get("hpccMode") === "XGMML") { const xgmml = context.xgmmlTextArea.get("value"); context.loadGraphFromXGMML(xgmml); } else if (context.xgmmlDialog.get("hpccMode") === "DOT") { const dot = context.xgmmlTextArea.get("value"); context.loadGraphFromDOT(dot); } else if (context.xgmmlDialog.get("hpccMode") === "DOTATTRS") { const dotAttrs = context.xgmmlTextArea.get("value"); context.global.setDotMetaAttributes(dotAttrs); context.main.setDotMetaAttributes(dotAttrs); context._onMainSync(); } }); on(dom.byId(this.id + "XGMMLDialogCancel"), "click", function (event) { context.xgmmlDialog.hide(); }); } _initItemGrid(grid) { const context = this; grid.on("dgrid-select, dgrid-deselect", function (event) { context.syncSelectionFrom(grid); }); grid.on(".dgrid-row:dblclick", function (evt) { const item = grid.row(evt).data; if (item._globalID) { const mainItem = context.main.getItem(item._globalID); context.main.centerOnItem(mainItem, true); } }); } _initTree() { this.treeStore = this.global.createTreeStore(); this.treeGrid = new declare([ESPUtil.Grid(false, true)])({ treeDepth: this.main.getDepth(), store: this.treeStore }, this.id + "TreeGrid"); this._initItemGrid(this.treeGrid); this.initContextMenu(); } initContextMenu() { const context = this; const pMenu = new Menu({ targetNodeIds: [this.id + "TreeGrid"] }); pMenu.addChild(new MenuItem({ label: this.i18n.ExpandAll, onClick(evt) { context.treeGrid.set("treeDepth", 9999); context.treeGrid.refresh(); } })); pMenu.addChild(new MenuItem({ label: this.i18n.CollapseAll, onClick(evt) { context.treeGrid.set("treeDepth", 1); context.treeGrid.refresh(); } })); pMenu.addChild(new MenuSeparator()); pMenu.addChild(new CheckedMenuItem({ label: this.i18n.Activities, checked: false, onClick(evt) { if (this.checked) { context.treeGrid.set("query", { id: "0" }); } else { context.treeGrid.set("query", { id: "0", __hpcc_notActivity: true }); } } })); } _initSubgraphs() { this.subgraphsStore = this.global.createStore(); this.subgraphsGrid = new declare([ESPUtil.Grid(false, true)])({ store: this.subgraphsStore }, this.id + "SubgraphsGrid"); this._initItemGrid(this.subgraphsGrid); } _initVertices() { this.verticesStore = this.global.createStore(); this.verticesGrid = new declare([ESPUtil.Grid(false, true)])({ store: this.verticesStore }, this.id + "VerticesGrid"); this._initItemGrid(this.verticesGrid); } _initEdges() { this.edgesStore = this.global.createStore(); this.edgesGrid = new declare([ESPUtil.Grid(false, true)])({ store: this.edgesStore }, this.id + "EdgesGrid"); this._initItemGrid(this.edgesGrid); } _onRefresh() { this.refreshData(); } _onTreeRefresh() { this.treeGrid.set("treeDepth", this.main.getDepth()); this.treeGrid.refresh(); } _onChangeActivityMetric() { const metric = this.widget.ActivityMetric.get("value"); this.widget.ActivitiesTreeMap.setActivityMetric(metric); } _doFind(prev) { if (this.findText !== this.widget.FindField.value) { this.findText = this.widget.FindField.value; this.found = this.global.findAsGlobalID(this.findText); this.syncSelectionFrom(this.found); this.foundIndex = -1; } this.foundIndex += prev ? -1 : +1; if (this.foundIndex < 0) { this.foundIndex = this.found.length - 1; } else if (this.foundIndex >= this.found.length) { this.foundIndex = 0; } if (this.found.length) { this.main.centerOnGlobalID(this.found[this.foundIndex], true); } this.refreshActionState(); } _onFind(prev) { this.findText = ""; this._doFind(false); } _onFindNext() { this._doFind(false); } _onFindPrevious() { this._doFind(true); } _onAbout() { html.set(dom.byId(this.id + "InfoDialogContent"), "<div style='width: 320px; height: 120px; text-align: center;'><p>" + this.i18n.Version + ": " + this.main.getVersion() + "</p><p>" + this.main.getResourceLinks() + "</p>"); this.infoDialog.set("title", this.i18n.AboutHPCCSystemsGraphControl); this.infoDialog.show(); } _onGetSVG() { html.set(dom.byId(this.id + "InfoDialogContent"), "<textarea rows='25' cols='80'>" + entities.encode(this.main.getSVG()) + "</textarea>"); this.infoDialog.set("title", this.i18n.SVGSource); this.infoDialog.show(); } _onRenderSVG() { const context = this; this.main.localLayout(function (svg) { html.set(dom.byId(context.id + "InfoDialogContent"), "<div style='border: 1px inset grey; width: 640px; height: 480px; overflow : auto; '>" + svg + "</div>"); context.infoDialog.set("title", this.i18n.RenderedSVG); context.infoDialog.show(); }); } _onGetXGMML() { this.xgmmlDialog.set("title", this.i18n.XGMML); this.xgmmlDialog.set("hpccMode", "XGMML"); this.xgmmlTextArea.set("value", this.main.getXGMML()); this.xgmmlDialog.show(); } _onEditDOT() { this.xgmmlDialog.set("title", this.i18n.DOT); this.xgmmlDialog.set("hpccMode", "DOT"); this.xgmmlTextArea.set("value", this.main.getDOT()); this.xgmmlDialog.show(); } _onGetGraphAttributes() { this.xgmmlDialog.set("title", this.i18n.DOTAttributes); this.xgmmlDialog.set("hpccMode", "DOTATTRS"); this.xgmmlTextArea.set("value", this.global.getDotMetaAttributes()); this.xgmmlDialog.show(); } isWorkunit() { return lang.exists("params.Wuid", this); } isQuery() { return lang.exists("params.QueryId", this); } init(params) { if (this.inherited(arguments)) return; if (this.global._plugin) { this.doInit(params); } else { this.global.on("ready", lang.hitch(this, function (evt) { this.doInit(params); })); } } refresh(params) { if (params.SubGraphId) { this.syncSelectionFrom([params.SubGraphId]); } } doInit(params) { if (this.global.version.major < 5) { dom.byId(this.id + "Warning").innerHTML = this.i18n.WarnOldGraphControl + " (" + this.global.version.version + ")"; } if (params.SafeMode && params.SafeMode !== "false") { this.main.depth.set("value", 1); let dotAttrs = this.global.getDotMetaAttributes(); dotAttrs = dotAttrs.replace("\n//graph[splines=\"line\"];", "\ngraph[splines=\"line\"];"); this.global.setDotMetaAttributes(dotAttrs); } else { let dotAttrs = this.global.getDotMetaAttributes(); dotAttrs = dotAttrs.replace("\ngraph[splines=\"line\"];", "\n//graph[splines=\"line\"];"); this.global.setDotMetaAttributes(dotAttrs); } this.graphName = params.GraphName; this.subGraphId = params.SubGraphId; this.widget.TimingsTreeMap.init(lang.mixin({ query: { graphsOnly: true, graphName: this.graphName, subGraphId: "*" }, hideHelp: true }, params)); this.widget.ActivitiesTreeMap.init(lang.mixin({ query: { activitiesOnly: true, graphName: this.graphName, subGraphId: "*" }, hideHelp: true }, params)); if (this.isWorkunit()) { this.wu = ESPWorkunit.Get(params.Wuid); let firstLoad = true; const context = this; this.wu.monitor(function () { context.wu.getInfo({ onGetApplicationValues(applicationValues) { }, onGetGraphs(graphs) { if (firstLoad === true) { firstLoad = false; context.loadGraphFromWu(context.wu, context.graphName, context.subGraphId); } else { context.refreshGraphFromWU(context.wu, context.graphName, context.subGraphId); } }, onGetTimers(timers) { context.graphTimers = context.wu.getGraphTimers(context.GraphName); } }); }); } else if (this.isQuery()) { this.targetQuery = params.Target; this.queryId = params.QueryId; this.loadGraphFromQuery(this.targetQuery, this.queryId, this.graphName); } } refreshData() { if (this.isWorkunit()) { this.loadGraphFromWu(this.wu, this.graphName, this.subGraphId, true); } else if (this.isQuery()) { this.loadGraphFromQuery(this.targetQuery, this.queryId, this.graphName); } } loadGraphFromXGMML(xgmml) { if (this.global.loadXGMML(xgmml, false, this.graphTimers, true)) { this.global.setMessage("..."); // Just in case it decides to render --- let mainRoot = [0]; const complexityInfo = this.global.getComplexityInfo(); if (this.params.SubGraphId) { mainRoot = [this.params.SubGraphId]; } else if (complexityInfo.isComplex()) { if (confirm(lang.replace(this.i18n.ComplexityWarning, complexityInfo) + "\n" + this.i18n.ManualTreeSelection)) { mainRoot = []; } } this.loadTree(); this.loadSubgraphs(); this.loadVertices(); this.loadEdges(); this.syncSelectionFrom(mainRoot); } } mergeGraphFromXGMML(xgmml) { if (this.global.loadXGMML(xgmml, true, this.graphTimers, true)) { this.global.setMessage("..."); // Just in case it decides to render --- this.refreshMainXGMML(); this.loadSubgraphs(); this.loadVertices(); this.loadEdges(); } } loadGraphFromDOT(dot) { this.global.loadDOT(dot); this.global.setMessage("..."); // Just in case it decides to render --- this.setMainRootItems([]); this.loadSubgraphs(); this.loadVertices(); this.loadEdges(); } loadGraphFromWu(wu, graphName, subGraphId, refresh: boolean = false) { const deferred = new Deferred(); this.main.setMessage(this.i18n.FetchingData); const context = this; wu.fetchGraphXgmmlByName(graphName, subGraphId, function (xgmml, svg) { context.main.setMessage(""); context.loadGraphFromXGMML(xgmml); deferred.resolve(); }, refresh); return deferred.promise; } refreshGraphFromWU(wu, graphName, subGraphId) { const context = this; wu.fetchGraphXgmmlByName(graphName, subGraphId, function (xgmml) { context.mergeGraphFromXGMML(xgmml); }, true); } loadGraphFromQuery(targetQuery, queryId, graphName) { this.main.setMessage(this.i18n.FetchingData); const context = this; WsWorkunits.WUQueryGetGraph({ request: { Target: targetQuery, QueryId: queryId, GraphName: graphName } }).then(function (response) { context.main.setMessage(""); if (lang.exists("WUQueryGetGraphResponse.Graphs.ECLGraphEx", response)) { if (response.WUQueryGetGraphResponse.Graphs.ECLGraphEx.length > 0) { context.loadGraphFromXGMML(response.WUQueryGetGraphResponse.Graphs.ECLGraphEx[0].Graph); } } }); } refreshGraphFromQuery(targetQuery, queryId, graphName) { const context = this; WsWorkunits.WUQueryGetGraph({ request: { Target: targetQuery, QueryId: queryId, GraphName: graphName } }).then(function (response) { if (lang.exists("WUQueryGetGraphResponse.Graphs.ECLGraphEx", response)) { if (response.WUQueryGetGraphResponse.Graphs.ECLGraphEx.length > 0) { context.mergeGraphFromXGMML(response.WUQueryGetGraphResponse.Graphs.ECLGraphEx[0].Graph); } } }); } loadTree() { const treeData = this.global.getTreeWithProperties(); this.treeStore.setTree(treeData); const context = this; const columns = [ tree({ field: "id", label: this.i18n.ID, width: 150, collapseOnRefresh: true, shouldExpand(row, level, previouslyExpanded) { if (previouslyExpanded !== undefined) { return previouslyExpanded; } else if (level < context.treeGrid.get("treeDepth")) { return true; } return false; }, formatter(_id, row) { let img = Utility.getImageURL("file.png"); let label = _id + " - "; switch (row._globalType) { case "Graph": img = Utility.getImageURL("server.png"); label = context.params.GraphName + " (" + row._children.length + ")"; break; case "Cluster": img = Utility.getImageURL("folder.png"); label += context.i18n.Subgraph + " (" + row._children.length + ")"; break; case "Vertex": label += row.label; break; } return "<img src='" + img + "'/>&nbsp;" + label; } }) ]; if (this.isWorkunit()) { this.treeStore.appendColumns(columns, ["name"], ["DescendantCount", "ecl", "definition", "SubgraphCount", "ActivityCount", "ChildCount", "Depth"]); } else if (this.isQuery()) { this.treeStore.appendColumns(columns, ["localTime", "totalTime", "label", "ecl"], ["DescendantCount", "definition", "SubgraphCount", "ActivityCount", "ChildCount", "Depth"]); } this.treeGrid.set("query", { id: "0", __hpcc_notActivity: true }); this.treeGrid.set("columns", columns); this.treeGrid.refresh(); } loadSubgraphs() { const subgraphs = this.global.getSubgraphsWithProperties(); this.subgraphsStore.setData(subgraphs); const columns = [ { label: this.i18n.ID, field: "id", width: 54, formatter(_id, row) { const img = Utility.getImageURL("folder.png"); return "<img src='" + img + "'/>&nbsp;" + _id; } } ]; this.subgraphsStore.appendColumns(columns, [this.i18n.TimeSeconds, "DescendantCount", "SubgraphCount", "ActivityCount"], ["ChildCount", "Depth"]); this.subgraphsGrid.set("columns", columns); this.subgraphsGrid.refresh(); } loadVertices() { const vertices = this.global.getVerticesWithProperties(); this.verticesStore.setData(vertices); const columns = [ { label: this.i18n.ID, field: "id", width: 54, formatter(_id, row) { const img = Utility.getImageURL("file.png"); return "<img src='" + img + "'/>&nbsp;" + _id; } }, { label: this.i18n.Label, field: "label", width: 150 } ]; this.verticesStore.appendColumns(columns, ["name"], ["ecl", "definition"], null, true); this.verticesGrid.set("columns", columns); this.verticesGrid.refresh(); this.widget.ActivityMetric.set("options", arrayUtil.map(arrayUtil.filter(columns, function (col, idx) { return col.label.indexOf("Time") === 0 || col.label.indexOf("Size") === 0 || col.label.indexOf("Skew") === 0 || col.label.indexOf("Num") === 0; }), function (col, idx) { return { label: col.label, value: col.label, selected: col.label === "TimeMaxLocalExecute" }; }).sort(function (l, r) { if (l.label < r.label) { return -1; } else if (l.label > r.label) { return 1; } return 0; })); this.widget.ActivitiesTreeMap.setActivities(vertices, true); this.widget.ActivityMetric.set("value", "TimeMaxLocalExecute"); } loadEdges() { const edges = this.global.getEdgesWithProperties(); this.edgesStore.setData(edges); const columns = [ { label: this.i18n.ID, field: "id", width: 50 } ]; this.edgesStore.appendColumns(columns, ["label", "count"], ["source", "target"]); this.edgesGrid.set("columns", columns); this.edgesGrid.refresh(); } inSyncSelectionFrom = false; syncSelectionFrom(sourceControl) { if (!this.inSyncSelectionFrom) { this._syncSelectionFrom(sourceControl); } } // _syncSelectionFrom: Utility.debounce(function (sourceControlOrGlobalIDs) { _syncSelectionFrom(sourceControlOrGlobalIDs) { this.inSyncSelectionFrom = true; const sourceControl = sourceControlOrGlobalIDs instanceof Array ? null : sourceControlOrGlobalIDs; let selectedGlobalIDs = sourceControlOrGlobalIDs instanceof Array ? sourceControlOrGlobalIDs : []; if (sourceControl) { // Get Selected Items --- if (sourceControl === this.widget.TimingsTreeMap) { const items = sourceControl.getSelected(); for (let i = 0; i < items.length; ++i) { if (items[i].SubGraphId) { selectedGlobalIDs.push(items[i].SubGraphId); } } } else if (sourceControl === this.widget.ActivitiesTreeMap) { const items = sourceControl.getSelected(); for (let i = 0; i < items.length; ++i) { if (items[i].ActivityID) { selectedGlobalIDs.push(items[i].ActivityID); } } } else if (sourceControl === this.verticesGrid || sourceControl === this.edgesGrid || sourceControl === this.subgraphsGrid || sourceControl === this.treeGrid) { const items = sourceControl.getSelected(); for (let i = 0; i < items.length; ++i) { if (lang.exists("_globalID", items[i])) { selectedGlobalIDs.push(items[i]._globalID); } } } else if (sourceControl === this.found) { selectedGlobalIDs = this.found; } else { selectedGlobalIDs = sourceControl.getSelectionAsGlobalID(); } } // Set Selected Items --- if (sourceControl !== this.treeGrid) { this.treeGrid.setSelection(selectedGlobalIDs); } if (sourceControl !== this.widget.TimingsTreeMap) { this.widget.TimingsTreeMap.setSelectedAsGlobalID(selectedGlobalIDs); } if (sourceControl !== this.widget.ActivitiesTreeMap) { this.widget.ActivitiesTreeMap.setSelectedAsGlobalID(selectedGlobalIDs); } if (sourceControl !== this.subgraphsGrid && this.subgraphsGrid.store) { this.subgraphsGrid.setSelection(selectedGlobalIDs); } if (sourceControl !== this.verticesGrid && this.verticesGrid.store) { this.verticesGrid.setSelection(selectedGlobalIDs); } if (sourceControl !== this.edgesGrid && this.edgesGrid.store) { this.edgesGrid.setSelection(selectedGlobalIDs); } // Refresh Graph Controls --- if (sourceControl !== this.main) { this.setMainRootItems(selectedGlobalIDs); } const propertiesDom = dom.byId(this.id + "Properties"); propertiesDom.innerHTML = ""; for (let i = 0; i < selectedGlobalIDs.length; ++i) { this.global.displayProperties(this.wu, selectedGlobalIDs[i], propertiesDom); } const context = this; if (selectedGlobalIDs.length) { const edges = arrayUtil.filter(selectedGlobalIDs, function (id) { return id && id.indexOf && id.indexOf("_") >= 0; }); if (edges.length === 1) { WsWorkunits.WUCDebug(context.params.Wuid, "<debug:print edgeId='" + edges[0] + "'/>").then(function (response) { if (lang.exists("WUDebugResponse.Result", response)) { context.global.displayTrace(response.WUDebugResponse.Result, propertiesDom); } }); } } this.inSyncSelectionFrom = false; // }, 500, false) } resetPage() { this.main.clear(); } setMainRootItems(globalIDs) { const graphView = this.global.getGraphView(globalIDs, this.main.getDepth(), this.main.distance.get("value"), this.main.option("subgraph"), this.main.option("vhidespills")); return graphView.navigateTo(this.main); } refreshMainXGMML() { const graphView = this.main.getCurrentGraphView(); graphView.refreshXGMML(this.main); } displayGraphs(graphs) { for (let i = 0; i < graphs.length; ++i) { this.wu.fetchGraphXgmml(i, null, function (xgmml) { this.main.loadXGMML(xgmml, true); }); } } refreshActionState() { const tab = this.widget.OverviewTabContainer.get("selectedChildWidget"); this.setDisabled(this.id + "FindPrevious", this.foundIndex <= 0, "iconLeft", "iconLeftDisabled"); this.setDisabled(this.id + "FindNext", this.foundIndex >= this.found.length - 1, "iconRight", "iconRightDisabled"); this.setDisabled(this.id + "ActivityMetric", tab.id !== this.id + "ActivitiesTreeMap"); } }
the_stack
import * as assert from 'assert'; import * as fs from 'fs'; import * as sinon from 'sinon'; import appInsights from '../../../../appInsights'; import { Logger } from '../../../../cli'; import Command from '../../../../Command'; import { fsUtil, sinonUtil } from '../../../../utils'; import commands from '../../commands'; const command: Command = require('./package-generate'); const admZipMock = { // we need these unused params so that they can be properly mocked with sinon /* eslint-disable @typescript-eslint/no-unused-vars */ addFile: (entryName: string, data: Buffer, comment?: string, attr?: number) => { }, addLocalFile: (localPath: string, zipPath?: string, zipName?: string) => { }, writeZip: (targetFileName?: string, callback?: (error: Error | null) => void) => { } /* eslint-enable @typescript-eslint/no-unused-vars */ }; describe(commands.PACKAGE_GENERATE, () => { let log: any[]; let logger: Logger; before(() => { sinon.stub(appInsights, 'trackEvent').callsFake(() => { }); (command as any).archive = admZipMock; }); beforeEach(() => { log = []; logger = { log: (msg: string) => { log.push(msg); }, logRaw: (msg: string) => { log.push(msg); }, logToStderr: (msg: string) => { log.push(msg); } }; sinon.stub(fs, 'mkdtempSync').callsFake(_ => '/tmp/abc'); sinon.stub(fsUtil, 'readdirR').callsFake(_ => ['file1.png', 'file.json']); sinon.stub(fs, 'readFileSync').callsFake(_ => 'abc'); sinon.stub(fs, 'writeFileSync').callsFake(_ => { }); sinon.stub(fs, 'rmdirSync').callsFake(_ => { }); sinon.stub(fs, 'mkdirSync').callsFake(_ => '/tmp/abc/def'); sinon.stub(fs, 'copyFileSync').callsFake(_ => { }); sinon.stub(fs, 'statSync').callsFake(src => { return { isDirectory: () => src.toString().indexOf('.') < 0 } as any; }); }); afterEach(() => { sinonUtil.restore([ (command as any).generateNewId, admZipMock.addFile, admZipMock.addLocalFile, admZipMock.writeZip, fs.copyFileSync, fs.mkdtempSync, fs.mkdirSync, fs.readFileSync, fs.rmdirSync, fs.statSync, fs.writeFileSync, fsUtil.copyRecursiveSync, fsUtil.readdirR ]); }); after(() => { sinonUtil.restore([ appInsights.trackEvent ]); }); it('has correct name', () => { assert.strictEqual(command.name.startsWith(commands.PACKAGE_GENERATE), true); }); it('has a description', () => { assert.notStrictEqual(command.description, null); }); it('creates a package for the specified HTML snippet', done => { const archiveWriteZipSpy = sinon.spy(admZipMock, 'writeZip'); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'all', debug: false } }, (err?: any) => { try { assert.strictEqual(typeof err, 'undefined'); assert(archiveWriteZipSpy.called); done(); } catch (e) { done(e); } }); }); it('creates a package for the specified HTML snippet (debug)', done => { const archiveWriteZipSpy = sinon.spy(admZipMock, 'writeZip'); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'all', debug: true } }, (err?: any) => { try { assert.strictEqual(typeof err, 'undefined'); assert(archiveWriteZipSpy.called); done(); } catch (e) { done(e); } }); }); it('creates a package exposed as a Teams tab', done => { sinonUtil.restore([fs.readFileSync, fs.writeFileSync]); sinon.stub(fs, 'readFileSync').callsFake(_ => '$supportedHosts$'); const fsWriteFileSyncSpy = sinon.stub(fs, 'writeFileSync').callsFake(_ => { }); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'tab', debug: false } }, () => { try { assert(fsWriteFileSyncSpy.calledWith('file.json', JSON.stringify(['SharePointWebPart', 'TeamsTab']).replace(/"/g, '&quot;'))); done(); } catch (e) { done(e); } }); }); it('creates a package exposed as a Teams personal app', done => { sinonUtil.restore([fs.readFileSync, fs.writeFileSync]); sinon.stub(fs, 'readFileSync').callsFake(_ => '$supportedHosts$'); const fsWriteFileSyncSpy = sinon.stub(fs, 'writeFileSync').callsFake(_ => { }); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'personalApp', debug: false } }, () => { try { assert(fsWriteFileSyncSpy.calledWith('file.json', JSON.stringify(['SharePointWebPart', 'TeamsPersonalApp']).replace(/"/g, '&quot;'))); done(); } catch (e) { done(e); } }); }); it('creates a package exposed as a Teams tab and personal app', done => { sinonUtil.restore([fs.readFileSync, fs.writeFileSync]); sinon.stub(fs, 'readFileSync').callsFake(_ => '$supportedHosts$'); const fsWriteFileSyncSpy = sinon.stub(fs, 'writeFileSync').callsFake(_ => { }); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'all', debug: false } }, () => { try { assert(fsWriteFileSyncSpy.calledWith('file.json', JSON.stringify(['SharePointWebPart', 'TeamsTab', 'TeamsPersonalApp']).replace(/"/g, '&quot;'))); done(); } catch (e) { done(e); } }); }); it('handles exception when creating a temp folder failed', done => { sinonUtil.restore(fs.mkdtempSync); sinon.stub(fs, 'mkdtempSync').throws(new Error('An error has occurred')); const archiveWriteZipSpy = sinon.spy(admZipMock, 'writeZip'); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'all', debug: false } }, (err?: any) => { try { assert.strictEqual(err, 'An error has occurred'); assert(archiveWriteZipSpy.notCalled); done(); } catch (e) { done(e); } }); }); it('handles error when creating the package failed', done => { sinon.stub(admZipMock, 'writeZip').throws(new Error('An error has occurred')); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'all', debug: false } }, (err?: any) => { try { assert.strictEqual(err, 'An error has occurred'); done(); } catch (e) { done(e); } }); }); it('removes the temp directory after the package has been created', done => { sinonUtil.restore(fs.rmdirSync); const fsrmdirSyncSpy = sinon.stub(fs, 'rmdirSync').callsFake(_ => { }); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'all', debug: false } }, (err?: any) => { try { assert.strictEqual(typeof err, 'undefined'); assert(fsrmdirSyncSpy.called); done(); } catch (e) { done(e); } }); }); it('removes the temp directory if creating the package failed', done => { sinonUtil.restore(fs.rmdirSync); const fsrmdirSyncSpy = sinon.stub(fs, 'rmdirSync').callsFake(_ => { }); sinon.stub(admZipMock, 'writeZip').throws(new Error('An error has occurred')); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'all', debug: false } }, (err?: any) => { try { assert.notStrictEqual(typeof err, 'undefined'); assert(fsrmdirSyncSpy.called); done(); } catch (e) { done(e); } }); }); it('prompts user to remove the temp directory manually if removing it automatically failed', done => { sinonUtil.restore(fs.rmdirSync); sinon.stub(fs, 'rmdirSync').throws(new Error('An error has occurred')); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'all', debug: false } }, (err?: any) => { try { assert.strictEqual(err, 'An error has occurred while removing the temp folder at /tmp/abc. Please remove it manually.'); done(); } catch (e) { done(e); } }); }); it('leaves unknown token as-is', done => { sinonUtil.restore([fs.readFileSync, fs.writeFileSync]); sinon.stub(fs, 'readFileSync').callsFake(_ => '$token$'); const fsWriteFileSyncSpy = sinon.stub(fs, 'writeFileSync').callsFake(_ => { }); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, enableForTeams: 'tab', debug: false } }, () => { try { assert(fsWriteFileSyncSpy.calledWith('file.json', '$token$')); done(); } catch (e) { done(e); } }); }); it('exposes page context globally', done => { sinonUtil.restore([fs.readFileSync, fs.writeFileSync]); sinon.stub(fs, 'readFileSync').callsFake(_ => '$exposePageContextGlobally$'); const fsWriteFileSyncSpy = sinon.stub(fs, 'writeFileSync').callsFake(_ => { }); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, exposePageContextGlobally: true, debug: false } }, () => { try { assert(fsWriteFileSyncSpy.calledWith('file.json', '!0')); done(); } catch (e) { done(e); } }); }); it('exposes Teams context globally', done => { sinonUtil.restore([fs.readFileSync, fs.writeFileSync]); sinon.stub(fs, 'readFileSync').callsFake(_ => '$exposeTeamsContextGlobally$'); const fsWriteFileSyncSpy = sinon.stub(fs, 'writeFileSync').callsFake(_ => { }); command.action(logger, { options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: 'abc', allowTenantWideDeployment: true, exposeTeamsContextGlobally: true, debug: false } }, () => { try { assert(fsWriteFileSyncSpy.calledWith('file.json', '!0')); done(); } catch (e) { done(e); } }); }); it(`fails validation if the enableForTeams option is invalid`, () => { const actual = command.validate({ options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: '@amsterdam-weather.html', allowTenantWideDeployment: true, enableForTeams: 'invalid' } }); assert.notStrictEqual(actual, true); }); it(`passes validation if the enableForTeams option is set to tab`, () => { const actual = command.validate({ options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: '@amsterdam-weather.html', allowTenantWideDeployment: true, enableForTeams: 'tab' } }); assert.strictEqual(actual, true); }); it(`passes validation if the enableForTeams option is set to personalApp`, () => { const actual = command.validate({ options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: '@amsterdam-weather.html', allowTenantWideDeployment: true, enableForTeams: 'personalApp' } }); assert.strictEqual(actual, true); }); it(`passes validation if the enableForTeams option is set to all`, () => { const actual = command.validate({ options: { webPartTitle: 'Amsterdam weather', webPartDescription: 'Shows weather in Amsterdam', packageName: 'amsterdam-weather', html: '@amsterdam-weather.html', allowTenantWideDeployment: true, enableForTeams: 'all' } }); assert.strictEqual(actual, true); }); it('supports debug mode', () => { const options = command.options(); let containsOption = false; options.forEach(o => { if (o.option === '--debug') { containsOption = true; } }); assert(containsOption); }); });
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/environmentsMappers"; import * as Parameters from "../models/parameters"; import { ManagedLabsClientContext } from "../managedLabsClientContext"; /** Class representing a Environments. */ export class Environments { private readonly client: ManagedLabsClientContext; /** * Create a Environments. * @param {ManagedLabsClientContext} client Reference to the service client. */ constructor(client: ManagedLabsClientContext) { this.client = client; } /** * List environments in a given environment setting. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param [options] The optional parameters * @returns Promise<Models.EnvironmentsListResponse> */ list(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: Models.EnvironmentsListOptionalParams): Promise<Models.EnvironmentsListResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param callback The callback */ list(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironment>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options: Models.EnvironmentsListOptionalParams, callback: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironment>): void; list(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, options?: Models.EnvironmentsListOptionalParams | msRest.ServiceCallback<Models.ResponseWithContinuationEnvironment>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironment>): Promise<Models.EnvironmentsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, environmentSettingName, options }, listOperationSpec, callback) as Promise<Models.EnvironmentsListResponse>; } /** * Get environment * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param [options] The optional parameters * @returns Promise<Models.EnvironmentsGetResponse> */ get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: Models.EnvironmentsGetOptionalParams): Promise<Models.EnvironmentsGetResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param callback The callback */ get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: msRest.ServiceCallback<Models.Environment>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: Models.EnvironmentsGetOptionalParams, callback: msRest.ServiceCallback<Models.Environment>): void; get(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: Models.EnvironmentsGetOptionalParams | msRest.ServiceCallback<Models.Environment>, callback?: msRest.ServiceCallback<Models.Environment>): Promise<Models.EnvironmentsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, environmentSettingName, environmentName, options }, getOperationSpec, callback) as Promise<Models.EnvironmentsGetResponse>; } /** * Create or replace an existing Environment. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param environment Represents an environment instance * @param [options] The optional parameters * @returns Promise<Models.EnvironmentsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: Models.Environment, options?: msRest.RequestOptionsBase): Promise<Models.EnvironmentsCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param environment Represents an environment instance * @param callback The callback */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: Models.Environment, callback: msRest.ServiceCallback<Models.Environment>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param environment Represents an environment instance * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: Models.Environment, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Environment>): void; createOrUpdate(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: Models.Environment, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Environment>, callback?: msRest.ServiceCallback<Models.Environment>): Promise<Models.EnvironmentsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, environmentSettingName, environmentName, environment, options }, createOrUpdateOperationSpec, callback) as Promise<Models.EnvironmentsCreateOrUpdateResponse>; } /** * Delete environment. This operation can take a while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,labAccountName,labName,environmentSettingName,environmentName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Modify properties of environments. * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param environment Represents an environment instance * @param [options] The optional parameters * @returns Promise<Models.EnvironmentsUpdateResponse> */ update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: Models.EnvironmentFragment, options?: msRest.RequestOptionsBase): Promise<Models.EnvironmentsUpdateResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param environment Represents an environment instance * @param callback The callback */ update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: Models.EnvironmentFragment, callback: msRest.ServiceCallback<Models.Environment>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param environment Represents an environment instance * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: Models.EnvironmentFragment, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Environment>): void; update(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, environment: Models.EnvironmentFragment, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Environment>, callback?: msRest.ServiceCallback<Models.Environment>): Promise<Models.EnvironmentsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, environmentSettingName, environmentName, environment, options }, updateOperationSpec, callback) as Promise<Models.EnvironmentsUpdateResponse>; } /** * Claims the environment and assigns it to the user * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ claim(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param callback The callback */ claim(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param options The optional parameters * @param callback The callback */ claim(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; claim(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, labAccountName, labName, environmentSettingName, environmentName, options }, claimOperationSpec, callback); } /** * Resets the user password on an environment This operation can take a while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param resetPasswordPayload Represents the payload for resetting passwords. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ resetPassword(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: Models.ResetPasswordPayload, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginResetPassword(resourceGroupName,labAccountName,labName,environmentSettingName,environmentName,resetPasswordPayload,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Starts an environment by starting all resources inside the environment. This operation can take * a while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ start(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginStart(resourceGroupName,labAccountName,labName,environmentSettingName,environmentName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Stops an environment by stopping all resources inside the environment This operation can take a * while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ stop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginStop(resourceGroupName,labAccountName,labName,environmentSettingName,environmentName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Delete environment. This operation can take a while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, labAccountName, labName, environmentSettingName, environmentName, options }, beginDeleteMethodOperationSpec, options); } /** * Resets the user password on an environment This operation can take a while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param resetPasswordPayload Represents the payload for resetting passwords. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginResetPassword(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, resetPasswordPayload: Models.ResetPasswordPayload, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, labAccountName, labName, environmentSettingName, environmentName, resetPasswordPayload, options }, beginResetPasswordOperationSpec, options); } /** * Starts an environment by starting all resources inside the environment. This operation can take * a while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginStart(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, labAccountName, labName, environmentSettingName, environmentName, options }, beginStartOperationSpec, options); } /** * Stops an environment by stopping all resources inside the environment This operation can take a * while to complete * @param resourceGroupName The name of the resource group. * @param labAccountName The name of the lab Account. * @param labName The name of the lab. * @param environmentSettingName The name of the environment Setting. * @param environmentName The name of the environment. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginStop(resourceGroupName: string, labAccountName: string, labName: string, environmentSettingName: string, environmentName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, labAccountName, labName, environmentSettingName, environmentName, options }, beginStopOperationSpec, options); } /** * List environments in a given environment setting. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.EnvironmentsListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.EnvironmentsListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironment>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironment>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ResponseWithContinuationEnvironment>, callback?: msRest.ServiceCallback<Models.ResponseWithContinuationEnvironment>): Promise<Models.EnvironmentsListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.EnvironmentsListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName ], queryParameters: [ Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ResponseWithContinuationEnvironment }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments/{environmentName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName, Parameters.environmentName ], queryParameters: [ Parameters.expand, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Environment }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments/{environmentName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName, Parameters.environmentName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "environment", mapper: { ...Mappers.Environment, required: true } }, responses: { 200: { bodyMapper: Mappers.Environment }, 201: { bodyMapper: Mappers.Environment }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments/{environmentName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName, Parameters.environmentName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "environment", mapper: { ...Mappers.EnvironmentFragment, required: true } }, responses: { 200: { bodyMapper: Mappers.Environment }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const claimOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments/{environmentName}/claim", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName, Parameters.environmentName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments/{environmentName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName, Parameters.environmentName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginResetPasswordOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments/{environmentName}/resetPassword", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName, Parameters.environmentName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "resetPasswordPayload", mapper: { ...Mappers.ResetPasswordPayload, required: true } }, responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginStartOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments/{environmentName}/start", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName, Parameters.environmentName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginStopOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LabServices/labaccounts/{labAccountName}/labs/{labName}/environmentsettings/{environmentSettingName}/environments/{environmentName}/stop", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labAccountName, Parameters.labName, Parameters.environmentSettingName, Parameters.environmentName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ResponseWithContinuationEnvironment }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import path from 'path'; import { Loader, LoaderResource } from '@pixi/loaders'; import { Texture, BaseTexture } from '@pixi/core'; import { BaseTextureCache, TextureCache, url, clearTextureCache } from '@pixi/utils'; import { SpritesheetLoader, Spritesheet } from '@pixi/spritesheet'; import sinon from 'sinon'; import { expect } from 'chai'; describe('SpritesheetLoader', function () { it('should exist and return a function', function () { expect(SpritesheetLoader).to.not.be.undefined; expect(SpritesheetLoader.use).to.be.a('function'); }); it('should install middleware', function (done) { Loader.registerPlugin(SpritesheetLoader); const loader = new Loader(); const baseTextures = Object.keys(BaseTextureCache).length; const textures = Object.keys(TextureCache).length; loader.add('building1', path.join(__dirname, 'resources/building1.json')); loader.load((loader, resources) => { expect(resources.building1).to.be.instanceof(LoaderResource); expect(resources.building1.spritesheet).to.be.instanceof(Spritesheet); resources.building1.spritesheet.destroy(true); expect(Object.keys(BaseTextureCache).length).to.equal(baseTextures); expect(Object.keys(TextureCache).length).to.equal(textures); loader.reset(); done(); }); }); it('should do nothing if the resource is not JSON', function () { const spy = sinon.spy(); const res = {}; SpritesheetLoader.use(res, spy); expect(spy).to.have.been.calledOnce; expect(res.textures).to.be.undefined; }); it('should do nothing if the resource is JSON, but improper format', function () { const spy = sinon.spy(); const res = createMockResource(LoaderResource.TYPE.JSON, {}); SpritesheetLoader.use(res, spy); expect(spy).to.have.been.calledOnce; expect(res.textures).to.be.undefined; }); it('should load the image & create textures if json is properly formatted', function () { const spy = sinon.spy(); const res = createMockResource(LoaderResource.TYPE.JSON, getJsonSpritesheet()); const loader = new Loader(); const addStub = sinon.stub(loader, 'add'); const imgRes = createMockResource(LoaderResource.TYPE.IMAGE, new Image()); imgRes.texture = new Texture(new BaseTexture(imgRes.data)); addStub.yields(imgRes); SpritesheetLoader.use.call(loader, res, spy); addStub.restore(); expect(spy).to.have.been.calledOnce; expect(addStub).to.have.been.calledWith( `${res.name}_image`, `${path.dirname(res.url)}/${res.data.meta.image}` ); expect(res).to.have.property('textures') .that.is.an('object') .with.keys(Object.keys(getJsonSpritesheet().frames)) .and.has.property('0.png') .that.is.an.instanceof(Texture); expect(res.textures['0.png'].frame.x).to.equal(14); expect(res.textures['0.png'].frame.y).to.equal(28); expect(res.textures['0.png'].defaultAnchor.x).to.equal(0.3); expect(res.textures['0.png'].defaultAnchor.y).to.equal(0.4); expect(res.textures['1.png'].defaultAnchor.x).to.equal(0.0); // default of defaultAnchor is 0,0 expect(res.textures['1.png'].defaultAnchor.y).to.equal(0.0); expect(res).to.have.property('spritesheet') .to.have.property('animations') .to.have.property('png123'); expect(res.spritesheet.animations.png123.length).to.equal(3); expect(res.spritesheet.animations.png123[0]).to.equal(res.textures['1.png']); }); it('should not load binary images as an image loader type', function (done) { const loader = new Loader(); // provide a mock pre-loader that creates an empty base texture for compressed texture assets // this is necessary because the SpriteSheetLoader expects a baseTexture on the resource loader.pre((resource, next) => { if (resource.extension === 'crn') { resource.texture = Texture.EMPTY; } next(); }) .add(`atlas_crn`, path.join(__dirname, 'resources', 'atlas_crn.json')) .add(`atlas`, path.join(__dirname, 'resources', 'building1.json')) .load((loader, resources) => { expect(resources.atlas_image.data).to.be.instanceof(HTMLImageElement); expect(resources.atlas_crn_image.data).to.not.be.instanceof(HTMLImageElement); loader.reset(); done(); }); }); it('should dispatch an error failing to load spritesheet image', function (done) { const spy = sinon.spy((error, ldr, res) => { expect(res.name).to.equal('atlas_error_image'); expect(res.error).to.equal(error); expect(error.toString()).to.have.string('Failed to load element using: IMG'); }); const loader = new Loader(); loader.add('atlas_error', path.join(__dirname, 'resources', 'atlas_error.json')); loader.onError.add(spy); loader.load((loader, resources) => { expect(resources.atlas_error_image.error).to.be.instanceof(Error); expect(spy.calledOnce).to.be.true; loader.reset(); done(); }); }); it('should build the image url', function () { function getPath(url, image) { return SpritesheetLoader.getResourcePath({ url, data: { meta: { image } }, }); } let result = getPath('http://some.com/spritesheet.json', 'img.png'); expect(result).to.be.equals('http://some.com/img.png'); result = getPath('http://some.com/some/dir/spritesheet.json', 'img.png'); expect(result).to.be.equals('http://some.com/some/dir/img.png'); result = getPath('http://some.com/some/dir/spritesheet.json', './img.png'); expect(result).to.be.equals('http://some.com/some/dir/img.png'); result = getPath('http://some.com/some/dir/spritesheet.json', '../img.png'); expect(result).to.be.equals('http://some.com/some/img.png'); result = getPath('/spritesheet.json', 'img.png'); expect(result).to.be.equals('/img.png'); result = getPath('/some/dir/spritesheet.json', 'img.png'); expect(result).to.be.equals('/some/dir/img.png'); result = getPath('/some/dir/spritesheet.json', './img.png'); expect(result).to.be.equals('/some/dir/img.png'); result = getPath('/some/dir/spritesheet.json', '../img.png'); expect(result).to.be.equals('/some/img.png'); }); // TODO: Test that rectangles are created correctly. // TODO: Test that bathc processing works correctly. // TODO: Test that resolution processing works correctly. // TODO: Test that metadata is honored. it('should not add itself via multipack', function (done) { // clear the caches only to avoid cluttering the output clearTextureCache(); const loader = new Loader(); loader.add('atlas_multi_self', path.join(__dirname, 'resources', 'building1-0.json')); loader.load((loader, resources) => { expect(Object.values(resources).filter((r) => r.url.includes('building1-0.json')).length).to.be.equals(1); loader.reset(); done(); }); }); it('should create multipack resources when related_multi_packs field is an array of strings', function (done) { // clear the caches only to avoid cluttering the output clearTextureCache(); const loader = new Loader(); loader.add('atlas_multi_child_check', path.join(__dirname, 'resources', 'building1-0.json')); loader.load((loader, resources) => { expect(resources.atlas_multi_child_check.children.some((r) => r.url.includes('building1-1.json'))).to.be.true; loader.reset(); done(); }); }); it('should not create multipack resources when related_multi_packs field is missing or the wrong type', function (done) { // clear the caches only to avoid cluttering the output clearTextureCache(); const loader = new Loader(); loader.add('atlas_no_multipack', path.join(__dirname, 'resources', 'building1.json')); loader.add('atlas_multipack_wrong_type', path.join(__dirname, 'resources', 'atlas-multipack-wrong-type.json')); loader.add('atlas_multipack_wrong_array', path.join(__dirname, 'resources', 'atlas-multipack-wrong-array.json')); loader.load((loader, resources) => { expect(resources.atlas_no_multipack.children.length).to.be.equals(1); expect(resources.atlas_multipack_wrong_type.children.length).to.be.equals(1); expect(resources.atlas_multipack_wrong_array.children.length).to.be.equals(1); loader.reset(); done(); }); }); it('should build the multipack url', function () { let result = url.resolve('http://some.com/spritesheet.json', 'spritesheet-1.json'); expect(result).to.be.equals('http://some.com/spritesheet-1.json'); result = url.resolve('http://some.com/some/dir/spritesheet.json', 'spritesheet-1.json'); expect(result).to.be.equals('http://some.com/some/dir/spritesheet-1.json'); result = url.resolve('http://some.com/some/dir/spritesheet.json', './spritesheet-1.json'); expect(result).to.be.equals('http://some.com/some/dir/spritesheet-1.json'); result = url.resolve('http://some.com/some/dir/spritesheet.json', '../spritesheet-1.json'); expect(result).to.be.equals('http://some.com/some/spritesheet-1.json'); result = url.resolve('/spritesheet.json', 'spritesheet-1.json'); expect(result).to.be.equals('/spritesheet-1.json'); result = url.resolve('/some/dir/spritesheet.json', 'spritesheet-1.json'); expect(result).to.be.equals('/some/dir/spritesheet-1.json'); result = url.resolve('/some/dir/spritesheet.json', './spritesheet-1.json'); expect(result).to.be.equals('/some/dir/spritesheet-1.json'); result = url.resolve('/some/dir/spritesheet.json', '../spritesheet-1.json'); expect(result).to.be.equals('/some/spritesheet-1.json'); }); it('should use metadata to load all multipack resources', function (done) { // clear the caches only to avoid cluttering the output clearTextureCache(); const loader = new Loader(); const metadata = { key: 'value' }; loader.add('building1-0', path.join(__dirname, 'resources', 'building1-0.json'), { metadata }); loader.load((loader, resources) => { expect(resources['building1-0'].metadata).to.be.equals(metadata); expect(resources['building1-1'].metadata).to.be.equals(metadata); done(); }); }); }); function createMockResource(type, data) { const name = `${Math.floor(Date.now() * Math.random())}`; return { url: `http://localhost/doesnt_exist/${name}`, name, type, data, metadata: {}, }; } function getJsonSpritesheet() { /* eslint-disable */ return {"frames": { "0.png": { "frame": {"x":14,"y":28,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14}, "anchor": {"x":0.3,"y":0.4} }, "1.png": { "frame": {"x":14,"y":42,"w":12,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":12,"h":14}, "sourceSize": {"w":12,"h":14} }, "2.png": { "frame": {"x":14,"y":14,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14} }, "3.png": { "frame": {"x":42,"y":0,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14} }, "4.png": { "frame": {"x":28,"y":0,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14} }, "5.png": { "frame": {"x":14,"y":0,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14} }, "6.png": { "frame": {"x":0,"y":42,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14} }, "7.png": { "frame": {"x":0,"y":28,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14} }, "8.png": { "frame": {"x":0,"y":14,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14} }, "9.png": { "frame": {"x":0,"y":0,"w":14,"h":14}, "rotated": false, "trimmed": false, "spriteSourceSize": {"x":0,"y":0,"w":14,"h":14}, "sourceSize": {"w":14,"h":14} }}, "animations": { "png123": [ "1.png", "2.png", "3.png" ] }, "meta": { "app": "http://www.texturepacker.com", "version": "1.0", "image": "hud.png", "format": "RGBA8888", "size": {"w":64,"h":64}, "scale": "1", "smartupdate": "$TexturePacker:SmartUpdate:47025c98c8b10634b75172d4ed7e7edc$" } }; /* eslint-enable */ }
the_stack
* A stream is a read-only sequence of values. While the contents of an array can be accessed * both sequentially and randomly (via index), a stream allows only sequential access. * * The advantage of this is that a stream can be evaluated lazily, so it does not require * to store intermediate values. This can boost performance when a large sequence is * processed via filtering, mapping etc. and accessed at most once. However, lazy * evaluation means that all processing is repeated when you access the sequence multiple * times; in such a case, it may be better to store the resulting sequence into an array. */ export interface Stream<T> extends Iterable<T> { /** * Returns an iterator for this stream. This is the same as calling the `Symbol.iterator` function property. */ iterator(): IterableIterator<T>; /** * Determines whether this stream contains no elements. */ isEmpty(): boolean; /** * Determines the number of elements in this stream. */ count(): number; /** * Collects all elements of this stream into an array. */ toArray(): T[]; /** * Collects all elements of this stream into a Set. */ toSet(): Set<T>; /** * Collects all elements of this stream into a Map, applying the provided functions to determine keys and values. * * @param keyFn The function to derive map keys. If omitted, the stream elements are used as keys. * @param valueFn The function to derive map values. If omitted, the stream elements are used as values. */ toMap<K = T, V = T>(keyFn?: (e: T) => K, valueFn?: (e: T) => V): Map<K, V>; /** * Returns a string representation of a stream. */ toString(): string; /** * Combines two streams by returning a new stream that yields all elements of this stream and the other stream. * * @param other Stream to be concatenated with this one. */ concat<T2>(other: Iterable<T2>): Stream<T | T2>; /** * Adds all elements of the stream into a string, separated by the specified separator string. * * @param separator A string used to separate one element of the stream from the next in the resulting string. * If omitted, the steam elements are separated with a comma. */ join(separator?: string): string /** * Returns the index of the first occurrence of a value in the stream, or -1 if it is not present. * * @param searchElement The value to locate in the array. * @param fromIndex The stream index at which to begin the search. If fromIndex is omitted, the search * starts at index 0. */ indexOf(searchElement: T, fromIndex?: number): number; /** * Determines whether all members of the stream satisfy the specified test. * * @param predicate This method calls the predicate function for each element in the stream until the * predicate returns a value which is coercible to the Boolean value `false`, or until the end * of the stream. */ every<S extends T>(predicate: (value: T) => value is S): this is Stream<S>; every(predicate: (value: T) => unknown): boolean; /** * Determines whether any member of the stream satisfies the specified test. * * @param predicate This method calls the predicate function for each element in the stream until the * predicate returns a value which is coercible to the Boolean value `true`, or until the end * of the stream. */ some(predicate: (value: T) => unknown): boolean; /** * Performs the specified action for each element in the stream. * * @param callbackfn Function called once for each element in the stream. */ forEach(callbackfn: (value: T, index: number) => void): void; /** * Returns a stream that yields the results of calling the specified callback function on each element * of the stream. The function is called when the resulting stream elements are actually accessed, so * accessing the resulting stream multiple times means the function is also called multiple times for * each element of the stream. * * @param callbackfn Lazily evaluated function mapping stream elements. */ map<U>(callbackfn: (value: T) => U): Stream<U>; /** * Returns the elements of the stream that meet the condition specified in a callback function. * The function is called when the resulting stream elements are actually accessed, so accessing the * resulting stream multiple times means the function is also called multiple times for each element * of the stream. * * @param predicate Lazily evaluated function checking a condition on stream elements. */ filter<S extends T>(predicate: (value: T) => value is S): Stream<S>; filter(predicate: (value: T) => unknown): Stream<T>; /** * Calls the specified callback function for all elements in the stream. The return value of the * callback function is the accumulated result, and is provided as an argument in the next call to * the callback function. * * @param callbackfn This method calls the function once for each element in the stream, providing * the previous and current values of the reduction. * @param initialValue If specified, `initialValue` is used as the initial value to start the * accumulation. The first call to the function provides this value as an argument instead * of a stream value. */ reduce(callbackfn: (previousValue: T, currentValue: T) => T): T | undefined; reduce<U = T>(callbackfn: (previousValue: U, currentValue: T) => U, initialValue: U): U; /** * Calls the specified callback function for all elements in the stream, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * * @param callbackfn This method calls the function once for each element in the stream, providing * the previous and current values of the reduction. * @param initialValue If specified, `initialValue` is used as the initial value to start the * accumulation. The first call to the function provides this value as an argument instead * of an array value. */ reduceRight(callbackfn: (previousValue: T, currentValue: T) => T): T | undefined; reduceRight<U = T>(callbackfn: (previousValue: U, currentValue: T) => U, initialValue: U): U; /** * Returns the value of the first element in the stream that meets the condition, or `undefined` * if there is no such element. * * @param predicate This method calls `predicate` once for each element of the stream, in ascending * order, until it finds one where `predicate` returns a value which is coercible to the * Boolean value `true`. */ find<S extends T>(predicate: (value: T) => value is S): S | undefined; find(predicate: (value: T) => unknown): T | undefined; /** * Returns the index of the first element in the stream that meets the condition, or `-1` * if there is no such element. * * @param predicate This method calls `predicate` once for each element of the stream, in ascending * order, until it finds one where `predicate` returns a value which is coercible to the * Boolean value `true`. */ findIndex(predicate: (value: T) => unknown): number; /** * Determines whether the stream includes a certain element, returning `true` or `false` as appropriate. * * @param searchElement The element to search for. */ includes(searchElement: T): boolean; /** * Calls a defined callback function on each element of the stream and then flattens the result into * a new stream. This is identical to a `map` followed by `flat` with depth 1. * * @param callback Lazily evaluated function mapping stream elements. */ flatMap<U>(callbackfn: (value: T) => U | Iterable<U>): Stream<U>; /** * Returns a new stream with all sub-stream or sub-array elements concatenated into it recursively up * to the specified depth. * * @param depth The maximum recursion depth. Defaults to 1. */ flat<D extends number = 1>(depth?: D): FlatStream<T, D>; /** * Returns the first element in the stream, or `undefined` if the stream is empty. */ head(): T | undefined; /** * Returns a stream that skips the first `skipCount` elements from this stream. * * @param skipCount The number of elements to skip. If this is larger than the number of elements in * the stream, an empty stream is returned. Defaults to 1. */ tail(skipCount?: number): Stream<T>; /** * Returns a stream consisting of the elements of this stream, truncated to be no longer than `maxSize` * in length. * * @param maxSize The number of elements the stream should be limited to */ limit(maxSize: number): Stream<T>; /** * Returns a stream containing only the distinct elements from this stream. Equality is determined * with the same rules as a standard `Set`. * * @param by A function returning the key used to check equality with a previous stream element. * If omitted, the stream elements themselves are used for comparison. */ distinct<Key = T>(by?: (element: T) => Key): Stream<T>; } export type FlatStream<T, Depth extends number> = { 'done': Stream<T>, 'recur': T extends Iterable<infer Content> ? FlatStream<Content, MinusOne<Depth>> : Stream<T> }[Depth extends 0 ? 'done' : 'recur']; export type MinusOne<N extends number> = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][N]; /** * The default implementation of `Stream` works with two input functions: * - The first function creates the initial state of an iteration. * - The second function gets the current state as argument and returns an `IteratorResult`. */ export class StreamImpl<S, T> implements Stream<T> { protected readonly startFn: () => S; protected readonly nextFn: (state: S) => IteratorResult<T>; constructor(startFn: () => S, nextFn: (state: S) => IteratorResult<T, undefined>) { this.startFn = startFn; this.nextFn = nextFn; } iterator(): IterableIterator<T> { const iterator = { state: this.startFn(), next: () => this.nextFn(iterator.state), [Symbol.iterator]: () => iterator }; return iterator; } [Symbol.iterator](): Iterator<T> { return this.iterator(); } isEmpty(): boolean { const iterator = this.iterator(); return !!iterator.next().done; } count(): number { const iterator = this.iterator(); let count = 0; let next = iterator.next(); while (!next.done) { count++; next = iterator.next(); } return count; } toArray(): T[] { const result: T[] = []; const iterator = this.iterator(); let next: IteratorResult<T>; do { next = iterator.next(); if (next.value !== undefined) { result.push(next.value); } } while (!next.done); return result; } toSet(): Set<T> { return new Set(this); } toMap<K = T, V = T>(keyFn?: (e: T) => K, valueFn?: (e: T) => V): Map<K, V> { const entryStream = this.map(element => <[K, V]>[ keyFn ? keyFn(element) : element, valueFn ? valueFn(element) : element ]); return new Map(entryStream); } toString(): string { return this.join(); } concat<T2>(other: Iterable<T2>): Stream<T | T2> { const iterator = other[Symbol.iterator](); return new StreamImpl<{ first: S, firstDone: boolean }, T | T2>( () => ({ first: this.startFn(), firstDone: false }), state => { let result: IteratorResult<T | T2>; if (!state.firstDone) { do { result = this.nextFn(state.first); if (!result.done) { return result; } } while (!result.done); state.firstDone = true; } do { result = iterator.next(); if (!result.done) { return result; } } while (!result.done); return DONE_RESULT; } ); } join(separator = ','): string { const iterator = this.iterator(); let value = ''; let result: IteratorResult<T>; let addSeparator = false; do { result = iterator.next(); if (!result.done) { if (addSeparator) { value += separator; } value += toString(result.value); } addSeparator = true; } while (!result.done); return value; } indexOf(searchElement: T, fromIndex = 0): number { const iterator = this.iterator(); let index = 0; let next = iterator.next(); while (!next.done) { if (index >= fromIndex && next.value === searchElement) { return index; } next = iterator.next(); index++; } return -1; } every(predicate: (value: T) => unknown): boolean { const iterator = this.iterator(); let next = iterator.next(); while (!next.done) { if (!predicate(next.value)) { return false; } next = iterator.next(); } return true; } some(predicate: (value: T) => unknown): boolean { const iterator = this.iterator(); let next = iterator.next(); while (!next.done) { if (predicate(next.value)) { return true; } next = iterator.next(); } return false; } forEach(callbackfn: (value: T, index: number) => void): void { const iterator = this.iterator(); let index = 0; let next = iterator.next(); while (!next.done) { callbackfn(next.value, index); next = iterator.next(); index++; } } map<U>(callbackfn: (value: T) => U): Stream<U> { return new StreamImpl<S, U>( this.startFn, (state) => { const { done, value } = this.nextFn(state); if (done) { return DONE_RESULT; } else { return { done: false, value: callbackfn(value) }; } } ); } filter(predicate: (value: T) => unknown): Stream<T> { return new StreamImpl<S, T>( this.startFn, state => { let result: IteratorResult<T>; do { result = this.nextFn(state); if (!result.done && predicate(result.value)) { return result; } } while (!result.done); return DONE_RESULT; } ); } reduce<U>(callbackfn: (previousValue: U | T, currentValue: T) => U, initialValue?: U): U | T | undefined { const iterator = this.iterator(); let previousValue: U | T | undefined = initialValue; let next = iterator.next(); while (!next.done) { if (previousValue === undefined) { previousValue = next.value; } else { previousValue = callbackfn(previousValue, next.value); } next = iterator.next(); } return previousValue; } reduceRight<U>(callbackfn: (previousValue: U | T, currentValue: T) => U, initialValue?: U): U | T | undefined { return this.recursiveReduce(this.iterator(), callbackfn, initialValue); } protected recursiveReduce<U>(iterator: Iterator<T>, callbackfn: (previousValue: U | T, currentValue: T) => U, initialValue?: U): U | T | undefined { const next = iterator.next(); if (next.done) { return initialValue; } const previousValue = this.recursiveReduce(iterator, callbackfn, initialValue); if (previousValue === undefined) { return next.value; } return callbackfn(previousValue, next.value); } find(predicate: (value: T) => unknown): T | undefined { const iterator = this.iterator(); let next = iterator.next(); while (!next.done) { if (predicate(next.value)) { return next.value; } next = iterator.next(); } return undefined; } findIndex(predicate: (value: T) => unknown): number { const iterator = this.iterator(); let index = 0; let next = iterator.next(); while (!next.done) { if (predicate(next.value)) { return index; } next = iterator.next(); index++; } return -1; } includes(searchElement: T): boolean { const iterator = this.iterator(); let next = iterator.next(); while (!next.done) { if (next.value === searchElement) { return true; } next = iterator.next(); } return false; } flatMap<U>(callbackfn: (value: T) => U | Iterable<U>): Stream<U> { type FlatMapState = { this: S, iterator?: Iterator<U, undefined> } return new StreamImpl<FlatMapState, U>( () => ({ this: this.startFn() }), (state) => { do { if (state.iterator) { const next = state.iterator.next(); if (next.done) { state.iterator = undefined; } else { return next; } } const { done, value } = this.nextFn(state.this); if (!done) { const mapped = callbackfn(value); if (isIterable(mapped)) { state.iterator = mapped[Symbol.iterator](); } else { return { done: false, value: mapped }; } } } while (state.iterator); return DONE_RESULT; } ); } flat<D extends number = 1>(depth?: D): FlatStream<T, D> { if (depth === undefined) { depth = 1 as D; } if (depth <= 0) { return this as unknown as FlatStream<T, D>; } const stream = depth > 1 ? this.flat(depth - 1) as StreamImpl<S, unknown> : this; type FlatMapState = { this: S, iterator?: Iterator<T, undefined> } return new StreamImpl<FlatMapState, T>( () => ({ this: stream.startFn() }), (state) => { do { if (state.iterator) { const next = state.iterator.next(); if (next.done) { state.iterator = undefined; } else { return next; } } const { done, value } = stream.nextFn(state.this); if (!done) { if (isIterable(value)) { state.iterator = value[Symbol.iterator]() as Iterator<T>; } else { return { done: false, value }; } } } while (state.iterator); return DONE_RESULT; } ) as unknown as FlatStream<T, D>; } head(): T | undefined { const iterator = this.iterator(); const result = iterator.next(); if (result.done) { return undefined; } return result.value; } tail(skipCount = 1): Stream<T> { return new StreamImpl<S, T>( () => { const state = this.startFn(); for (let i = 0; i < skipCount; i++) { const next = this.nextFn(state); if (next.done) { return state; } } return state; }, this.nextFn ); } limit(maxSize: number): Stream<T> { return new StreamImpl<{ size: number, state: S }, T>( () => ({ size: 0, state: this.startFn() }), state => { state.size++; if (state.size > maxSize) { return DONE_RESULT; } return this.nextFn(state.state); } ); } distinct<Key = T>(by?: (element: T) => Key): Stream<T> { const set = new Set<T | Key>(); return this.filter(e => { const value = by ? by(e) : e; if (set.has(value)) { return false; } else { set.add(value); return true; } }); } } function toString(item: unknown): string { if (typeof item === 'string') { return item as string; } if (typeof item === 'undefined') { return 'undefined'; } // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof (item as any).toString === 'function') { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (item as any).toString(); } return Object.prototype.toString.call(item); } function isIterable<T>(obj: unknown): obj is Iterable<T> { return !!obj && typeof (obj as Iterable<T>)[Symbol.iterator] === 'function'; } /** * An empty stream of any type. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export const EMPTY_STREAM: Stream<any> = new StreamImpl<undefined, any>(() => undefined, () => DONE_RESULT); /** * Use this `IteratorResult` when implementing a `StreamImpl` to indicate that there are no more elements in the stream. */ export const DONE_RESULT: IteratorReturnResult<undefined> = Object.freeze({ done: true, value: undefined }); /** * Create a stream from one or more iterables or array-likes. */ export function stream<T>(...collections: Array<Iterable<T> | ArrayLike<T>>): Stream<T> { if (collections.length === 1) { const collection = collections[0]; if (collection instanceof StreamImpl) { return collection as Stream<T>; } if (isIterable(collection)) { return new StreamImpl<Iterator<T, undefined>, T>( () => collection[Symbol.iterator](), (iterator) => iterator.next() ); } if (typeof collection.length === 'number') { return new StreamImpl<{ index: number }, T>( () => ({ index: 0 }), (state) => { if (state.index < collection.length) { return { done: false, value: collection[state.index++] }; } else { return DONE_RESULT; } } ); } } if (collections.length > 1) { type State = { collIndex: number, iterator?: Iterator<T, undefined>, array?: ArrayLike<T>, arrIndex: number }; return new StreamImpl<State, T>( () => ({ collIndex: 0, arrIndex: 0 }), (state) => { do { if (state.iterator) { const next = state.iterator.next(); if (!next.done) { return next; } state.iterator = undefined; } if (state.array) { if (state.arrIndex < state.array.length) { return { done: false, value: state.array[state.arrIndex++] }; } state.array = undefined; state.arrIndex = 0; } if (state.collIndex < collections.length) { const collection = collections[state.collIndex++]; if (isIterable(collection)) { state.iterator = collection[Symbol.iterator](); } else if (collection && typeof collection.length === 'number') { state.array = collection; } } } while (state.iterator || state.array || state.collIndex < collections.length); return DONE_RESULT; } ); } return EMPTY_STREAM; } /** * A tree iterator adds the ability to prune the current iteration. */ export interface TreeIterator<T> extends IterableIterator<T> { /** * Skip the whole subtree below the last returned element. The iteration continues as if that * element had no children. */ prune(): void } /** * A tree stream is used to stream the elements of a tree, for example an AST or CST. */ export interface TreeStream<T> extends Stream<T> { iterator(): TreeIterator<T> } /** * The default implementation of `TreeStream` takes a root element and a function that computes the * children of its argument. The root is not included in the stream. */ export class TreeStreamImpl<T> extends StreamImpl<{ iterators: Array<Iterator<T>>, pruned: boolean }, T> implements TreeStream<T> { constructor(root: T, children: (node: T) => Iterable<T>) { super( () => ({ iterators: [children(root)[Symbol.iterator]()], pruned: false }), state => { if (state.pruned) { state.iterators.pop(); state.pruned = false; } while (state.iterators.length > 0) { const iterator = state.iterators[state.iterators.length - 1]; const next = iterator.next(); if (next.done) { state.iterators.pop(); } else { state.iterators.push(children(next.value)[Symbol.iterator]()); return next; } } return DONE_RESULT; } ); } iterator(): TreeIterator<T> { const iterator = { state: this.startFn(), next: () => this.nextFn(iterator.state), prune: () => { iterator.state.pruned = true; }, [Symbol.iterator]: () => iterator }; return iterator; } } /** * A set of utility functions that reduce a stream to a single value. */ export namespace Reduction { /** * Compute the sum of a number stream. */ export function sum(stream: Stream<number>): number { return stream.reduce((a, b) => a + b, 0); } /** * Compute the product of a number stream. */ export function product(stream: Stream<number>): number { return stream.reduce((a, b) => a * b, 0); } /** * Compute the minimum of a number stream. Returns `undefined` if the stream is empty. */ export function min(stream: Stream<number>): number | undefined { return stream.reduce((a, b) => Math.min(a, b)); } /** * Compute the maximum of a number stream. Returns `undefined` if the stream is empty. */ export function max(stream: Stream<number>): number | undefined { return stream.reduce((a, b) => Math.max(a, b)); } }
the_stack
import { formatDate, isFutureDate, isLessThanOneHourAgo, isLessThanOneMinuteAgo, isLessThanOneWeekAgo, isLessThanOneYearAgo, isToday, isTomorrow, isYesterday, TimeUnit, isLessThanOneWeekAway, isLessThanOneYearAway, } from '@shopify/dates'; import {memoize} from '@shopify/decorators'; import {languageFromLocale, regionFromLocale} from '@shopify/i18n'; import { I18nDetails, PrimitiveReplacementDictionary, ComplexReplacementDictionary, TranslationDictionary, LanguageDirection, } from './types'; import { dateStyle, DateStyle, DEFAULT_WEEK_START_DAY, WEEK_START_DAYS, RTL_LANGUAGES, Weekday, currencyDecimalPlaces, DEFAULT_DECIMAL_PLACES, EASTERN_NAME_ORDER_FORMATTERS, } from './constants'; import { MissingCurrencyCodeError, MissingCountryError, I18nError, } from './errors'; import { getCurrencySymbol, translate, getTranslationTree, TranslateOptions as RootTranslateOptions, memoizedNumberFormatter, memoizedPluralRules, convertFirstSpaceToNonBreakingSpace, } from './utilities'; export interface NumberFormatOptions extends Intl.NumberFormatOptions { as?: 'number' | 'currency' | 'percent'; precision?: number; } export interface CurrencyFormatOptions extends NumberFormatOptions { form?: 'auto' | 'short' | 'explicit' | 'none'; } export interface TranslateOptions { scope: RootTranslateOptions<any>['scope']; } // Used for currecies that don't use fractional units (eg. JPY) const DECIMAL_NOT_SUPPORTED = 'N/A'; const PERIOD = '.'; const DECIMAL_VALUE_FOR_CURRENCIES_WITHOUT_DECIMALS = '00'; export class I18n { readonly locale: string; readonly pseudolocalize: boolean | string; readonly defaultCountry?: string; readonly defaultCurrency?: string; readonly defaultTimezone?: string; readonly onError: NonNullable<I18nDetails['onError']>; readonly loading: boolean; get language() { return languageFromLocale(this.locale); } get region() { return regionFromLocale(this.locale); } /** * @deprecated Use I18n#region instead. */ get countryCode() { return regionFromLocale(this.locale); } get languageDirection() { return RTL_LANGUAGES.includes(this.language) ? LanguageDirection.Rtl : LanguageDirection.Ltr; } get isRtlLanguage() { return this.languageDirection === LanguageDirection.Rtl; } get isLtrLanguage() { return this.languageDirection === LanguageDirection.Ltr; } constructor( public readonly translations: TranslationDictionary[], { locale, currency, timezone, country, pseudolocalize = false, onError, loading, }: I18nDetails & {loading?: boolean}, ) { this.locale = locale; this.defaultCountry = country; this.defaultCurrency = currency; this.defaultTimezone = timezone; this.pseudolocalize = pseudolocalize; this.onError = onError || defaultOnError; this.loading = loading || false; } translate( id: string, options: TranslateOptions, replacements?: PrimitiveReplacementDictionary, ): string; translate( id: string, options: TranslateOptions, replacements?: ComplexReplacementDictionary, ): React.ReactElement<any>; translate(id: string, replacements?: PrimitiveReplacementDictionary): string; translate( id: string, replacements?: ComplexReplacementDictionary, ): React.ReactElement<any>; translate( id: string, optionsOrReplacements?: | TranslateOptions | PrimitiveReplacementDictionary | ComplexReplacementDictionary, replacements?: | PrimitiveReplacementDictionary | ComplexReplacementDictionary, ): any { const {pseudolocalize} = this; let normalizedOptions: RootTranslateOptions< PrimitiveReplacementDictionary | ComplexReplacementDictionary >; if (optionsOrReplacements == null) { normalizedOptions = {pseudotranslate: pseudolocalize}; } else if (isTranslateOptions(optionsOrReplacements)) { normalizedOptions = { ...optionsOrReplacements, replacements, pseudotranslate: pseudolocalize, }; } else { normalizedOptions = { replacements: optionsOrReplacements, pseudotranslate: pseudolocalize, }; } try { return translate(id, normalizedOptions, this.translations, this.locale); } catch (error) { this.onError(error); return ''; } } getTranslationTree( id: string, replacements?: | PrimitiveReplacementDictionary | ComplexReplacementDictionary, ): string | TranslationDictionary { try { if (!replacements) { return getTranslationTree(id, this.translations, this.locale); } return getTranslationTree( id, this.translations, this.locale, replacements, ); } catch (error) { this.onError(error); return ''; } } translationKeyExists(id: string) { try { getTranslationTree(id, this.translations, this.locale); return true; } catch (error) { return false; } } formatNumber( amount: number, {as, precision, ...options}: NumberFormatOptions = {}, ) { const {locale, defaultCurrency: currency} = this; if (as === 'currency' && currency == null && options.currency == null) { this.onError( new MissingCurrencyCodeError( `formatNumber(amount, {as: 'currency'}) cannot be called without a currency code.`, ), ); return ''; } return memoizedNumberFormatter(locale, { style: as, maximumFractionDigits: precision, currency, ...options, }).format(amount); } unformatNumber(input: string): string { const {thousandSymbol, decimalSymbol} = this.numberSymbols(); const normalizedValue = normalizedNumber( input, decimalSymbol, thousandSymbol === PERIOD, ); return normalizedValue === '' ? '' : parseFloat(normalizedValue).toString(); } formatCurrency( amount: number, {form, ...options}: CurrencyFormatOptions = {}, ) { switch (form) { case 'auto': return this.formatCurrencyAuto(amount, options); case 'explicit': return this.formatCurrencyExplicit(amount, options); case 'short': return this.formatCurrencyShort(amount, options); case 'none': return this.formatCurrencyNone(amount, options); } return this.formatNumber(amount, {as: 'currency', ...options}); } unformatCurrency(input: string, currencyCode: string): string { // This decimal symbol will always be '.' regardless of the locale // since it's our internal representation of the string const decimalSymbol = this.currencyDecimalSymbol(currencyCode); const expectedDecimalSymbol = decimalSymbol === DECIMAL_NOT_SUPPORTED ? PERIOD : decimalSymbol; const normalizedValue = normalizedNumber(input, expectedDecimalSymbol); if (normalizedValue === '') { return ''; } if (decimalSymbol === DECIMAL_NOT_SUPPORTED) { const roundedAmount = parseFloat(normalizedValue).toFixed(0); return `${roundedAmount}.${DECIMAL_VALUE_FOR_CURRENCIES_WITHOUT_DECIMALS}`; } const decimalPlaces = currencyDecimalPlaces.get(currencyCode.toUpperCase()) || DEFAULT_DECIMAL_PLACES; return parseFloat(normalizedValue).toFixed(decimalPlaces); } formatPercentage(amount: number, options: Intl.NumberFormatOptions = {}) { return this.formatNumber(amount, {as: 'percent', ...options}); } formatDate( date: Date, options: Intl.DateTimeFormatOptions & {style?: DateStyle} = {}, ): string { const {locale, defaultTimezone} = this; const {timeZone = defaultTimezone} = options; const {style = undefined, ...formatOptions} = options || {}; if (style) { return style === DateStyle.Humanize ? this.humanizeDate(date, {...formatOptions, timeZone}) : this.formatDate(date, {...formatOptions, ...dateStyle[style]}); } return formatDate(date, locale, {...formatOptions, timeZone}); } ordinal(amount: number) { const {locale} = this; const group = memoizedPluralRules(locale, {type: 'ordinal'}).select(amount); return this.translate(group, {scope: 'ordinal'}, {amount}); } weekStartDay(argCountry?: I18n['defaultCountry']): Weekday { const country = argCountry || this.defaultCountry; if (!country) { throw new MissingCountryError( 'weekStartDay() cannot be called without a country code.', ); } return WEEK_START_DAYS.get(country) || DEFAULT_WEEK_START_DAY; } getCurrencySymbol = (currencyCode?: string) => { const currency = currencyCode || this.defaultCurrency; if (currency == null) { throw new MissingCurrencyCodeError( 'formatCurrency cannot be called without a currency code.', ); } return this.getCurrencySymbolLocalized(this.locale, currency); }; getCurrencySymbolLocalized(locale: string, currency: string) { return getCurrencySymbol(locale, {currency}); } formatName( firstName?: string, lastName?: string, options?: {full?: boolean}, ) { if (!firstName) { return lastName || ''; } if (!lastName) { return firstName; } const isFullName = Boolean(options && options.full); const customNameFormatter = EASTERN_NAME_ORDER_FORMATTERS.get(this.locale) || EASTERN_NAME_ORDER_FORMATTERS.get(this.language); if (customNameFormatter) { return customNameFormatter(firstName, lastName, isFullName); } if (isFullName) { return `${firstName} ${lastName}`; } return firstName; } hasEasternNameOrderFormatter() { const easternNameOrderFormatter = EASTERN_NAME_ORDER_FORMATTERS.get(this.locale) || EASTERN_NAME_ORDER_FORMATTERS.get(this.language); return Boolean(easternNameOrderFormatter); } @memoize() numberSymbols() { const formattedNumber = this.formatNumber(123456.7, { maximumFractionDigits: 1, minimumFractionDigits: 1, }); let thousandSymbol; let decimalSymbol; for (const char of formattedNumber) { if (isNaN(parseInt(char, 10))) { if (thousandSymbol) decimalSymbol = char; else thousandSymbol = char; } } return {thousandSymbol, decimalSymbol}; } private formatCurrencyAuto( amount: number, options: Intl.NumberFormatOptions = {}, ): string { // use the short format if we can't determine a currency match, or if the // currencies match, use explicit when the currencies definitively do not // match. const formatShort = options.currency == null || this.defaultCurrency == null || options.currency === this.defaultCurrency; return formatShort ? this.formatCurrencyShort(amount, options) : this.formatCurrencyExplicit(amount, options); } private formatCurrencyExplicit( amount: number, options: Intl.NumberFormatOptions = {}, ): string { const value = this.formatCurrencyShort(amount, options); const isoCode = options.currency || this.defaultCurrency || ''; if (value.includes(isoCode)) { return value; } return `${value} ${isoCode}`; } private formatCurrencyShort( amount: number, options: NumberFormatOptions = {}, ): string { const formattedAmount = this.formatCurrencyNone(amount, options); const shortSymbol = this.getShortCurrencySymbol(options.currency); const formattedWithSymbol = shortSymbol.prefixed ? `${shortSymbol.symbol}${formattedAmount}` : `${formattedAmount}${shortSymbol.symbol}`; return amount < 0 ? `-${formattedWithSymbol.replace(/[-−]/, '')}` : formattedWithSymbol; } private formatCurrencyNone( amount: number, options: NumberFormatOptions = {}, ): string { const {locale} = this; let adjustedPrecision = options.precision; if (adjustedPrecision === undefined) { const currency = options.currency || this.defaultCurrency || ''; adjustedPrecision = currencyDecimalPlaces.get(currency.toUpperCase()); } return memoizedNumberFormatter(locale, { style: 'decimal', minimumFractionDigits: adjustedPrecision, maximumFractionDigits: adjustedPrecision, ...options, }).format(amount); } // Intl.NumberFormat sometimes annotates the "currency symbol" with a country code. // For example, in locale 'fr-FR', 'USD' is given the "symbol" of " $US". // This method strips out the country-code annotation, if there is one. // (So, for 'fr-FR' and 'USD', the return value would be " $"). // // For other currencies, e.g. CHF and OMR, the "symbol" is the ISO currency code. // In those cases, we return the full currency code without stripping the country. private getShortCurrencySymbol(currencyCode = this.defaultCurrency || '') { const currency = currencyCode || this.defaultCurrency || ''; const regionCode = currency.substring(0, 2); const info = this.getCurrencySymbol(currency); const shortSymbol = info.symbol.replace(regionCode, ''); const alphabeticCharacters = /[A-Za-zÀ-ÖØ-öø-ÿĀ-ɏḂ-ỳ]/; return alphabeticCharacters.exec(shortSymbol) ? info : {symbol: shortSymbol, prefixed: info.prefixed}; } private humanizeDate(date: Date, options?: Intl.DateTimeFormatOptions) { if (isFutureDate(date)) { return this.humanizeFutureDate(date, options); } else { return this.humanizePastDate(date, options); } } private humanizePastDate(date: Date, options?: Intl.DateTimeFormatOptions) { if (isLessThanOneMinuteAgo(date)) { return this.translate('date.humanize.lessThanOneMinuteAgo'); } if (isLessThanOneHourAgo(date)) { const now = new Date(); const minutes = Math.floor( (now.getTime() - date.getTime()) / TimeUnit.Minute, ); return this.translate('date.humanize.lessThanOneHourAgo', { count: minutes, }); } const timeZone = options?.timeZone; const time = this.getTimeFromDate(date, options); if (isToday(date, timeZone)) { return time; } if (isYesterday(date, timeZone)) { return this.translate('date.humanize.yesterday', {time}); } if (isLessThanOneWeekAgo(date)) { const weekday = this.getWeekdayFromDate(date, options); return this.translate('date.humanize.lessThanOneWeekAgo', { weekday, time, }); } if (isLessThanOneYearAgo(date)) { const monthDay = this.getMonthDayFromDate(date, options); return this.translate('date.humanize.lessThanOneYearAgo', { date: monthDay, time, }); } return this.formatDate(date, { ...options, style: DateStyle.Short, }); } private humanizeFutureDate(date: Date, options?: Intl.DateTimeFormatOptions) { const timeZone = options?.timeZone; const time = this.getTimeFromDate(date, options); if (isToday(date, timeZone)) { return this.translate('date.humanize.today', {time}); } if (isTomorrow(date, timeZone)) { return this.translate('date.humanize.tomorrow', {time}); } if (isLessThanOneWeekAway(date)) { const weekday = this.getWeekdayFromDate(date, options); return this.translate('date.humanize.lessThanOneWeekAway', { weekday, time, }); } if (isLessThanOneYearAway(date)) { const monthDay = this.getMonthDayFromDate(date, options); return this.translate('date.humanize.lessThanOneYearAway', { date: monthDay, time, }); } return this.formatDate(date, { ...options, style: DateStyle.Short, }); } private getTimeZone( date: Date, options?: Intl.DateTimeFormatOptions, ): string { const {localeMatcher, formatMatcher, timeZone} = options || {}; const hourZone = this.formatDate(date, { localeMatcher, formatMatcher, timeZone, hour12: false, timeZoneName: 'short', hour: 'numeric', }); const zoneMatchGroup = /\s([\w()+\-:.]+$)/.exec(hourZone); return zoneMatchGroup ? zoneMatchGroup[1] : ''; } private getTimeFromDate(date: Date, options?: Intl.DateTimeFormatOptions) { const {localeMatcher, formatMatcher, hour12, timeZone, timeZoneName} = options || {}; const formattedTime = this.formatDate(date, { localeMatcher, formatMatcher, hour12, timeZone, timeZoneName: timeZoneName === 'short' ? undefined : timeZoneName, hour: 'numeric', minute: '2-digit', }).toLocaleLowerCase(); const time = timeZoneName === 'short' ? `${formattedTime} ${this.getTimeZone(date, options)}` : formattedTime; return convertFirstSpaceToNonBreakingSpace(time); } private getWeekdayFromDate(date: Date, options?: Intl.DateTimeFormatOptions) { const {localeMatcher, formatMatcher, hour12, timeZone} = options || {}; return this.formatDate(date, { localeMatcher, formatMatcher, hour12, timeZone, weekday: 'long', }); } private getMonthDayFromDate( date: Date, options?: Intl.DateTimeFormatOptions, ) { const {localeMatcher, formatMatcher, hour12, timeZone} = options || {}; return this.formatDate(date, { localeMatcher, formatMatcher, hour12, timeZone, month: 'short', day: 'numeric', }); } private currencyDecimalSymbol(currencyCode: string) { const digitOrSpace = /\s|\d/g; const templatedInput = 1; const decimal = this.formatCurrencyNone(templatedInput, { currency: currencyCode, }).replace(digitOrSpace, ''); return decimal.length === 0 ? DECIMAL_NOT_SUPPORTED : decimal; } } function normalizedNumber( input: string, expectedDecimal: string, usesPeriodThousandSymbol?: boolean, ) { const nonDigits = /\D/g; // For locales that use non-period symbols as the decimal symbol, users may still input a period // and expect it to be treated as the decimal symbol for their locale. const hasExpectedDecimalSymbol = input.lastIndexOf(expectedDecimal) !== -1; const hasPeriodAsDecimal = input.lastIndexOf(PERIOD) !== -1; const usesPeriodDecimal = !usesPeriodThousandSymbol && !hasExpectedDecimalSymbol && hasPeriodAsDecimal; const decimalSymbolToUse = usesPeriodDecimal ? PERIOD : expectedDecimal; const lastDecimalIndex = input.lastIndexOf(decimalSymbolToUse); const integerValue = input .substring(0, lastDecimalIndex) .replace(nonDigits, ''); const decimalValue = input .substring(lastDecimalIndex + 1) .replace(nonDigits, ''); const isNegative = input.trim().startsWith('-'); const negativeSign = isNegative ? '-' : ''; const normalizedDecimal = lastDecimalIndex === -1 ? '' : PERIOD; const normalizedValue = `${negativeSign}${integerValue}${normalizedDecimal}${decimalValue}`; return normalizedValue === '' || normalizedValue === PERIOD ? '' : normalizedValue; } function isTranslateOptions( object: | TranslateOptions | PrimitiveReplacementDictionary | ComplexReplacementDictionary, ): object is TranslateOptions { return 'scope' in object; } function defaultOnError(error: I18nError) { throw error; }
the_stack
import { Context } from './contexts'; /** * Cookie options of the HttpResponse.setCookie method. * * The value of maxAge is in seconds. * * @export * @interface CookieOptions */ export interface CookieOptions { domain?: string; expires?: Date; httpOnly?: boolean; maxAge?: number; path?: string; secure?: boolean; sameSite?: 'strict'|'lax'|'none'; } /** * Represent an HTTP response. This class must be extended. * Instances of HttpResponse are returned in hooks and controller * methods. * * @export * @abstract * @class HttpResponse */ export abstract class HttpResponse { /** * Property used internally by isHttpResponse. * * @memberof HttpResponse */ readonly isHttpResponse = true; /** * Status code of the response. * * @abstract * @type {number} * @memberof HttpResponse */ abstract statusCode: number; /** * Status message of the response. It must follow the HTTP conventions * and be consistent with the statusCode property. * * @abstract * @type {string} * @memberof HttpResponse */ abstract statusMessage: string; /** * Specify if the body property is a stream. * * @type {boolean} * @memberof HttpResponse */ readonly stream: boolean = false; private cookies: { [key: string]: { value: string|undefined, options: CookieOptions } } = {}; private headers: { [key: string]: string } = {}; /** * Create an instance of HttpResponse. * @param {*} [body] - Optional body of the response. * @memberof HttpResponse */ constructor(public body?: any, options: { stream?: boolean } = {}) { this.stream = options.stream || false; } /** * Add or replace a header in the response. * * @param {string} name - The header name. * @param {string} value - The value name. * @returns {this} * @memberof HttpResponse */ setHeader(name: string, value: string): this { this.headers[name] = value; return this; } /** * Read the value of a header added with setHeader. * * @param {string} name - The header name. * @returns {(string|undefined)} The header value or undefined if it * does not exist. * @memberof HttpResponse */ getHeader(name: string): string|undefined { return this.headers[name]; } /** * Read all the headers added with setHeader. * * @returns {{ [key: string]: string }} - The headers. * @memberof HttpResponse */ getHeaders(): { [key: string]: string } { return { ...this.headers }; } /** * Add or replace a cookie in the response. * * @param {string} name - The cookie name. * @param {string} value - The cookie value. * @param {CookieOptions} [options={}] - The cookie directives if any. * @returns {this} * @memberof HttpResponse */ setCookie(name: string, value: string, options: CookieOptions = {}): this { this.cookies[name] = { value, options }; return this; } /** * Read the value and directives of a cookie added with setCookie. * * @param {string} name - The cookie name. * @returns {({ value: string|undefined, options: CookieOptions })} The cookie value and directives * or undefined and an empty object if the cookie does not exist. * @memberof HttpResponse */ getCookie(name: string): { value: string|undefined, options: CookieOptions } { if (!this.cookies[name]) { return { value: undefined, options: {} }; } const { value, options } = this.cookies[name]; return { value, options: { ...options } }; } /** * Read all the cookies added with setCookie. * * @returns {({ [key: string]: { value: string|undefined, options: CookieOptions } })} * The name, value and directives of the cookies. * @memberof HttpResponse */ getCookies(): { [key: string]: { value: string|undefined, options: CookieOptions } } { const cookies: { [key: string]: { value: string|undefined, options: CookieOptions } } = {}; for (const cookieName in this.cookies) { const { value, options } = this.cookies[cookieName]; cookies[cookieName] = { value, options: { ...options } }; } return cookies; } } /** * Check if an object is an instance of HttpResponse. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponse} - True if the error is an instance of HttpResponse. False otherwise. */ export function isHttpResponse(obj: any): obj is HttpResponse { return obj instanceof HttpResponse || (typeof obj === 'object' && obj !== null && obj.isHttpResponse === true); } /* 2xx Success */ /** * Represent an HTTP response with a success status 2xx. * * @export * @abstract * @class HttpResponseSuccess * @extends {HttpResponse} */ export abstract class HttpResponseSuccess extends HttpResponse { /** * Property used internally by isHttpResponseSuccess. * * @memberof HttpResponseSuccess */ readonly isHttpResponseSuccess = true; /** * Create an instance of HttpResponseSuccess. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseSuccess */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseSuccess. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseSuccess} - True if the error is an instance of HttpResponseSuccess. False otherwise. */ export function isHttpResponseSuccess(obj: any): obj is HttpResponseSuccess { return obj instanceof HttpResponseSuccess || (typeof obj === 'object' && obj !== null && obj.isHttpResponseSuccess === true); } /** * Represent an HTTP response with the status 200 - OK. * * @export * @class HttpResponseOK * @extends {HttpResponseSuccess} */ export class HttpResponseOK extends HttpResponseSuccess { /** * Property used internally by isHttpResponseOK. * * @memberof HttpResponseOK */ readonly isHttpResponseOK = true; statusCode = 200; statusMessage = 'OK'; /** * Create an instance of HttpResponseOK. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseOK */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseOK. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseOK} - True if the error is an instance of HttpResponseOK. False otherwise. */ export function isHttpResponseOK(obj: any): obj is HttpResponseOK { return obj instanceof HttpResponseOK || (typeof obj === 'object' && obj !== null && obj.isHttpResponseOK === true); } /** * Represent an HTTP response with the status 201 - CREATED. * * @export * @class HttpResponseCreated * @extends {HttpResponseSuccess} */ export class HttpResponseCreated extends HttpResponseSuccess { /** * Property used internally by isHttpResponseCreated. * * @memberof HttpResponseCreated */ readonly isHttpResponseCreated = true; statusCode = 201; statusMessage = 'CREATED'; /** * Create an instance of HttpResponseCreated. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseCreated */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseCreated. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseCreated} - True if the error is an instance of HttpResponseCreated. False otherwise. */ export function isHttpResponseCreated(obj: any): obj is HttpResponseCreated { return obj instanceof HttpResponseCreated || (typeof obj === 'object' && obj !== null && obj.isHttpResponseCreated === true); } /** * Represent an HTTP response with the status 204 - NO CONTENT. * * @export * @class HttpResponseNoContent * @extends {HttpResponseSuccess} */ export class HttpResponseNoContent extends HttpResponseSuccess { /** * Property used internally by is HttpResponseNoContent. * * @memberof HttpResponseNoContent */ readonly isHttpResponseNoContent = true; statusCode = 204; statusMessage = 'NO CONTENT'; /** * Create an instance of HttpResponseNoContent. * @memberof HttpResponseNoContent */ constructor() { super(); } } /** * Check if an object is an instance of HttpResponseNoContent. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseNoContent} - True if the error is an instance of HttpResponseNoContent. False otherwise. */ export function isHttpResponseNoContent(obj: any): obj is HttpResponseNoContent { return obj instanceof HttpResponseNoContent || (typeof obj === 'object' && obj !== null && obj.isHttpResponseNoContent === true); } /* 3xx Redirection */ /** * Represent an HTTP response with a redirection status 3xx. * * @export * @abstract * @class HttpResponseRedirection * @extends {HttpResponse} */ export abstract class HttpResponseRedirection extends HttpResponse { /** * Property used internally by isHttpResponseRedirection. * * @memberof HttpResponseRedirection */ readonly isHttpResponseRedirection = true; /** * Create an instance of HttpResponseRedirection. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseRedirection */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseRedirection. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseRedirection} - True if the error is an instance of HttpResponseRedirection. * False otherwise. */ export function isHttpResponseRedirection(obj: any): obj is HttpResponseRedirection { return obj instanceof HttpResponseRedirection || (typeof obj === 'object' && obj !== null && obj.isHttpResponseRedirection === true); } /** * Represent an HTTP response with the status 301 - MOVED PERMANENTLY. * * @export * @class HttpResponseMovedPermanently * @extends {HttpResponseRedirection} */ export class HttpResponseMovedPermanently extends HttpResponseRedirection { /** * Property used internally by isHttpResponseMovedPermanently. * * @memberof isHttpResponseMovedPermanently */ readonly isHttpResponseMovedPermanently = true; readonly statusCode = 301; readonly statusMessage = 'MOVED PERMANENTLY'; /** * Create an instance of HttpResponseMovedPermanently. * @param {string} path - The redirection path. * @memberof HttpResponseMovedPermanently */ constructor(public path: string) { super(); } } /** * Check if an object is an instance of HttpResponseMovedPermanently. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseMovedPermanently} - True if the error is an * instance of HttpResponseMovedPermanently. False otherwise. */ export function isHttpResponseMovedPermanently(obj: any): obj is HttpResponseMovedPermanently { return obj instanceof HttpResponseMovedPermanently || (typeof obj === 'object' && obj !== null && obj.isHttpResponseMovedPermanently === true); } /** * Represent an HTTP response with the status 302 - FOUND. * * @export * @class HttpResponseRedirect * @extends {HttpResponseRedirection} */ export class HttpResponseRedirect extends HttpResponseRedirection { /** * Property used internally by isHttpResponseRedirect. * * @memberof HttpResponseRedirect */ readonly isHttpResponseRedirect = true; statusCode = 302; statusMessage = 'FOUND'; /** * Create an instance of HttpResponseRedirect. * @param {string} path - The redirection path. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseRedirect */ constructor(public path: string, body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseRedirect. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseRedirect} - True if the error is an instance of HttpResponseRedirect. False otherwise. */ export function isHttpResponseRedirect(obj: any): obj is HttpResponseRedirect { return obj instanceof HttpResponseRedirect || (typeof obj === 'object' && obj !== null && obj.isHttpResponseRedirect === true); } /* 4xx Client Error */ /** * Represent an HTTP response with a client error status 4xx. * * @export * @abstract * @class HttpResponseClientError * @extends {HttpResponse} */ export abstract class HttpResponseClientError extends HttpResponse { /** * Property used internally by isHttpResponseClientError. * * @memberof HttpResponseClientError */ readonly isHttpResponseClientError = true; /** * Create an instance of HttpResponseClientError. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseClientError */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseClientError. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseClientError} - True if the error is an instance of HttpResponseClientError. * False otherwise. */ export function isHttpResponseClientError(obj: any): obj is HttpResponseClientError { return obj instanceof HttpResponseClientError || (typeof obj === 'object' && obj !== null && obj.isHttpResponseClientError === true); } /** * Represent an HTTP response with the status 400 - BAD REQUEST. * * @export * @class HttpResponseBadRequest * @extends {HttpResponseClientError} */ export class HttpResponseBadRequest extends HttpResponseClientError { /** * Property used internally by isHttpResponseBadRequest. * * @memberof HttpResponseBadRequest */ readonly isHttpResponseBadRequest = true; statusCode = 400; statusMessage = 'BAD REQUEST'; /** * Create an instance of HttpResponseBadRequest. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseBadRequest */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseBadRequest. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseBadRequest} - True if the error is an instance of HttpResponseBadRequest. * False otherwise. */ export function isHttpResponseBadRequest(obj: any): obj is HttpResponseBadRequest { return obj instanceof HttpResponseBadRequest || (typeof obj === 'object' && obj !== null && obj.isHttpResponseBadRequest === true); } /** * Represent an HTTP response with the status 401 - UNAUTHORIZED. * * @export * @class HttpResponseUnauthorized * @extends {HttpResponseClientError} */ export class HttpResponseUnauthorized extends HttpResponseClientError { /** * Property used internally by isHttpResponseUnauthorized. * * @memberof HttpResponseUnauthorized */ readonly isHttpResponseUnauthorized = true; statusCode = 401; statusMessage = 'UNAUTHORIZED'; /** * Create an instance of HttpResponseUnauthorized. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseUnauthorized */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); this.setHeader('WWW-Authenticate', ''); } } /** * Check if an object is an instance of HttpResponseUnauthorized. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseUnauthorized} - True if the error is an instance of HttpResponseUnauthorized. * False otherwise. */ export function isHttpResponseUnauthorized(obj: any): obj is HttpResponseUnauthorized { return obj instanceof HttpResponseUnauthorized || (typeof obj === 'object' && obj !== null && obj.isHttpResponseUnauthorized === true); } /** * Represent an HTTP response with the status 403 - FORBIDDEN. * * @export * @class HttpResponseForbidden * @extends {HttpResponseClientError} */ export class HttpResponseForbidden extends HttpResponseClientError { /** * Property used internally by isHttpResponseForbidden. * * @memberof HttpResponseForbidden */ readonly isHttpResponseForbidden = true; statusCode = 403; statusMessage = 'FORBIDDEN'; /** * Create an instance of HttpResponseForbidden. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseForbidden */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseForbidden. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseForbidden} - True if the error is an instance of HttpResponseForbidden. False otherwise. */ export function isHttpResponseForbidden(obj: any): obj is HttpResponseForbidden { return obj instanceof HttpResponseForbidden || (typeof obj === 'object' && obj !== null && obj.isHttpResponseForbidden === true); } /** * Represent an HTTP response with the status 404 - NOT FOUND. * * @export * @class HttpResponseNotFound * @extends {HttpResponseClientError} */ export class HttpResponseNotFound extends HttpResponseClientError { /** * Property used internally by isHttpResponseNotFound. * * @memberof HttpResponseNotFound */ readonly isHttpResponseNotFound = true; statusCode = 404; statusMessage = 'NOT FOUND'; /** * Create an instance of HttpResponseNotFound. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseNotFound */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseNotFound. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseNotFound} - True if the error is an instance of HttpResponseNotFound. False otherwise. */ export function isHttpResponseNotFound(obj: any): obj is HttpResponseNotFound { return obj instanceof HttpResponseNotFound || (typeof obj === 'object' && obj !== null && obj.isHttpResponseNotFound === true); } /** * Represent an HTTP response with the status 405 - METHOD NOT ALLOWED. * * @export * @class HttpResponseMethodNotAllowed * @extends {HttpResponseClientError} */ export class HttpResponseMethodNotAllowed extends HttpResponseClientError { /** * Property used internally by isHttpResponseMethodNotAllowed. * * @memberof HttpResponseMethodNotAllowed */ readonly isHttpResponseMethodNotAllowed = true; statusCode = 405; statusMessage = 'METHOD NOT ALLOWED'; /** * Create an instance of HttpResponseMethodNotAllowed. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseMethodNotAllowed */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseMethodNotAllowed. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseMethodNotAllowed} - True if the error is an instance of HttpResponseMethodNotAllowed. * False otherwise. */ export function isHttpResponseMethodNotAllowed(obj: any): obj is HttpResponseMethodNotAllowed { return obj instanceof HttpResponseMethodNotAllowed || (typeof obj === 'object' && obj !== null && obj.isHttpResponseMethodNotAllowed === true); } /** * Represent an HTTP response with the status 409 - CONFLICT. * * @export * @class HttpResponseConflict * @extends {HttpResponseClientError} */ export class HttpResponseConflict extends HttpResponseClientError { /** * Property used internally by isHttpResponseConflict. * * @memberof HttpResponseConflict */ readonly isHttpResponseConflict = true; statusCode = 409; statusMessage = 'CONFLICT'; /** * Create an instance of HttpResponseConflict. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseConflict */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseConflict. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseConflict} - True if the error is an instance of HttpResponseConflict. False otherwise. */ export function isHttpResponseConflict(obj: any): obj is HttpResponseConflict { return obj instanceof HttpResponseConflict || (typeof obj === 'object' && obj !== null && obj.isHttpResponseConflict === true); } /** * Represent an HTTP response with the status 429 - TOO MANY REQUESTS. * * @export * @class HttpResponseTooManyRequests * @extends {HttpResponseClientError} */ export class HttpResponseTooManyRequests extends HttpResponseClientError { /** * Property used internally by isHttpResponseTooManyRequests. * * @memberof HttpResponseTooManyRequests */ readonly isHttpResponseTooManyRequests = true; statusCode = 429; statusMessage = 'TOO MANY REQUESTS'; /** * Create an instance of HttpResponseTooManyRequests. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseTooManyRequests */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseTooManyRequests. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseTooManyRequests} - True if the error is an instance of HttpResponseTooManyRequests. * False otherwise. */ export function isHttpResponseTooManyRequests(obj: any): obj is HttpResponseTooManyRequests { return obj instanceof HttpResponseTooManyRequests || (typeof obj === 'object' && obj !== null && obj.isHttpResponseTooManyRequests === true); } /* 5xx Server Error */ /** * Represent an HTTP response with a server error status 5xx. * * @export * @abstract * @class HttpResponseServerError * @extends {HttpResponse} */ export abstract class HttpResponseServerError extends HttpResponse { /** * Property used internally by isHttpResponseServerError. * * @memberof HttpResponseServerError */ readonly isHttpResponseServerError = true; constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseServerError. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseServerError} - True if the error is an instance of HttpResponseServerError. * False otherwise. */ export function isHttpResponseServerError(obj: any): obj is HttpResponseServerError { return obj instanceof HttpResponseServerError || (typeof obj === 'object' && obj !== null && obj.isHttpResponseServerError === true); } /** * Represent an HTTP response with the status 500 - INTERNAL SERVER ERROR. * * @export * @class HttpResponseInternalServerError * @extends {HttpResponseServerError} */ export class HttpResponseInternalServerError extends HttpResponseServerError { /** * Property used internally by isHttpResponseInternalServerError. * * @memberof HttpResponseInternalServerError */ readonly isHttpResponseInternalServerError = true; readonly error?: Error; readonly ctx?: Context; statusCode = 500; statusMessage = 'INTERNAL SERVER ERROR'; /** * Create an instance of HttpResponseInternalServerError. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseInternalServerError */ constructor(body?: any, options: { stream?: boolean, error?: Error, ctx?: Context } = {}) { super(body, options); this.error = options.error; this.ctx = options.ctx; } } /** * Check if an object is an instance of HttpResponseInternalServerError. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseInternalServerError} - True if the error is an instance of * HttpResponseInternalServerError. False otherwise. */ export function isHttpResponseInternalServerError(obj: any): obj is HttpResponseInternalServerError { return obj instanceof HttpResponseInternalServerError || (typeof obj === 'object' && obj !== null && obj.isHttpResponseInternalServerError === true); } /** * Represent an HTTP response with the status 501 - NOT IMPLEMENTED. * * @export * @class HttpResponseNotImplemented * @extends {HttpResponseServerError} */ export class HttpResponseNotImplemented extends HttpResponseServerError { /** * Property used internally by isHttpResponseNotImplemented. * * @memberof HttpResponseNotImplemented */ readonly isHttpResponseNotImplemented = true; statusCode = 501; statusMessage = 'NOT IMPLEMENTED'; /** * Create an instance of HttpResponseNotImplemented. * @param {*} [body] - Optional body of the response. * @memberof HttpResponseNotImplemented */ constructor(body?: any, options: { stream?: boolean } = {}) { super(body, options); } } /** * Check if an object is an instance of HttpResponseNotImplemented. * * This function is a help when you have several packages using @foal/core. * Npm can install the package several times, which leads to duplicate class * definitions. If this is the case, the keyword `instanceof` may return false * while the object is an instance of the class. This function fixes this * problem. * * @export * @param {*} obj - The object to check. * @returns {obj is HttpResponseNotImplemented} - True if the error is an instance of HttpResponseNotImplemented. * False otherwise. */ export function isHttpResponseNotImplemented(obj: any): obj is HttpResponseNotImplemented { return obj instanceof HttpResponseNotImplemented || (typeof obj === 'object' && obj !== null && obj.isHttpResponseNotImplemented === true); }
the_stack
jest.useFakeTimers(); import React from 'react'; import produce from 'immer'; import {FlipperPlugin} from '../plugin'; import {renderMockFlipperWithPlugin} from '../test-utils/createMockFlipperWithPlugin'; import { _SandyPluginDefinition, PluginClient, TestUtils, usePlugin, createState, DevicePluginClient, DeviceLogEntry, useValue, } from 'flipper-plugin'; import {selectPlugin} from '../reducers/connections'; import {updateSettings} from '../reducers/settings'; import {switchPlugin} from '../reducers/pluginManager'; interface PersistedState { count: 1; } class TestPlugin extends FlipperPlugin<any, any, any> { static id = 'TestPlugin'; static defaultPersistedState = { count: 0, }; static details = TestUtils.createMockPluginDetails({ id: 'TestPlugin', }); static persistedStateReducer( persistedState: PersistedState, method: string, payload: {delta?: number}, ) { return produce(persistedState, (draft) => { if (method === 'inc') { draft.count += payload?.delta || 1; } }); } render() { return ( <h1> Hello:{' '} <span data-testid="counter">{this.props.persistedState.count}</span> </h1> ); } } test('Plugin container can render plugin and receive updates', async () => { const {renderer, sendMessage, act} = await renderMockFlipperWithPlugin( TestPlugin, ); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <h1> Hello: <span data-testid="counter" > 0 </span> </h1> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); act(() => { sendMessage('inc', {delta: 2}); }); expect((await renderer.findByTestId('counter')).textContent).toBe('2'); }); test('PluginContainer can render Sandy plugins', async () => { let renders = 0; function MySandyPlugin() { renders++; const sandyApi = usePlugin(plugin); const count = useValue(sandyApi.count); expect(Object.keys(sandyApi)).toEqual([ 'connectedStub', 'disconnectedStub', 'activatedStub', 'deactivatedStub', 'count', ]); expect(() => { // eslint-disable-next-line usePlugin(function bla() { return {}; }); }).toThrowError(/didn't match the type of the requested plugin/); return <div>Hello from Sandy{count}</div>; } type Events = { inc: {delta: number}; }; const plugin = (client: PluginClient<Events>) => { const count = createState(0); const connectedStub = jest.fn(); const disconnectedStub = jest.fn(); const activatedStub = jest.fn(); const deactivatedStub = jest.fn(); client.onConnect(connectedStub); client.onDisconnect(disconnectedStub); client.onActivate(activatedStub); client.onDeactivate(deactivatedStub); client.onMessage('inc', ({delta}) => { count.set(count.get() + delta); }); return { connectedStub, disconnectedStub, activatedStub, deactivatedStub, count, }; }; const definition = new _SandyPluginDefinition( TestUtils.createMockPluginDetails(), { plugin, Component: MySandyPlugin, }, ); const {renderer, act, sendMessage, client, store} = await renderMockFlipperWithPlugin(definition); expect(client.rawSend).toBeCalledWith('init', {plugin: 'TestPlugin'}); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <div> Hello from Sandy 0 </div> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); expect(renders).toBe(1); // sending irrelevant message does not cause a re-render act(() => { sendMessage('oops', {delta: 2}); }); expect(renders).toBe(1); // sending a new message cause a re-render act(() => { sendMessage('inc', {delta: 2}); }); expect(renders).toBe(2); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <div> Hello from Sandy 2 </div> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); // make sure the plugin gets connected const pluginInstance: ReturnType<typeof plugin> = client.sandyPluginStates.get(definition.id)!.instanceApi; expect(pluginInstance.connectedStub).toBeCalledTimes(1); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(0); // select non existing plugin act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: 'Logs', deepLinkPayload: null, }), ); }); expect(client.rawSend).toBeCalledWith('deinit', {plugin: 'TestPlugin'}); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> No plugin selected </div> </body> `); expect(pluginInstance.connectedStub).toBeCalledTimes(1); expect(pluginInstance.disconnectedStub).toBeCalledTimes(1); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); // send some messages while in BG act(() => { sendMessage('inc', {delta: 3}); sendMessage('inc', {delta: 4}); }); expect(renders).toBe(2); expect(pluginInstance.count.get()).toBe(2); // go back act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: definition.id, deepLinkPayload: null, }), ); }); // Might be needed, but seems to work reliable without: await sleep(1000); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <div> Hello from Sandy 9 </div> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); expect(pluginInstance.count.get()).toBe(9); expect(pluginInstance.connectedStub).toBeCalledTimes(2); expect(pluginInstance.disconnectedStub).toBeCalledTimes(1); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); expect(client.rawSend).toBeCalledWith('init', {plugin: 'TestPlugin'}); // disable act(() => { store.dispatch( switchPlugin({ plugin: definition, selectedApp: client.query.app, }), ); }); expect(pluginInstance.connectedStub).toBeCalledTimes(2); expect(pluginInstance.disconnectedStub).toBeCalledTimes(2); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(2); expect(client.rawSend).toBeCalledWith('deinit', {plugin: 'TestPlugin'}); // re-enable act(() => { store.dispatch( switchPlugin({ plugin: definition, selectedApp: client.query.app, }), ); }); // note: this is the old pluginInstance, so that one is not reconnected! expect(pluginInstance.connectedStub).toBeCalledTimes(2); expect(pluginInstance.disconnectedStub).toBeCalledTimes(2); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(2); expect( client.sandyPluginStates.get('TestPlugin')!.instanceApi.connectedStub, ).toBeCalledTimes(1); expect(client.rawSend).toBeCalledWith('init', {plugin: 'TestPlugin'}); expect( client.sandyPluginStates.get('TestPlugin')!.instanceApi.count.get(), ).toBe(0); }); test('PluginContainer triggers correct lifecycles for background plugin', async () => { function MySandyPlugin() { return <div>Hello from Sandy</div>; } const plugin = (client: PluginClient) => { const connectedStub = jest.fn(); const disconnectedStub = jest.fn(); const activatedStub = jest.fn(); const deactivatedStub = jest.fn(); client.onConnect(connectedStub); client.onDisconnect(disconnectedStub); client.onActivate(activatedStub); client.onDeactivate(deactivatedStub); return {connectedStub, disconnectedStub, activatedStub, deactivatedStub}; }; const definition = new _SandyPluginDefinition( TestUtils.createMockPluginDetails(), { plugin, Component: MySandyPlugin, }, ); const {act, client, store} = await renderMockFlipperWithPlugin(definition, { onSend(method) { if (method === 'getBackgroundPlugins') { return {plugins: [definition.id]}; } }, }); expect(client.rawSend).toBeCalledWith('init', {plugin: 'TestPlugin'}); (client.rawSend as jest.Mock).mockClear(); // make sure the plugin gets connected const pluginInstance: ReturnType<typeof plugin> = client.sandyPluginStates.get(definition.id)!.instanceApi; expect(pluginInstance.connectedStub).toBeCalledTimes(1); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(0); // select non existing plugin act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: 'Logs', deepLinkPayload: null, }), ); }); // bg plugin! expect(client.rawSend).not.toBeCalled(); (client.rawSend as jest.Mock).mockClear(); expect(pluginInstance.connectedStub).toBeCalledTimes(1); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); // go back act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: definition.id, deepLinkPayload: null, }), ); }); expect(pluginInstance.connectedStub).toBeCalledTimes(1); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); expect(client.rawSend).not.toBeCalled(); (client.rawSend as jest.Mock).mockClear(); // disable act(() => { store.dispatch( switchPlugin({ plugin: definition, selectedApp: client.query.app, }), ); }); expect(pluginInstance.connectedStub).toBeCalledTimes(1); expect(pluginInstance.disconnectedStub).toBeCalledTimes(1); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(2); expect(client.rawSend).toBeCalledWith('deinit', {plugin: 'TestPlugin'}); (client.rawSend as jest.Mock).mockClear(); // select something else act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: 'Logs', deepLinkPayload: null, }), ); }); // re-enable act(() => { store.dispatch( switchPlugin({ plugin: definition, selectedApp: client.query.app, }), ); }); // note: this is the old pluginInstance, so that one is not reconnected! expect(pluginInstance.connectedStub).toBeCalledTimes(1); expect(pluginInstance.disconnectedStub).toBeCalledTimes(1); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(2); const newPluginInstance: ReturnType<typeof plugin> = client.sandyPluginStates.get('TestPlugin')!.instanceApi; expect(newPluginInstance.connectedStub).toBeCalledTimes(1); expect(newPluginInstance.disconnectedStub).toBeCalledTimes(0); expect(newPluginInstance.activatedStub).toBeCalledTimes(0); expect(newPluginInstance.deactivatedStub).toBeCalledTimes(0); expect(client.rawSend).toBeCalledWith('init', {plugin: 'TestPlugin'}); (client.rawSend as jest.Mock).mockClear(); // select new plugin act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: definition.id, deepLinkPayload: null, }), ); }); expect(newPluginInstance.connectedStub).toBeCalledTimes(1); expect(newPluginInstance.disconnectedStub).toBeCalledTimes(0); expect(newPluginInstance.activatedStub).toBeCalledTimes(1); expect(newPluginInstance.deactivatedStub).toBeCalledTimes(0); expect(client.rawSend).not.toBeCalled(); (client.rawSend as jest.Mock).mockClear(); }); test('PluginContainer + Sandy plugin supports deeplink', async () => { const linksSeen: any[] = []; const plugin = (client: PluginClient) => { const linkState = createState(''); client.onDeepLink((link) => { linksSeen.push(link); linkState.set(String(link)); }); return { linkState, }; }; const definition = new _SandyPluginDefinition( TestUtils.createMockPluginDetails(), { plugin, Component() { const instance = usePlugin(plugin); const linkState = useValue(instance.linkState); return <h1>hello {linkState || 'world'}</h1>; }, }, ); const {renderer, act, client, store} = await renderMockFlipperWithPlugin( definition, ); expect(client.rawSend).toBeCalledWith('init', {plugin: 'TestPlugin'}); expect(linksSeen).toEqual([]); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <h1> hello world </h1> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); act(() => { store.dispatch( selectPlugin({ selectedPlugin: definition.id, deepLinkPayload: 'universe!', selectedAppId: client.id, }), ); }); jest.runAllTimers(); expect(linksSeen).toEqual(['universe!']); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <h1> hello universe! </h1> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); // Sending same link doesn't trigger again act(() => { store.dispatch( selectPlugin({ selectedPlugin: definition.id, deepLinkPayload: 'universe!', selectedAppId: client.id, }), ); }); jest.runAllTimers(); expect(linksSeen).toEqual(['universe!']); // ...nor does a random other store update that does trigger a plugin container render act(() => { store.dispatch( updateSettings({ ...store.getState().settingsState, }), ); }); expect(linksSeen).toEqual(['universe!']); // Different link does trigger again act(() => { store.dispatch( selectPlugin({ selectedPlugin: definition.id, deepLinkPayload: 'london!', selectedAppId: client.id, }), ); }); jest.runAllTimers(); expect(linksSeen).toEqual(['universe!', 'london!']); // and same link does trigger if something else was selected in the mean time act(() => { store.dispatch( selectPlugin({ selectedPlugin: 'Logs', deepLinkPayload: 'london!', selectedAppId: client.id, }), ); }); act(() => { store.dispatch( selectPlugin({ selectedPlugin: definition.id, deepLinkPayload: 'london!', selectedAppId: client.id, }), ); }); jest.runAllTimers(); expect(linksSeen).toEqual(['universe!', 'london!', 'london!']); }); test('PluginContainer can render Sandy device plugins', async () => { let renders = 0; function MySandyPlugin() { renders++; const sandyApi = usePlugin(devicePlugin); expect(Object.keys(sandyApi)).toEqual([ 'activatedStub', 'deactivatedStub', 'lastLogMessage', ]); expect(() => { // eslint-disable-next-line usePlugin(function bla() { return {}; }); }).toThrowError(/didn't match the type of the requested plugin/); const lastLogMessage = useValue(sandyApi.lastLogMessage); return <div>Hello from Sandy: {lastLogMessage?.message}</div>; } const devicePlugin = (client: DevicePluginClient) => { const lastLogMessage = createState<undefined | DeviceLogEntry>(undefined); const activatedStub = jest.fn(); const deactivatedStub = jest.fn(); client.onActivate(activatedStub); client.onDeactivate(deactivatedStub); client.onDeviceLogEntry((e) => { lastLogMessage.set(e); }); return {activatedStub, deactivatedStub, lastLogMessage}; }; const definition = new _SandyPluginDefinition( TestUtils.createMockPluginDetails({pluginType: 'device'}), { supportsDevice: () => true, devicePlugin, Component: MySandyPlugin, }, ); const {renderer, act, store, device} = await renderMockFlipperWithPlugin( definition, ); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <div> Hello from Sandy: </div> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); expect(renders).toBe(1); act(() => { device.addLogEntry({ date: new Date(), message: 'helleuh', pid: 0, tid: 0, type: 'info', tag: 'test', }); }); expect(renders).toBe(2); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <div> Hello from Sandy: helleuh </div> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); // make sure the plugin gets connected const pluginInstance: ReturnType<typeof devicePlugin> = device.sandyPluginStates.get(definition.id)!.instanceApi; expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(0); // select non existing plugin act(() => { store.dispatch( selectPlugin({ selectedDevice: device, selectedPlugin: 'Logs', deepLinkPayload: null, }), ); }); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> No plugin selected </div> </body> `); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); // go back act(() => { store.dispatch( selectPlugin({ selectedDevice: device, selectedPlugin: definition.id, deepLinkPayload: null, }), ); }); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); }); test('PluginContainer + Sandy device plugin supports deeplink', async () => { const linksSeen: any[] = []; const devicePlugin = (client: DevicePluginClient) => { const linkState = createState(''); client.onDeepLink((link) => { linksSeen.push(link); linkState.set(String(link)); }); return { linkState, }; }; const definition = new _SandyPluginDefinition( TestUtils.createMockPluginDetails({pluginType: 'device'}), { devicePlugin, supportsDevice: () => true, Component() { const instance = usePlugin(devicePlugin); const linkState = useValue(instance.linkState); return <h1>hello {linkState || 'world'}</h1>; }, }, ); const {renderer, act, store, device} = await renderMockFlipperWithPlugin( definition, ); const theUniverse = { thisIs: 'theUniverse', toString() { return JSON.stringify({...this}); }, }; expect(linksSeen).toEqual([]); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <h1> hello world </h1> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); act(() => { store.dispatch( selectPlugin({ selectedDevice: device, selectedPlugin: definition.id, deepLinkPayload: theUniverse, selectedAppId: null, }), ); }); jest.runAllTimers(); expect(linksSeen).toEqual([theUniverse]); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <h1> hello {"thisIs":"theUniverse"} </h1> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); // Sending same link doesn't trigger again act(() => { store.dispatch( selectPlugin({ selectedDevice: device, selectedPlugin: definition.id, deepLinkPayload: theUniverse, selectedAppId: null, }), ); }); jest.runAllTimers(); expect(linksSeen).toEqual([theUniverse]); // ...nor does a random other store update that does trigger a plugin container render act(() => { store.dispatch( updateSettings({ ...store.getState().settingsState, }), ); }); expect(linksSeen).toEqual([theUniverse]); // Different link does trigger again act(() => { store.dispatch( selectPlugin({ selectedDevice: device, selectedPlugin: definition.id, deepLinkPayload: 'london!', selectedAppId: null, }), ); }); jest.runAllTimers(); expect(linksSeen).toEqual([theUniverse, 'london!']); // and same link does trigger if something else was selected in the mean time act(() => { store.dispatch( selectPlugin({ selectedDevice: device, selectedPlugin: 'Logs', deepLinkPayload: 'london!', selectedAppId: null, }), ); }); act(() => { store.dispatch( selectPlugin({ selectedDevice: device, selectedPlugin: definition.id, deepLinkPayload: 'london!', selectedAppId: null, }), ); }); jest.runAllTimers(); expect(linksSeen).toEqual([theUniverse, 'london!', 'london!']); }); test('Sandy plugins support isPluginSupported + selectPlugin', async () => { let renders = 0; const linksSeen: any[] = []; function MySandyPlugin() { renders++; return <h1>Plugin1</h1>; } const plugin = (client: PluginClient) => { const activatedStub = jest.fn(); const deactivatedStub = jest.fn(); client.onDeepLink((link) => { linksSeen.push(link); }); client.onActivate(activatedStub); client.onDeactivate(deactivatedStub); return { activatedStub, deactivatedStub, selectPlugin: client.selectPlugin, }; }; const definition = new _SandyPluginDefinition( TestUtils.createMockPluginDetails({id: 'base'}), { plugin, Component: MySandyPlugin, }, ); const definition2 = new _SandyPluginDefinition( TestUtils.createMockPluginDetails({id: 'other'}), { plugin() { return {}; }, Component() { return <h1>Plugin2</h1>; }, }, ); const definition3 = new _SandyPluginDefinition( TestUtils.createMockPluginDetails({id: 'device', pluginType: 'device'}), { supportsDevice() { return true; }, devicePlugin() { return {}; }, Component() { return <h1>Plugin3</h1>; }, }, ); const {renderer, client, store} = await renderMockFlipperWithPlugin( definition, { additionalPlugins: [definition2, definition3], dontEnableAdditionalPlugins: true, }, ); expect(renderer.baseElement.querySelector('h1')).toMatchInlineSnapshot(` <h1> Plugin1 </h1> `); expect(renders).toBe(1); const pluginInstance: ReturnType<typeof plugin> = client.sandyPluginStates.get(definition.id)!.instanceApi; expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(0); expect(linksSeen).toEqual([]); // star and navigate to a device plugin store.dispatch(switchPlugin({plugin: definition3})); pluginInstance.selectPlugin(definition3.id); expect(store.getState().connections.selectedPlugin).toBe(definition3.id); expect(renderer.baseElement.querySelector('h1')).toMatchInlineSnapshot(` <h1> Plugin3 </h1> `); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); // go back by opening own plugin again (funny, but why not) pluginInstance.selectPlugin(definition.id, 'data'); expect(store.getState().connections.selectedPlugin).toBe(definition.id); expect(pluginInstance.activatedStub).toBeCalledTimes(2); jest.runAllTimers(); expect(renderer.baseElement.querySelector('h1')).toMatchInlineSnapshot(` <h1> Plugin1 </h1> `); expect(linksSeen).toEqual(['data']); // try to plugin 2 - it should be possible to select it even if it is not enabled pluginInstance.selectPlugin(definition2.id); expect(store.getState().connections.selectedPlugin).toBe(definition2.id); // star plugin 2 and navigate to plugin 2 store.dispatch( switchPlugin({ plugin: definition2, selectedApp: client.query.app, }), ); pluginInstance.selectPlugin(definition2.id); expect(store.getState().connections.selectedPlugin).toBe(definition2.id); expect(pluginInstance.deactivatedStub).toBeCalledTimes(2); expect(renderer.baseElement.querySelector('h1')).toMatchInlineSnapshot(` <h1> Plugin2 </h1> `); expect(renders).toBe(2); }); test('PluginContainer can render Sandy plugins for archived devices', async () => { let renders = 0; function MySandyPlugin() { renders++; const sandyApi = usePlugin(plugin); const count = useValue(sandyApi.count); expect(Object.keys(sandyApi)).toEqual([ 'connectedStub', 'disconnectedStub', 'activatedStub', 'deactivatedStub', 'count', ]); expect(() => { // eslint-disable-next-line usePlugin(function bla() { return {}; }); }).toThrowError(/didn't match the type of the requested plugin/); return <div>Hello from Sandy{count}</div>; } type Events = { inc: {delta: number}; }; const plugin = (client: PluginClient<Events>) => { expect(client.connected.get()).toBeFalsy(); expect(client.isConnected).toBeFalsy(); expect(client.device.isConnected).toBeFalsy(); expect(client.device.isArchived).toBeTruthy(); const count = createState(0); const connectedStub = jest.fn(); const disconnectedStub = jest.fn(); const activatedStub = jest.fn(); const deactivatedStub = jest.fn(); client.onConnect(connectedStub); client.onDisconnect(disconnectedStub); client.onActivate(activatedStub); client.onDeactivate(deactivatedStub); client.onMessage('inc', ({delta}) => { count.set(count.get() + delta); }); return { connectedStub, disconnectedStub, activatedStub, deactivatedStub, count, }; }; const definition = new _SandyPluginDefinition( TestUtils.createMockPluginDetails(), { plugin, Component: MySandyPlugin, }, ); const {renderer, act, client, store} = await renderMockFlipperWithPlugin( definition, {archivedDevice: true}, ); expect(client.rawSend).not.toBeCalled(); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <div> Hello from Sandy 0 </div> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); expect(renders).toBe(1); // make sure the plugin gets activated, but not connected! const pluginInstance: ReturnType<typeof plugin> = client.sandyPluginStates.get(definition.id)!.instanceApi; expect(pluginInstance.connectedStub).toBeCalledTimes(0); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(0); // select non existing plugin act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: 'Logs', deepLinkPayload: null, }), ); }); expect(client.rawSend).not.toBeCalled(); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> No plugin selected </div> </body> `); expect(pluginInstance.connectedStub).toBeCalledTimes(0); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); // go back act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: definition.id, deepLinkPayload: null, }), ); }); // Might be needed, but seems to work reliable without: await sleep(1000); expect(renderer.baseElement).toMatchInlineSnapshot(` <body> <div> <div class="css-1x2cmzz-SandySplitContainer e1hsqii10" > <div /> <div class="css-1knrt0j-SandySplitContainer e1hsqii10" > <div class="css-1woty6b-Container" > <div> Hello from Sandy 0 </div> </div> <div class="css-724x97-View-FlexBox-FlexRow" id="detailsSidebar" /> </div> </div> </div> </body> `); expect(pluginInstance.count.get()).toBe(0); expect(pluginInstance.connectedStub).toBeCalledTimes(0); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); expect(client.rawSend).not.toBeCalled(); }); test('PluginContainer triggers correct lifecycles for background plugin', async () => { function MySandyPlugin() { return <div>Hello from Sandy</div>; } const plugin = (client: PluginClient) => { expect(client.connected.get()).toBeFalsy(); expect(client.isConnected).toBeFalsy(); expect(client.device.isConnected).toBeFalsy(); expect(client.device.isArchived).toBeTruthy(); const connectedStub = jest.fn(); const disconnectedStub = jest.fn(); const activatedStub = jest.fn(); const deactivatedStub = jest.fn(); client.onConnect(connectedStub); client.onDisconnect(disconnectedStub); client.onActivate(activatedStub); client.onDeactivate(deactivatedStub); return {connectedStub, disconnectedStub, activatedStub, deactivatedStub}; }; const definition = new _SandyPluginDefinition( TestUtils.createMockPluginDetails(), { plugin, Component: MySandyPlugin, }, ); const {act, client, store} = await renderMockFlipperWithPlugin(definition, { archivedDevice: true, onSend(_method) { throw new Error('not to be called'); }, }); expect(client.rawSend).not.toBeCalled(); // make sure the plugin gets connected const pluginInstance: ReturnType<typeof plugin> = client.sandyPluginStates.get(definition.id)!.instanceApi; expect(pluginInstance.connectedStub).toBeCalledTimes(0); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(0); // select non existing plugin act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: 'Logs', deepLinkPayload: null, }), ); }); // bg plugin! expect(client.rawSend).not.toBeCalled(); expect(pluginInstance.connectedStub).toBeCalledTimes(0); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(1); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); // go back act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: definition.id, deepLinkPayload: null, }), ); }); expect(pluginInstance.connectedStub).toBeCalledTimes(0); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(2); expect(pluginInstance.deactivatedStub).toBeCalledTimes(1); expect(client.rawSend).not.toBeCalled(); // select something else act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: 'Logs', deepLinkPayload: null, }), ); }); // select new plugin act(() => { store.dispatch( selectPlugin({ selectedAppId: client.id, selectedPlugin: definition.id, deepLinkPayload: null, }), ); }); expect(pluginInstance.connectedStub).toBeCalledTimes(0); expect(pluginInstance.disconnectedStub).toBeCalledTimes(0); expect(pluginInstance.activatedStub).toBeCalledTimes(3); expect(pluginInstance.deactivatedStub).toBeCalledTimes(2); expect(client.rawSend).not.toBeCalled(); });
the_stack
import { ColorMatrixFilter } from '@pixi/filter-color-matrix'; import { Graphics, GraphicsGeometry, ILineStyleOptions } from '@pixi/graphics'; import { Sprite } from '@pixi/sprite'; import { utils } from './utils'; export type DrawCommands = (string|number)[]; export class AnimateGraphics extends Graphics { constructor(geometry?: GraphicsGeometry) { super(geometry); // overwrite with a cleaner version, so fewer function calls are involved this.s = super.lineStyle; } // ************************** // Graphics methods // ************************** /** * Execute a series of commands, this is the name of the short function * followed by the parameters, e.g., `["f", "#ff0000", "r", 0, 0, 100, 200]` * @param commands The commands and parameters to draw * @return This instance for chaining. */ public drawCommands(commands: DrawCommands): this { let currentCommand: string; const params = []; let i = 0; while (i <= commands.length) { const item = commands[i++]; if (item === undefined || (this as any)[item]) { if (currentCommand) { (this as any)[currentCommand].apply(this, params); params.length = 0; } currentCommand = item as string; } else { params.push(item); } } return this; } /** * Shortcut for `drawCommands`. */ public d = this.drawCommands; /** * Shortcut for `closePath`. **/ public cp = super.closePath; /** * Shortcut for `beginHole` **/ public bh = super.beginHole; /** * Shortcut for `endHole` **/ public eh = super.endHole; /** * Shortcut for `moveTo`. **/ public m = super.moveTo; /** * Shortcut for `lineTo`. **/ public l = super.lineTo; /** * Shortcut for `quadraticCurveTo`. **/ public q = super.quadraticCurveTo; /** * Shortcut for `bezierCurveTo`. **/ public b = super.bezierCurveTo; /** * Shortcut for `beginFill`. **/ public f = super.beginFill; /** * Shortcut for `lineStyle`. **/ public s(width: number, color?: number, alpha?: number, alignment?: number, native?: boolean): this; public s(options?: ILineStyleOptions): this; public s(...args: any[]): this { return super.lineStyle(...args); } /** * Shortcut for `drawRect`. **/ public dr = super.drawRect; /** * Shortcut for `drawRoundedRect`. **/ public rr = super.drawRoundedRect; /** * Shortcut for `drawRoundedRect`. **/ public rc = super.drawRoundedRect; /** * Shortcut for `drawCircle`. **/ public dc = super.drawCircle; /** * Shortcut for `arc`. **/ public ar = super.arc; /** * Shortcut for `arcTo`. **/ public at = super.arcTo; /** * Shortcut for `drawEllipse`. */ public de = super.drawEllipse; /** * Placeholder method for a linear gradient fill. Pixi does not support linear gradient fills, * so we just pick the first color in colorArray * @param colorArray An array of CSS compatible color values @see `f` * @return The Graphics instance the method is called on (useful for chaining calls.) **/ public lf(colorArray: number[]): this { // @if DEBUG console.warn('Linear gradient fills are not supported'); // @endif return this.f(colorArray[0]) as this; } /** * Placeholder method for a radial gradient fill. Pixi does not support radial gradient fills, * so we just pick the first color in colorArray * @param colorArray An array of CSS compatible color values @see `f` * @return The Graphics instance the method is called on (useful for chaining calls.) **/ public rf(colorArray: number[]): this { // @if DEBUG console.warn('Radial gradient fills are not supported'); // @endif return this.f(colorArray[0]) as this; } /** * Placeholder method for a `beginBitmapFill`. Pixi does not support bitmap fills. * @return The Graphics instance the method is called on (useful for chaining calls.) **/ public bf(): this { // @if DEBUG console.warn('Bitmap fills are not supported'); // @endif return this.f(0x0) as this; } /** * Placeholder method for a `setStrokeDash`. Pixi does not support dashed strokes. * @return The Graphics instance the method is called on (useful for chaining calls.) **/ public sd(): this { // @if DEBUG console.warn('Dashed strokes are not supported'); // @endif return this; } /** * Placeholder method for a `beginBitmapStroke`. Pixi does not support bitmap strokes. * @return The Graphics instance the method is called on (useful for chaining calls.) **/ public bs(): this { // @if DEBUG console.warn('Bitmap strokes are not supported'); // @endif return this; } /** * Placeholder method for a `beginLinearGradientStroke`. Pixi does not support gradient strokes. * @return The Graphics instance the method is called on (useful for chaining calls.) **/ public ls(): this { // @if DEBUG console.warn('Linear gradient strokes are not supported'); // @endif return this; } /** * Placeholder method for a `beginRadialGradientStroke`. Pixi does not support gradient strokes. * @return The Graphics instance the method is called on (useful for chaining calls.) **/ public rs(): this { // @if DEBUG console.warn('Radial gradient strokes are not supported'); // @endif return this; } // ************************** // DisplayObject methods // ************************** /** * Function to set if this is renderable or not. Useful for setting masks. * @param renderable Make renderable. Defaults to false. * @return This instance, for chaining. */ public setRenderable(renderable?: boolean): this { this.renderable = !!renderable; return this; } /** * Shortcut for `setRenderable`. */ public re = this.setRenderable; /** * Shortcut for `setTransform`. */ public t = super.setTransform; /** * Setter for mask to be able to chain. * @param mask The mask shape to use * @return Instance for chaining */ public setMask(mask: Graphics|Sprite): this { // According to PIXI, only Graphics and Sprites can // be used as mask, let's ignore everything else, like other // movieclips and displayobjects/containers if (mask) { if (!(mask instanceof Graphics) && !(mask instanceof Sprite)) { if (typeof console !== 'undefined' && console.warn) { console.warn('Warning: Masks can only be PIXI.Graphics or PIXI.Sprite objects.'); } return this; } } this.mask = mask; return this; } /** * Shortcut for `setMask`. */ public ma = this.setMask; /** * Chainable setter for alpha * @param alpha The alpha amount to use, from 0 to 1 * @return Instance for chaining */ public setAlpha(alpha: number): this { this.alpha = alpha; return this; } /** * Shortcut for `setAlpha`. */ public a = this.setAlpha; /** * Set the tint values by color. * @param tint The color value to tint * @return Object for chaining */ public setTint(tint: string|number): this { if (typeof tint === 'string') { tint = utils.hexToUint(tint); } // this.tint = tint // return this; // TODO: Replace with DisplayObject.tint setter // once the functionality is added to Pixi.js, for // now we'll use the slower ColorMatrixFilter to handle // the color transformation const r = (tint >> 16) & 0xFF; const g = (tint >> 8) & 0xFF; const b = tint & 0xFF; return this.setColorTransform(r / 255, 0, g / 255, 0, b / 255, 0); } /** * Shortcut for `setTint`. */ public i = this.setTint; /** * Set additive and multiply color, tinting * @param r The multiply red value * @param rA The additive red value * @param g The multiply green value * @param gA The additive green value * @param b The multiply blue value * @param bA The additive blue value * @return Object for chaining */ public setColorTransform(r: number, rA: number, g: number, gA: number, b: number, bA: number): this { const filter = this.colorTransformFilter; filter.matrix[0] = r; filter.matrix[4] = rA; filter.matrix[6] = g; filter.matrix[9] = gA; filter.matrix[12] = b; filter.matrix[14] = bA; this.filters = [filter]; return this; } /** * Shortcut for `setColor`. */ // method instead of direct reference to allow override in v1 shim public c(r: number, rA: number, g: number, gA: number, b: number, bA: number): this { return this.setColorTransform(r, rA, g, gA, b, bA); } // public c = this.setColorTransform; protected _colorTransformFilter: ColorMatrixFilter; /** * The current default color transforming filter */ public set colorTransformFilter(filter: ColorMatrixFilter) { this._colorTransformFilter = filter; } public get colorTransformFilter(): ColorMatrixFilter { return this._colorTransformFilter || new ColorMatrixFilter(); } }
the_stack
import React, { Component, } from "react"; import { autorun, IReactionDisposer, makeObservable, observable } from "mobx"; import prettyBytesOriginal from "pretty-bytes"; import prettyMillisecondsOriginal from 'pretty-ms'; import queryString from 'query-string'; import { editQuery } from "./queryHelper"; import { message } from "antd"; import { MessageType } from "antd/lib/message"; import { TopicMessage } from "../state/restInterfaces"; // Note: Making a <Memo> component is not possible, the container JSX will always render children first so they can be passed as props export const nameof = <T>(name: Extract<keyof T, string>): string => name; export class AutoRefresh extends Component { timerId: NodeJS.Timeout; componentDidMount() { this.reload = this.reload.bind(this); this.timerId = setInterval(() => this.reload(), 1000); } componentWillUnmount() { clearInterval(this.timerId); } reload() { this.forceUpdate(); } render() { //let c = this.props.children as ReactNodeArray; //console.log('AutoRefresh.render(): ' + c.length + ' children'); return (this.props.children); } } export class TimeSince { timestamp: number = Date.now(); /** Reset timer back to 0 ms (or the given value). For example '1000' will set the timer as if it was started 1 second ago. */ reset(to: number = 0) { this.timestamp = Date.now() - to; } /** Time since last reset (or create) in ms */ get value() { return Date.now() - this.timestamp; } } export class Cooldown { timestamp: number = 0; // time of last trigger duration: number = 0; // how long the CD takes to charge /** * @description Create a cooldown with the given duration * @param duration time the cooldown takes to complete in ms * @param start `running` to start 'on cooldown', `ready` to start already charged */ constructor(duration: number, start: ('ready' | 'running') = 'running') { this.duration = duration; if (start === 'running') { this.timestamp = Date.now() } } /** Time (in ms) since the last time the cooldown was triggered */ timeSinceLastTrigger(): number { return Date.now() - this.timestamp; } /** Time (in ms) until the cooldown is ready (or 0 if it is) */ get timeLeft(): number { const t = this.duration - this.timeSinceLastTrigger(); if (t < 0) return 0; return t; } // Check if ready get isReady(): boolean { return this.timeLeft <= 0; } // 'Use' the cooldown. Check if ready, and if it is also trigger it consume(force: boolean = false): boolean { if (this.timeLeft <= 0 || force) { this.timestamp = Date.now(); return true; } return false; } // Force the cooldown to be ready setReady(): void { this.timestamp = 0; } // Same as 'consume(true)' restart(): void { this.timestamp = Date.now(); } } export class Timer { target: number = 0; duration: number = 0; constructor(duration: number, initialState: ('started' | 'done') = 'started') { this.duration = duration; if (initialState === 'started') { this.target = Date.now() + duration; } else { this.target = 0; } } /** Time (in ms) until done (or 0) */ get timeLeft() { const t = this.target - Date.now(); if (t < 0) return 0; return t; } get isRunning() { return !this.isDone; } get isDone() { return this.timeLeft <= 0; } /** Restart timer */ restart() { this.target = Date.now() + this.duration; } /** Set timer completed */ setDone() { this.target = 0; } } export class DebugTimerStore { private static instance: DebugTimerStore; static get Instance() { if (!this.instance) this.instance = new DebugTimerStore(); return this.instance; } @observable secondCounter = 0; @observable private frame = 0; private constructor() { this.increaseSec = this.increaseSec.bind(this); setInterval(this.increaseSec, 1000); this.increaseFrame = this.increaseFrame.bind(this); //setInterval(this.increaseFrame, 30); makeObservable(this); } private increaseSec() { this.secondCounter++; } private increaseFrame() { this.frame++; } public useSeconds() { this.mobxTrigger = this.secondCounter; } public useFrame() { this.mobxTrigger = this.frame; } mobxTrigger: any; } let refreshCounter = 0; // used to always create a different value, forcing some components to always re-render export const alwaysChanging = () => refreshCounter = (refreshCounter + 1) % 1000; export function assignDeep(target: any, source: any) { for (const key in source) { if (!Object.prototype.hasOwnProperty.call(source, key)) continue; if (key === "__proto__" || key === "constructor") continue; const value = source[key]; const existing = key in target ? target[key] : undefined; // if (existing === undefined && onlySetExisting) { // console.log('skipping key ' + key + ' because it doesnt exist in the target'); // continue; // } if (typeof value === 'function' || typeof value === 'symbol') { //console.log('skipping key ' + key + ' because its type is ' + typeof value); continue; } if (typeof value === 'object') { if (!existing || typeof existing !== 'object') target[key] = value; else assignDeep(target[key], value); continue; } if (existing === value) continue; // console.log(`Key ["${key}"]: ${JSON.stringify(existing)} -> ${JSON.stringify(value)}`); target[key] = value; } } export function containsIgnoreCase(str: string, search: string): boolean { return str.toLowerCase().indexOf(search.toLowerCase()) >= 0; } const collator = new Intl.Collator(undefined, { usage: 'search', sensitivity: 'base', }); export function compareIgnoreCase(a: string, b: string) { return collator.compare(a, b); } type FoundProperty = { propertyName: string, path: string[], value: any } type PropertySearchResult = 'continue' | 'abort'; type PropertySearchExContext = { isMatch: (propertyName: string, path: string[], value: any) => boolean, currentPath: string[], results: FoundProperty[], returnFirstResult: boolean } export function collectElements(obj: any, isMatch: (propertyName: string, path: string[], value: any) => boolean, returnFirstMatch: boolean): FoundProperty[] { const ctx: PropertySearchExContext = { isMatch: isMatch, currentPath: [], results: [], returnFirstResult: returnFirstMatch, }; collectElementsRecursive(ctx, obj); return ctx.results; } function collectElementsRecursive(ctx: PropertySearchExContext, obj: any): PropertySearchResult { for (const key in obj) { const value = obj[key]; // property match? const isMatch = ctx.isMatch(key, ctx.currentPath, value); if (isMatch) { const clonedPath = Object.assign([], ctx.currentPath); ctx.results.push({ propertyName: key, path: clonedPath, value: value }); if (ctx.returnFirstResult) return 'abort'; } // descend into object if (typeof value === 'object') { ctx.currentPath.push(key); const childResult = collectElementsRecursive(ctx, value); ctx.currentPath.pop(); if (childResult == 'abort') return 'abort'; } } return 'continue'; } type IsMatchFunc = (pathElement: string, propertyName: string, value: any) => boolean; export type CollectedProperty = { path: string[], value: any } export function collectElements2( targetObject: any, // "**" collectes all current and nested properties // "*" collects all current properties // anything else is passed to "isMatch" path: string[], isMatch: IsMatchFunc ): CollectedProperty[] { // Explore set let currentExplore: CollectedProperty[] = [ { path: [], value: targetObject }, ]; let nextExplore: CollectedProperty[] = []; const results: CollectedProperty[] = []; for (let i = 0; i < path.length; i++) { const segment = path[i]; const isLast = i == (path.length - 1); const targetList = isLast ? results : nextExplore; for (const foundProp of currentExplore) { const currentObj = foundProp.value; switch (segment) { case "**": // And all their nested objects are a result const allNested = collectElements(currentObj, (key, path, value) => { return typeof value == 'object'; }, false); for (const n of allNested) { targetList.push({ path: [...foundProp.path, ...n.path, n.propertyName], value: n.value }); } // Also explore this object again as well (because '**' also includes the current props) targetList.push({ path: [...foundProp.path], value: currentObj, }); break; case "*": // Explore all properties for (const key in currentObj) { const value = currentObj[key]; if (value == null || typeof value == 'function') continue; targetList.push({ path: [...foundProp.path, key], value: value, }); } break; default: // Some user defined string for (const key in currentObj) { const value = currentObj[key]; if (value == null || typeof value == 'function') continue; const match = isMatch(segment, key, value); if (match) { targetList.push({ path: [...foundProp.path, key], value: value, }); } } break; } } // use the next array as the current one currentExplore = nextExplore; nextExplore = []; } return results; } export function getAllMessageKeys(messages: TopicMessage[]): Property[] { const ctx: GetAllKeysContext = { currentFullPath: "", currentPath: [], results: [], existingPaths: new Set<string>(), }; // slice is needed because messages array is observable for (const m of messages.slice()) { const payload = m.value.payload; getAllKeysRecursive(ctx, payload); ctx.currentPath = []; ctx.currentFullPath = ""; } // console.log('getAllMessageKeys', ctx.results); return ctx.results; } interface Property { /** property name */ propertyName: string; /** path to the property (excluding 'prop' itself) */ path: string[]; /** path + prop */ fullPath: string; } type GetAllKeysContext = { currentPath: string[], // complete, real path currentFullPath: string, // string path, with array indices replaced by a start existingPaths: Set<string>, // list of 'currentFullPath' entries, used to filter duplicates results: Property[], } function getAllKeysRecursive(ctx: GetAllKeysContext, obj: any): PropertySearchResult { const isArray = Array.isArray(obj); let result = 'continue' as PropertySearchResult; const pathToHere = ctx.currentFullPath; for (const key in obj) { const value = obj[key]; ctx.currentPath.push(key); const currentFullPath = isArray ? pathToHere + `[*]` : pathToHere + `.${key}`; ctx.currentFullPath = currentFullPath; if (!isArray) { // add result, but only for object properties const isNewPath = !ctx.existingPaths.has(currentFullPath); if (isNewPath) { // and only if its a new path ctx.existingPaths.add(currentFullPath); const clonedPath = Object.assign([], ctx.currentPath); ctx.results.push({ propertyName: key, path: clonedPath, // all the keys fullPath: currentFullPath, }); } } // descend into object if (typeof value === 'object' && value != null) { const childResult = getAllKeysRecursive(ctx, value); if (childResult == 'abort') result = 'abort'; } ctx.currentPath.pop(); ctx.currentFullPath = currentFullPath; if (result == 'abort') break; } ctx.currentFullPath = pathToHere; return result; } const secToMs = 1000; const minToMs = 60 * secToMs; const hoursToMs = 60 * minToMs; const daysToMs = 24 * hoursToMs; export function hoursToMilliseconds(hours: number) { return hours * hoursToMs; } export const cullText = (str: string, length: number) => str.length > length ? `${str.substring(0, length - 3)}...` : str; export function groupConsecutive(ar: number[]): number[][] { const groups: number[][] = []; for (const cur of ar) { const group = groups.length > 0 ? groups[groups.length - 1] : undefined; if (group) { const last = group[group.length - 1]; if (last == cur - 1) { // We can extend the group group.push(cur); continue; } } groups.push([cur]); } return groups; } export const prettyBytesOrNA = function (n: number) { if (!isFinite(n) || n < 0) return "N/A"; return prettyBytes(n); } export const prettyBytes = function (n: number) { if (typeof n === 'undefined' || n === null) return "N/A"; // null, undefined -> N/A if (typeof n !== 'number') { if (typeof n === 'string') { // string if (n === "") return "N/A"; // empty -> N/A n = parseFloat(String(n)); if (!isFinite(n)) return String(n); // "NaN" or "Infinity" // number parsed, fall through } else { // something else: object, function, ... return "NaN"; } } // n is a finite number return prettyBytesOriginal(n); } export const prettyMilliseconds = function (n: number, options?: prettyMillisecondsOriginal.Options) { if (typeof n === 'undefined' || n === null) return "N/A"; // null, undefined -> N/A if (typeof n !== 'number') { if (typeof n === 'string') { // string if (n === "") return "N/A"; // empty -> N/A n = parseFloat(String(n)); if (!isFinite(n)) return String(n); // "NaN" or "Infinity" // number parsed, fall through } else { // something else: object, function, ... return "NaN"; } } else { if (!isFinite(n)) return "N/A"; } // n is a finite number return prettyMillisecondsOriginal(n, options); } const between = (min: number, max: number) => (num: number) => num >= min && num < max; const isK = between(1000, 1000000); const isM = between(1000000, 1000000000); const isInfinite = (num: number) => !isFinite(num); const toK = (num: number) => `${(num / 1000).toFixed(1)}k`; const toM = (num: number) => `${(num / 1000000).toFixed(1)}m`; const toG = (num: number) => `${(num / 1000000000).toFixed(1)}g`; export function prettyNumber(num: number) { if (isNaN(num) || isInfinite(num) || num < 1000) return String(num); if (isK(num)) return toK(num); if (isM(num)) return toM(num); return toG(num); } export function fromDecimalSeparated(str: string): number { if (!str || str === '') return 0; return parseInt(str.replace(',', '')); } export function toDecimalSeparated(num: number): string { return String(num).replace(/\B(?=(\d{3})+(?!\d))/g, ','); } export function keepInRange(num: number, min: number, max: number) { if (num < min) return min; else if (num > max) return max; else return num; } /** * random digits and letters (entropy: 53bit) */ export function randomId() { return (Math.random() * Number.MAX_SAFE_INTEGER).toString(36); } /** * "prefix-randomId()-randomId()" */ export function simpleUniqueId(prefix?: string) { return `${prefix}-${randomId()}-${randomId()}`; } /** * 4x 'randomId()' */ export function uniqueId4(): string { return randomId() + randomId() + randomId() + randomId(); } export function titleCase(str: string): string { if (!str) return str; return str[0].toUpperCase() + str.slice(1); } // Bind an observable object to the url query // - reads the current query parameters and sets them on the observable // - whenever a prop in the observable changes, it updates the url // You might want to use different names for the query parameters: // observable = { propA: 5 } // queryNames = { 'propA': 'x' } // query => ?x=5 // export function bindObjectToUrl< // T extends { [key: string]: (number | string | number[] | string[]) }, // >(observable: T, queryNames: { [K in keyof T]?: string }): IReactionDisposer { export function bindObjectToUrl< TObservable extends { [K in keyof TQueryNames]: (number | string | number[] | string[] | null | undefined) }, TQueryNames extends { [K in keyof TObservable]: string }, >( observable: { [K in keyof TQueryNames]: any }, queryNames: TQueryNames, shouldInclude?: (propName: keyof TObservable, obj: TObservable) => boolean ): IReactionDisposer { const query = queryString.parse(window.location.search); // query -> observable for (const propName of Object.keys(queryNames) as [keyof TObservable]) { const queryName = queryNames[propName]; const value = query[queryName as string]; if (value == null) continue; if (Array.isArray(value)) { const allNum = value.all(v => Number.isFinite(Number(v))); const ar = allNum ? value.map(v => Number(v)) : value; observable[propName] = ar as any; } else { const v = Number.isFinite(Number(value)) ? Number(value) : value; observable[propName] = v as any; } } const disposer = autorun(() => { editQuery(query => { for (const propName of Object.keys(queryNames) as [keyof TObservable]) { const queryName = queryNames[propName]; const newValue = observable[propName]; if (shouldInclude && !shouldInclude(propName, observable)) { query[queryName] = null; continue; } if (newValue == null) query[queryName] = null; else if (typeof newValue === 'boolean') query[queryName] = String(Number(newValue)); else query[queryName] = String(newValue); // console.log('updated', { propName: propName, queryName: queryName, newValue: newValue }); } }) }); return disposer; } type NoticeType = 'info' | 'success' | 'error' | 'warning' | 'loading'; export class Message { private key: string; private hideFunc: MessageType; private duration: number | null; constructor(private text: string, private type: NoticeType = 'loading', private suffix: string = "") { this.key = randomId(); if (type == 'loading') this.duration = 0; // loading stays open until changed else this.duration = null; // others disappear automatically this.update(); } private update() { this.hideFunc = message.open({ content: this.text + this.suffix, key: this.key, type: this.type, duration: this.duration, }); } hide() { this.hideFunc(); } setLoading(text?: string, suffix?: string) { if (text) this.text = text; if (suffix) this.suffix = suffix; this.type = 'loading'; this.duration = 0; this.update(); } setSuccess(text?: string, suffix?: string) { if (text) this.text = text; if (suffix) this.suffix = suffix; this.type = 'success'; this.duration = 2.5; this.update(); } setError(text?: string, suffix?: string) { if (text) this.text = text; if (suffix) this.suffix = suffix; this.type = 'error'; this.duration = 2.5; this.update(); } } /** * Scroll the main content region */ export function scrollToTop(): void { const mainLayout = document.getElementById('mainLayout'); if (!mainLayout) return; mainLayout.scrollTo({ behavior: 'smooth', left: 0, top: 0 }); } /** * Scroll the main content region to the target element (which is found by the given id) */ export function scrollTo(targetId: string, anchor: 'start' | 'end' | 'center' = 'center', offset?: number): void { const mainLayout = document.getElementById('mainLayout'); if (!mainLayout) return; const target = document.getElementById(targetId); if (!target) return; const rect = target.getBoundingClientRect(); let top = 0; switch (anchor) { case 'start': top = rect.top; break; case 'center': top = (rect.top + rect.bottom) / 2; break; case 'end': top = rect.bottom; break; } mainLayout.scrollTo({ behavior: 'smooth', top: target.getBoundingClientRect().top + mainLayout.scrollTop + (offset ?? 0) }); } // See: https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings export function decodeBase64(base64: string) { const data = atob(base64); const length = data.length; const bytes = new Uint8Array(length); for (let i = 0; i < length; i++) bytes[i] = data.charCodeAt(i); const decoder = new TextDecoder(); // default is utf-8 return decoder.decode(bytes); }
the_stack
import * as assert from "assert"; import * as fs from "fs"; import * as path from "path"; import * as ts from "typescript"; import { Type, TypeParam, Comment, Field, Class, Struct, TypeDef, Function, Variable } from "./types"; // Get files to build overrides from const publicOverridesDir = path.join(__dirname, "..", "overrides"); const filePaths = fs.readdirSync(publicOverridesDir).map((fileName) => path.join(publicOverridesDir, fileName)); // Additional internal overrides const additionalOverridesDir = process.argv[2] && path.resolve(process.argv[2]); if(additionalOverridesDir) { filePaths.push(...fs.readdirSync(additionalOverridesDir).map((fileName) => path.join(additionalOverridesDir, fileName))) } // Parse file into AST const program = ts.createProgram(filePaths, { noResolve: true, target: ts.ScriptTarget.Latest, }); const keywordTypes = new Set<ts.SyntaxKind>([ ts.SyntaxKind.NeverKeyword, ts.SyntaxKind.VoidKeyword, ts.SyntaxKind.NullKeyword, ts.SyntaxKind.UndefinedKeyword, ts.SyntaxKind.BooleanKeyword, ts.SyntaxKind.NumberKeyword, ts.SyntaxKind.StringKeyword, ts.SyntaxKind.AnyKeyword, ts.SyntaxKind.UnknownKeyword, ]); const declarations: Record<string, Class | Struct | TypeDef | Function | Variable> = {}; for (const filePath of filePaths) { const sourceFile = program.getSourceFile(filePath); assert.ok(sourceFile); function getPos(pos: number): string { assert.ok(sourceFile); const mapped = sourceFile.getLineAndCharacterOfPosition(pos); return `${filePath}:${mapped.line + 1}:${mapped.character + 1}`; } function convertType(type?: ts.TypeNode): Type { if (type === undefined) { return { name: "any" }; } else if (keywordTypes.has(type.kind)) { return { name: type.getText(sourceFile) }; } else if (ts.isLiteralTypeNode(type)) { return { name: type.literal.getText(sourceFile) }; } else if (ts.isTypeReferenceNode(type)) { return { name: type.typeName.getText(sourceFile), args: type.typeArguments?.map(convertType), }; } else if (ts.isArrayTypeNode(type)) { return { name: "[]", args: [convertType(type.elementType)], }; } else if (ts.isUnionTypeNode(type)) { return { name: "|", args: type.types.map(convertType), }; } else if (ts.isTupleTypeNode(type)) { return { name: "()", params: type.elements.map(convertTupleMember), }; } else if (ts.isFunctionTypeNode(type)) { const params = type.parameters.map(convertParameter); const returns = convertType(type.type); return { params, returns }; } else if (ts.isTypeQueryNode(type)) { return { name: "typeof", args: [{ name: type.exprName.getText(sourceFile) }], }; } else if (ts.isTypeOperatorNode(type) && type.operator === ts.SyntaxKind.KeyOfKeyword) { return { name: "keyof", args: [{ name: type.type.getText(sourceFile) }], }; } else if (ts.isTypeLiteralNode(type)) { return { members: type.members.map(convertMember), }; } else if (ts.isIndexedAccessTypeNode(type)) { const objectType = convertType(type.objectType); objectType.index = convertType(type.indexType); return objectType; } else if (ts.isParenthesizedTypeNode(type)) { return convertType(type.type); } throw new TypeError(`unrecognised type at ${getPos(type.pos)}: ${type.getText(sourceFile)}`); } function convertTupleMember(node: ts.TypeNode | ts.NamedTupleMember): Field { if (ts.isNamedTupleMember(node)) { return { name: node.name.getText(sourceFile), type: convertType(node.type), }; } else { return { name: "", type: convertType(node) }; } } function convertTypeParams(nodes?: ts.NodeArray<ts.TypeParameterDeclaration>): TypeParam[] | undefined { return nodes?.map((node) => ({ name: node.name.getText(sourceFile), constraint: node.constraint && convertType(node.constraint), default: node.default && convertType(node.default), })); } function convertCommentText(text?: string | ts.NodeArray<ts.JSDocText | ts.JSDocLink>): string | undefined { if (text === undefined || typeof text === "string") { return text?.toString(); } else { return text.map((part) => part.text).join(" "); } } function convertComment(node: ts.Node): Comment | undefined { // @ts-expect-error jsDoc is marked as @internal const jsDocs = node.jsDoc as ts.JSDoc[]; if (jsDocs === undefined || jsDocs.length === 0) return undefined; const jsDoc = jsDocs[jsDocs.length - 1]; const comment: Comment = { text: convertCommentText(jsDoc.comment) ?? "" }; for (const tag of jsDoc.tags ?? []) { if (ts.isJSDocParameterTag(tag)) { comment.params ??= []; comment.params.push({ name: tag.name.getText(sourceFile), text: convertCommentText(tag.comment) ?? "", }); } else if (ts.isJSDocReturnTag(tag)) { comment.returns = convertCommentText(tag.comment); } } return comment; } function convertParameter(node: ts.ParameterDeclaration): Field { const name = node.name.getText(sourceFile); const type = convertType(node.type); if (node.dotDotDotToken) type.variadic = true; type.optional = node.questionToken && true; return { name, type }; } function convertConstructor(node: ts.ConstructorDeclaration): Field { const params = node.parameters.map(convertParameter); const type: Type = { params }; const comment = convertComment(node); return { name: "constructor", type, comment }; } function convertFieldMeta( node: | ts.MethodSignature | ts.MethodDeclaration | ts.PropertySignature | ts.PropertyDeclaration | ts.FunctionDeclaration | ts.ConstructSignatureDeclaration ): Partial<Field> { const comment = convertComment(node); const meta: Partial<Field> = { comment }; for (const modifier of node.modifiers ?? []) { if (modifier.kind == ts.SyntaxKind.StaticKeyword) { meta.static = true; } else if (modifier.kind == ts.SyntaxKind.ReadonlyKeyword) { meta.readonly = true; } } return meta; } function convertMethod( node: ts.MethodSignature | ts.MethodDeclaration | ts.FunctionDeclaration | ts.ConstructSignatureDeclaration ): Field { const defaultName = ts.isConstructSignatureDeclaration(node) ? "new" : ""; const name = node.name?.getText(sourceFile) ?? defaultName; const params = node.parameters.map(convertParameter); const returns = convertType(node.type); const optional = node.questionToken && true; const type: Type = { params, returns, optional }; const meta = convertFieldMeta(node); const typeparams = convertTypeParams(node.typeParameters); return { name, type, ...meta, typeparams }; } function convertProperty(node: ts.PropertySignature | ts.PropertyDeclaration): Field { const name = node.name.getText(sourceFile); const type = convertType(node.type); type.optional = node.questionToken && true; const meta = convertFieldMeta(node); return { name, type, ...meta }; } function convertIndexSignature(node: ts.IndexSignatureDeclaration): Field { assert.ok(node.parameters.length == 1); const name = `[${node.parameters[0].getText(sourceFile)}]`; const type = convertType(node.type); return { name, type }; } function convertMember(node: ts.Node): Field { if (ts.isConstructorDeclaration(node)) { return convertConstructor(node); } if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node) || ts.isConstructSignatureDeclaration(node)) { return convertMethod(node); } if (ts.isPropertySignature(node) || ts.isPropertyDeclaration(node)) { return convertProperty(node); } if (ts.isIndexSignatureDeclaration(node)) { return convertIndexSignature(node); } throw new TypeError(`unrecognised member at ${getPos(node.pos)}: ${node.getText(sourceFile)}`); } function convertHeritageClause(node: ts.HeritageClause): Type[] { return node.types.map((type) => ({ name: type.expression.getText(sourceFile), args: type.typeArguments && type.typeArguments.map(convertType), })); } function convertHeritageClauses(nodes?: ts.NodeArray<ts.HeritageClause>): Pick<Class, "extends" | "implements"> { const heritage: Pick<Class, "extends" | "implements"> = {}; for (const node of nodes ?? []) { if (node.token === ts.SyntaxKind.ExtendsKeyword) { heritage.extends ??= []; heritage.extends.push(...convertHeritageClause(node)); } else if (node.token === ts.SyntaxKind.ImplementsKeyword) { heritage.implements ??= []; heritage.implements.push(...convertHeritageClause(node)); } } return heritage; } function convertClass(node: ts.ClassDeclaration): Class { assert.ok(node.name); const name = node.name.escapedText.toString(); const members = node.members.map(convertMember); const typeparams = convertTypeParams(node.typeParameters); const heritage = convertHeritageClauses(node.heritageClauses); const comment = convertComment(node); return { kind: "class", name, members, typeparams, ...heritage, comment, }; } function convertStruct(node: ts.InterfaceDeclaration): Struct { const name = node.name.escapedText.toString(); const members = node.members.map(convertMember); const typeparams = convertTypeParams(node.typeParameters); const heritage = convertHeritageClauses(node.heritageClauses); const comment = convertComment(node); return { kind: "struct", name, members, typeparams, extends: heritage.extends, comment, }; } function convertTypeDef(node: ts.TypeAliasDeclaration): TypeDef { const name = node.name.escapedText.toString(); const type = convertType(node.type); const typeparams = convertTypeParams(node.typeParameters); const comment = convertComment(node); return { kind: "typedef", name, type, typeparams, comment, }; } function convertFunction(node: ts.FunctionDeclaration): Function { const { name, type, typeparams, comment } = convertMethod(node); return { kind: "function", name, type, typeparams, comment, }; } function convertVariableDeclaration(node: ts.VariableDeclaration): Variable { const name = node.name.getText(sourceFile); const type = convertType(node.type); const comment = convertComment(node); return { kind: "variable", name, type, comment, }; } function convertVariable(node: ts.VariableStatement): Variable[] { return node.declarationList.declarations.map(convertVariableDeclaration); } function convertStatement(node: ts.Statement): (Class | Struct | TypeDef | Function | Variable)[] { if (ts.isClassDeclaration(node)) { return [convertClass(node)]; } else if (ts.isInterfaceDeclaration(node)) { return [convertStruct(node)]; } else if (ts.isTypeAliasDeclaration(node)) { return [convertTypeDef(node)]; } else if (ts.isFunctionDeclaration(node)) { return [convertFunction(node)]; } else if (ts.isVariableStatement(node)) { return convertVariable(node); } throw new TypeError(`unrecognised statement at ${getPos(node.pos)}: ${node.getText(sourceFile)}`); } for (const statement of sourceFile.statements) { if (ts.isExportDeclaration(statement)) { // Ignore "export {}" at the end of files, we use this so TypeScript doesn't think // the override files are lib files causing name collisions continue; } const nodes = convertStatement(statement); for (const node of nodes) { let name = node.name; let number = 2; while (name in declarations) name = `${node.name}${number++}`; declarations[name] = node; } } } fs.writeFileSync("overrides.json", JSON.stringify(declarations, null, 2), "utf8");
the_stack
let _lastObjectUID = 0; function objectGetMoney(obj: Obj): number { const MONEY_PID = 41 for(var i = 0; i < obj.inventory.length; i++) { if(obj.inventory[i].pid === MONEY_PID) { return obj.inventory[i].amount } } return 0 } function objectSingleAnim(obj: Obj, reversed?: boolean, callback?: () => void): void { if(reversed) obj.frame = imageInfo[obj.art].numFrames - 1 else obj.frame = 0 obj.lastFrameTime = 0 obj.anim = reversed ? "reverse" : "single" obj.animCallback = callback || (() => { obj.anim = null }) } function canUseObject(obj: Obj, source?: Obj): boolean { if(obj._script !== undefined && obj._script.use_p_proc !== undefined) return true else if(obj.type === "item" || obj.type === "scenery") if(objectIsDoor(obj) || objectIsStairs(obj) || objectIsLadder(obj)) return true else return (obj.pro.extra.actionFlags & 8) != 0 return false } function objectIsDoor(obj: Obj): boolean { return (obj.type === "scenery" && obj.pro.extra.subType === 0) // SCENERY_DOOR } function objectIsStairs(obj: Obj): boolean { return (obj.type === "scenery" && obj.pro.extra.subType === 1) // SCENERY_STAIRS } function objectIsLadder(obj: Obj): boolean { return (obj.type === "scenery" && (obj.pro.extra.subType === 3 || // SCENERY_LADDER_BOTTOM obj.pro.extra.subType === 4)) // SCENERY_LADDER_TOP } function objectIsContainer(obj: Obj): boolean { return (obj.type === "item" && obj.pro.extra.subType === 1) // SUBTYPE_CONTAINER } function objectIsWeapon(obj: any): boolean { if(obj === undefined || obj === null) return false //return obj.type === "item" && obj.pro.extra.subType === 3 // weapon subtype return obj.weapon !== undefined } function objectIsExplosive(obj: Obj): boolean { return (obj.pid === 85 /* Plastic Explosives */ || obj.pid === 51 /* Dynamite */) } function objectFindItemIndex(obj: Obj, item: Obj): number { for(var i = 0; i < obj.inventory.length; i++) { if(obj.inventory[i].pid === item.pid) return i } return -1 } function cloneItem(item: Obj): Obj { return Object.assign({}, item); } function objectSwapItem(a: Obj, item: Obj, b: Obj, amount: number) { // swap item from a -> b if(amount === 0) return var idx = objectFindItemIndex(a, item) if(idx === -1) throw "item (" + item + ") does not exist in a" if(amount !== undefined && amount < item.amount) { // just deduct amount from a and give amount to b item.amount -= amount b.addInventoryItem(cloneItem(item), amount) } else { // just swap them a.inventory.splice(idx, 1) b.addInventoryItem(item, amount || 1) } } function objectGetDamageType(obj: any): string { // TODO: any (where does dmgType go? WeaponObj?) if(obj.dmgType !== undefined) return obj.dmgType throw "no damage type for obj: " + obj } function objectExplode(obj: Obj, source: Obj, minDmg: number, maxDmg: number): void { var damage = maxDmg var explosion = createObjectWithPID(makePID(5 /* misc */, 14 /* Explosion */), -1) explosion.position.x = obj.position.x explosion.position.y = obj.position.y; (<any>obj).dmgType = "explosion" // TODO: any (WeaponObj?) lazyLoadImage(explosion.art, function() { gMap.addObject(explosion) console.log("adding explosion") objectSingleAnim(explosion, false, function() { gMap.destroyObject(explosion) // damage critters in a radius var hexes = hexesInRadius(obj.position, 8 /* explosion radius */) // TODO: radius for(var i = 0; i < hexes.length; i++) { var objs = objectsAtPosition(hexes[i]) for(var j = 0; j < objs.length; j++) { if(objs[j].type === "critter") console.log("todo: damage", (<Critter>objs[j]).name) Scripting.damage(objs[j], obj, obj /*source*/, damage) } } // remove explosive gMap.destroyObject(obj) }) }) } function useExplosive(obj: Obj, source: Critter): void { if(source.isPlayer !== true) return // ? var mins, secs while(true) { var time = prompt("Time to detonate?", "1:00") if(time === null) return // cancel var s = time.split(':') if(s.length !== 2) continue mins = parseInt(s[0]) secs = parseInt(s[1]) if(isNaN(mins) || isNaN(secs)) continue break } // TODO: skill rolls var ticks = (mins*60*10) + secs*10 // game ticks until detonation console.log("arming explosive for " + ticks + " ticks") Scripting.timeEventList.push({ticks: ticks, obj: null, userdata: null, fn: function() { // explode! // TODO: explosion damage calculations objectExplode(obj, source, 10 /* min dmg */, 25 /* max dmg */) }}) } // Set the object (door/container) open/closed; returns true if possible, false if not (e.g. locked) function setObjectOpen(obj: Obj, open: boolean, loot: boolean=true, signalEvent: boolean=true): boolean { if(!objectIsDoor(obj) && !objectIsContainer(obj)) return false; // Open/closable doors/containers // TODO: Door/Container subclasses if(obj.locked) return false; obj.open = open; if(signalEvent) { Events.emit("objSetOpen", { obj, open }); Events.emit(open ? "objOpen" : "objClose", { obj }); } // Animate open/closed objectSingleAnim(obj, !open, function() { obj.anim = null if(loot && objectIsContainer(obj) && open) { // loot a container uiLoot(obj); } }); return true; } // Toggle the object (door/container) open/closed; returns true if possible, false if not (e.g. locked) function toggleObjectOpen(obj: Obj, loot: boolean=true, signalEvent: boolean=true): boolean { return setObjectOpen(obj, !obj.open, loot, signalEvent); } // Returns whether or not the object was used function useObject(obj: Obj, source?: Critter, useScript?: boolean): boolean { if(canUseObject(obj, source) === false) { console.log("can't use object") return false } if(useScript !== false && obj._script && obj._script.use_p_proc !== undefined) { if(source === undefined) source = player if(Scripting.use(obj, source) === true) { console.log("useObject: overriden") return true // script overrided us } } else if(obj.script !== undefined && !obj._script) console.log("object used has script but is not loaded: " + obj.script) if(objectIsExplosive(obj)) { useExplosive(obj, source) return true } if(objectIsDoor(obj) || objectIsContainer(obj)) { toggleObjectOpen(obj, true, true); } else if(objectIsStairs(obj)) { var destTile = fromTileNum(obj.extra.destination & 0xffff) var destElev = ((obj.extra.destination >> 28) & 0xf) >> 1 if(obj.extra.destinationMap === -1 && obj.extra.destination !== -1) { // same map, new destination console.log("stairs: tile: " + destTile.x + ", " + destTile.y + ", elev: " + destElev) player.position = destTile gMap.changeElevation(destElev) } else { console.log("stairs -> " + obj.extra.destinationMap + " @ " + destTile.x + ", " + destTile.y + ", elev: " + destElev) gMap.loadMapByID(obj.extra.destinationMap, destTile, destElev) } } else if(objectIsLadder(obj)) { var isTop = (obj.pro.extra.subType === 4) var level = isTop ? currentElevation + 1 : currentElevation - 1 var destTile = fromTileNum(obj.extra.destination & 0xffff) // TODO: destination also supposedly contains elevation and map console.log("ladder (" + (isTop ? "top" : "bottom") + " -> level " + level + ")") player.position = destTile gMap.changeElevation(level) } else objectSingleAnim(obj) gMap.updateMap() return true } function objectFindIndex(obj: Obj): number { return gMap.getObjects().findIndex(object => object === obj); } function objectZCompare(a: Obj, b: Obj): number { var aY = a.position.y var bY = b.position.y var aX = a.position.x var bX = b.position.x if(aY === bY) { if(aX < bX) return -1 else if(aX > bX) return 1 else if(aX === bX) { if(a.type === "wall") return -1 else if(b.type === "wall") return 1 else return 0 } } else if(aY < bY) return -1 else if(aY > bY) return 1 throw "unreachable" } function objectZOrder(obj: Obj, index: number): void { var oldIdx = (index !== undefined) ? index : objectFindIndex(obj) if(oldIdx === -1) { console.log("objectZOrder: no such object...") return } // TOOD: mutable/potentially unsafe usage of getObjects var objects = gMap.getObjects() objects.splice(oldIdx, 1) // remove the object... var inserted = false for(var i = 0; i < objects.length; i++) { var zc = objectZCompare(obj, objects[i]) if(zc === -1) { objects.splice(i, 0, obj) // insert at new index inserted = true break } } if(!inserted) // couldn't find a spot, just add it in objects.push(obj) } function zsort(objects: Obj[]): void { objects.sort(objectZCompare) } function useElevator(): void { // Player walked into an elevator // // We search for the Elevator Stub (Scenery PID 1293) // in the range of 11. The original engine uses a square // of size 11x11, but we don't do that. console.log("[elevator]") var center = player.position var hexes = hexesInRadius(center, 11) var elevatorStub = null for(var i = 0; i < hexes.length; i++) { var objs = objectsAtPosition(hexes[i]) for(var j = 0; j < objs.length; j++) { var obj = objs[j] if(obj.type === "scenery" && obj.pidID === 1293) { console.log("elevator stub @ " + hexes[i].x + ", " + hexes[i].y) elevatorStub = obj break } } } if(elevatorStub === null) throw "couldn't find elevator stub near " + center.x + ", " + center.y console.log("elevator type: " + elevatorStub.extra.type + ", " + "level: " + elevatorStub.extra.level) var elevator = getElevator(elevatorStub.extra.type) if(!elevator) throw "no elevator: " + elevatorStub.extra.type uiElevator(elevator) } interface SerializedObj { uid: number; pid: number; pidID: number; type: string; pro: any; flags: number; art: string; frmPID: number; orientation: number; visible: boolean; extra: any; script: string; _script: Scripting.SerializedScript|undefined; name: string; subtype: string; invArt: string; frame: number; amount: number; position: Point; inventory: SerializedObj[]; lightRadius: number; lightIntensity: number; } class Obj { uid: number = -1; // Unique ID given to all objects, to distinguish objects with the same PIDs pid: number; // PID (Prototype IDentifier) pidID: number; // ID (not type) part of the PID type: string = null; // TODO: enum // Type of object (critter, item, ...) pro: any = null; // TODO: pro ref // PRO Object flags: number = 0; // Flags from PRO; may be overriden by map objects art: string; // TODO: Path // Art path frmPID: number = null; // Art FID orientation: number = null; // Direction the object is facing visible: boolean = true; // Is the object visible? open: boolean = false; // Is the object open? (Mainly for doors) locked: boolean = false; // Is the object locked? (Mainly for doors) extra: any; // TODO script: string; // Script name _script: Scripting.Script|undefined; // Live script object // TOOD: unify these name: string; // = "<unnamed obj>"; // Only for some critters at the moment. subtype: string; // Some objects, like items and scenery, have subtypes invArt: string; // Art path used for in-inventory image anim: any = null; // Current animation (TODO: Is this only a string? It should probably be an enum.) animCallback: any = null; // Callback when current animation is finished playing frame: number = 0; // Animation frame index lastFrameTime: number = 0; // Time since last animation frame played // Frame shift/offset // For static animations, this is just null (effectively just the frame offset as declared in the .FRM), // but for walk/run animations it is the sum of frame offsets between the last action frame // and the current frame. shift: Point = null; // Outline color, if outlined outline: string|null = null; amount: number = 1; // TODO: Where does this belong? Items and misc seem to have it, or is Money an Item? position: Point = {x: -1, y: -1}; inventory: Obj[] = []; // TODO: verify lightRadius: number = 0; lightIntensity: number = 655; static fromPID(pid: number, sid?: number): Obj { return Obj.fromPID_(new Obj(), pid, sid) } static fromPID_<T extends Obj>(obj: T, pid: number, sid?: number): T { console.log(`fromPID: pid=${pid}, sid=${sid}`) var pidType = (pid >> 24) & 0xff var pidID = pid & 0xffff var pro: any = loadPRO(pid, pidID) // TODO: any obj.type = getPROTypeName(pidType) obj.pid = pid obj.pro = pro obj.flags = obj.pro.flags // TODO: Subclasses if(pidType == 0) { // item obj.subtype = getPROSubTypeName(pro.extra.subtype) obj.name = getMessage("pro_item", pro.textID) var invPID = pro.extra.invFRM & 0xffff console.log(`invPID: ${invPID}, pid=${pid}`) if(invPID !== 0xffff) obj.invArt = "art/inven/" + getLstId("art/inven/inven", invPID).split('.')[0] } if(obj.pro !== undefined) obj.art = lookupArt(makePID(obj.pro.frmType, obj.pro.frmPID)) else obj.art = "art/items/RESERVED" obj.init() obj.loadScript(sid) return obj } static fromMapObject(mobj: any, deserializing: boolean=false): Obj { return Obj.fromMapObject_(new Obj(), mobj, deserializing) } static fromMapObject_<T extends Obj>(obj: T, mobj: any, deserializing: boolean=false): T { // Load an Obj from a map object //console.log("fromMapObject: %o", mobj) if(mobj.uid) obj.uid = mobj.uid; obj.pid = mobj.pid obj.pidID = mobj.pidID obj.frmPID = mobj.frmPID obj.orientation = mobj.orientation if(obj.type === null) obj.type = mobj.type obj.art = mobj.art obj.position = mobj.position obj.lightRadius = mobj.lightRadius obj.lightIntensity = mobj.lightIntensity obj.subtype = mobj.subtype obj.amount = mobj.amount obj.inventory = mobj.inventory obj.script = mobj.script obj.extra = mobj.extra obj.pro = mobj.pro || loadPRO(obj.pid, obj.pidID) obj.flags = mobj.flags // NOTE: Tested with two objects in Mapper, map object flags seem to inherit PROs already and should thus use them // etc? TODO: check this! obj.init() if(deserializing) { obj.inventory = mobj.inventory.map((obj: SerializedObj) => deserializeObj(obj)) obj.script = mobj.script if(mobj._script) obj._script = Scripting.deserializeScript(mobj._script) // TODO: Should we load the script if mobj._script does not exist? } else if(Config.engine.doLoadScripts) obj.loadScript() return obj } init() { if(this.uid === -1) this.uid = _lastObjectUID++; //console.log("init: %o", this) if(this.inventory !== undefined) // containers and critters this.inventory = this.inventory.map(obj => objFromMapObject(obj)) } loadScript(sid:number=-1): void { var scriptName = null if(sid >= 0) scriptName = lookupScriptName(sid) else if(this.script) scriptName = this.script else if(this.pro) { if(this.pro.extra !== undefined && this.pro.extra.scriptID >= 0) { // scriptName = lookupScriptName(this.pro.extra.scriptID & 0xffff) console.warn(`PRO says sid is ${this.pro.extra.scriptID & 0xffff} (${scriptName}), but we're not ascribing it one (test)`) } else if(this.pro.scriptID >= 0) { // scriptName = lookupScriptName(this.pro.scriptID & 0xffff) console.warn(`PRO says sid is ${this.pro.extra.scriptID & 0xffff} (${scriptName}), but we're not ascribing it one (test)`) } } if(scriptName != null) { if(Config.engine.doLogScriptLoads) console.log("loadScript: loading %s (sid=%d)", scriptName, sid) // console.trace(); var script = Scripting.loadScript(scriptName) if(!script) { console.log("loadScript: load script failed for %s (sid=%d)", scriptName, sid) } else { this.script = scriptName this._script = script Scripting.initScript(this._script, this) } } } enterMap(): void { // TODO: do we updateMap? // TODO: is this correct? // TODO: map objects should be a registry, and this should be activated when objects // are added in. @important if(this._script) Scripting.objectEnterMap(this, currentElevation, gMap.mapID) } setAmount(amount: number): Obj { this.amount = amount return this } // Moves the object; returns `true` if successfully moved, // or `false` if interrupted (such as by an exit grid). move(position: Point, curIdx?: number, signalEvents: boolean=true): boolean { this.position = position if(signalEvents) Events.emit("objMove", { obj: this, position }) // rebuild the lightmap if(Config.engine.doFloorLighting) Lightmap.rebuildLight() // give us a new z-order if(Config.engine.doZOrder !== false) objectZOrder(this, curIdx) return true } updateAnim(): void { if(!this.anim) return var time = heart.timer.getTime() var fps = imageInfo[this.art].fps if(fps === 0) fps = 10 // XXX: ? if(time - this.lastFrameTime >= 1000/fps) { if(this.anim === "reverse") this.frame-- else this.frame++ this.lastFrameTime = time if(this.frame === -1 || this.frame === imageInfo[this.art].numFrames) { // animation is done if(this.anim === "reverse") this.frame++ else this.frame-- if(this.animCallback) this.animCallback() } } } blocks(): boolean { // TODO: We could make use of subclass polymorphism to reduce the cases here // NOTE: This may be overloaded in subclasses if(this.type === "misc") return false if(!this.pro) return true // XXX: ? if(this.subtype === "door") return !this.open if(this.visible === false) return false return !(this.pro.flags & 0x00000010 /* NoBlock */) } inAnim(): boolean { return !!this.animCallback // TODO: find a better way } // Clear any animation the object has clearAnim(): void { this.frame = 0 this.animCallback = null this.anim = null this.shift = null } // Are two objects approximately (not necessarily strictly) equal? approxEq(obj: Obj) { return (this.pid === obj.pid) } clone(): Obj { // TODO: check this and probably fix it // If we have a script, temporarily remove it so that we may clone the // object without the script, and then re-load it for a new instance. if(this._script) { console.log("cloning an object with a script: %o", this) var _script = this._script this._script = null var obj = deepClone(this) this._script = _script obj.loadScript() // load new copy of the script return obj } // no script, just deep clone the object return deepClone(this) } addInventoryItem(item: Obj, count: number=1): void { for(var i = 0; i < this.inventory.length; i++) { if(this.inventory[i].approxEq(item)) { this.inventory[i].amount += count return } } // no existing item, add new inventory object this.inventory.push(item.clone().setAmount(count)) } getMessageCategory(): string { const categories: { [category: string]: string } = { "item": "pro_item", "critter": "pro_crit", "scenery": "pro_scen", "wall": "pro_wall", "misc": "pro_misc" }; return categories[this.type]; } getDescription(): string { if(!this.pro) return null return getMessage(this.getMessageCategory(), this.pro.textID + 1) || null } // TODO: override this for subclasses serialize(): SerializedObj { return { uid: this.uid, pid: this.pid, pidID: this.pidID, type: this.type, pro: this.pro, // XXX: if pro changes in the future, this should be cloned flags: this.flags, art: this.art, frmPID: this.frmPID, orientation: this.orientation, visible: this.visible, extra: this.extra, script: this.script, _script: this._script ? this._script._serialize() : null, name: this.name, subtype: this.subtype, invArt: this.invArt, frame: this.frame, amount: this.amount, position: {x: this.position.x, y: this.position.y}, inventory: this.inventory.map(obj => obj.serialize()), lightRadius: this.lightRadius, lightIntensity: this.lightIntensity } } } class Item extends Obj { type = "item"; static fromPID(pid: number, sid?: number): Item { return Obj.fromPID_(new Item(), pid, sid) } static fromMapObject(mobj: any, deserializing: boolean=false): Item { return Obj.fromMapObject_(new Item(), mobj, deserializing) } init() { super.init() // load item inventory art if(this.pro === null) return this.name = getMessage("pro_item", this.pro.textID) var invPID = this.pro.extra.invFRM & 0xffff if(invPID !== 0xffff) this.invArt = "art/inven/" + getLstId("art/inven/inven", invPID).split('.')[0] } } class WeaponObj extends Item { weapon?: Weapon = null; static fromPID(pid: number, sid?: number): WeaponObj { return Obj.fromPID_(new WeaponObj(), pid, sid) } static fromMapObject(mobj: any, deserializing: boolean=false): WeaponObj { return Obj.fromMapObject_(new WeaponObj(), mobj, deserializing) } init() { super.init() // TODO: Weapon initialization //console.log("Weapon init") this.weapon = new Weapon(this) } } class Scenery extends Obj { type = "scenery"; static fromPID(pid: number, sid?: number): Scenery { return Obj.fromPID_(new Scenery(), pid, sid) } static fromMapObject(mobj: any, deserializing: boolean=false): Scenery { return Obj.fromMapObject_(new Scenery(), mobj, deserializing) } init() { super.init(); //console.log("Scenery init") if(!this.pro) return; const subtypeMap: { [subtype: number]: string } = { 0: "door", 1: "stairs", 2: "elevator", 3: "ladder", 4: "ladder", 5: "generic" }; this.subtype = subtypeMap[this.pro.extra.subType]; } } class Door extends Scenery { static fromPID(pid: number, sid?: number): Door { return Obj.fromPID_(new Door(), pid, sid) } static fromMapObject(mobj: any, deserializing: boolean=false): Door { return Obj.fromMapObject_(new Door(), mobj, deserializing) } init() { super.init() //console.log("Door init") } } // Creates an object of a relevant type from a Prototype ID and an optional Script ID function createObjectWithPID(pid: number, sid?: number) { var pidType = (pid >> 24) & 0xff if(pidType == 1) // critter return Critter.fromPID(pid, sid) else if(pidType == 0) { // item var pro = loadPRO(pid, pid & 0xffff) if(pro && pro.extra && pro.extra.subType == 3) return WeaponObj.fromPID(pid, sid) else return Item.fromPID(pid, sid) } else if(pidType == 2) { // scenery var pro = loadPRO(pid, pid & 0xffff) if(pro && pro.extra && pro.extra.subType == 0) return Door.fromPID(pid, sid) else return Scenery.fromPID(pid, sid) } else return Obj.fromPID(pid, sid) } function objFromMapObject(mobj: any, deserializing: boolean=false) { var pid = mobj.pid var pidType = (pid >> 24) & 0xff if(pidType == 1) // critter return Critter.fromMapObject(mobj, deserializing) else if(pidType == 0) { // item var pro = mobj.pro || loadPRO(pid, pid & 0xffff) if(pro && pro.extra && pro.extra.subType == 3) return WeaponObj.fromMapObject(mobj, deserializing) else return Item.fromMapObject(mobj, deserializing) } else if(pidType == 2) { // scenery var pro = mobj.pro || loadPRO(pid, pid & 0xffff) if(pro && pro.extra && pro.extra.subType == 0) return Door.fromMapObject(mobj, deserializing) else return Scenery.fromMapObject(mobj, deserializing) } else return Obj.fromMapObject(mobj, deserializing) } function deserializeObj(mobj: SerializedObj) { return objFromMapObject(mobj, true) }
the_stack
import { Component, INotifyPropertyChanged, Property, Complex, Collection, Internationalization, NotifyPropertyChanges, ModuleDeclaration } from '@syncfusion/ej2-base'; import { Browser, EmitType, remove, Event, EventHandler } from '@syncfusion/ej2-base'; import { DataManager } from '@syncfusion/ej2-data'; import { StockChartModel } from './stock-chart-model'; import { Chart, ZoomSettings, CrosshairSettings } from '../chart/chart'; import { ZoomSettingsModel, CrosshairSettingsModel } from '../chart/chart-model'; import { appendChildElement, redrawElement, titlePositionX, textElement } from '../common/utils/helper'; import { Axis } from '../chart/axis/axis'; import { Series } from '../chart/series/chart-series'; import { Size, Rect, TextOption, measureText, SvgRenderer } from '@syncfusion/ej2-svg-base'; import { Periods } from '../common/model/base'; import { IRangeSelectorRenderEventArgs, ITooltipRenderEventArgs, IMouseEventArgs, IPointEventArgs } from '../chart/model/chart-interface'; import { IAxisLabelRenderEventArgs, ISeriesRenderEventArgs, IZoomingEventArgs } from '../chart/model/chart-interface'; import { PeriodsModel } from '../common/model/base-model'; import { TooltipSettings } from '../common/model/base'; import { TooltipSettingsModel } from '../common/model/base-model'; import { calculateSize, getElement } from '../common/utils/helper'; import { RangeNavigator } from '../range-navigator/range-navigator'; import { getRangeValueXByPoint } from '../range-navigator/utils/helper'; import { PeriodSelector } from '../common/period-selector/period-selector'; import { CartesianChart } from './renderer/cartesian-chart'; import { RangeSelector } from './renderer/range-selector'; import { ToolBarSelector } from './renderer/toolbar-selector'; import { StockMargin, StockChartArea, StockChartAxis, StockChartRow, StockChartIndexes, StockEventsSettings, IStockLegendRenderEventArgs, IStockLegendClickEventArgs } from './model/base'; import { StockSeries, IStockChartEventArgs, StockChartIndicator, StockChartBorder, IRangeChangeEventArgs } from './model/base'; import { StockChartAnnotationSettings, IStockEventRenderArgs, } from './model/base'; import { StockChartAnnotationSettingsModel } from './model/base-model'; import { StockChartFont } from './model/base'; import { StockSeriesModel, StockChartIndicatorModel, StockChartAxisModel, StockChartRowModel } from './model/base-model'; import { StockChartIndexesModel, StockChartFontModel, StockChartAreaModel, StockEventsSettingsModel } from './model/base-model'; import { StockChartBorderModel, StockMarginModel } from './model/base-model'; import { ChartSeriesType, TrendlineTypes, TechnicalIndicators, ChartTheme, SelectionMode } from '../chart/utils/enum'; import { ExportType, Alignment } from '../common/utils/enum'; import { getSeriesColor, getThemeColor } from '../common/model/theme'; import { StockEvents } from './renderer/stock-events'; import { IThemeStyle } from '../chart/model/chart-interface'; import { StockChartLegendSettingsModel } from './legend/legend-model'; import { StockLegend, StockChartLegendSettings } from './legend/legend'; import { SeriesModel } from './index'; /** * Stock Chart * @public */ @NotifyPropertyChanges export class StockChart extends Component<HTMLElement> implements INotifyPropertyChanged { //Module Declaration of Stockchart. /** * `legendModule` is used to manipulate and add legend to the Stockchart. */ public stockLegendModule: StockLegend; /** * The width of the stockChart as a string accepts input as both like '100px' or '100%'. * If specified as '100%, stockChart renders to the full width of its parent element. * * @default null */ @Property(null) public width: string; /** * The height of the stockChart as a string accepts input both as '100px' or '100%'. * If specified as '100%, stockChart renders to the full height of its parent element. * * @default null */ @Property(null) public height: string; /** * Specifies the DataSource for the stockChart. It can be an array of JSON objects or an instance of DataManager. * ```html * <div id='financial'></div> * ``` * ```typescript * let dataManager: DataManager = new DataManager({ * url: 'http://mvc.syncfusion.com/Services/Northwnd.svc/Tasks/' * }); * let query: Query = new Query().take(50).where('Estimate', 'greaterThan', 0, false); * let financial: stockChart = new stockChart({ * ... * dataSource:dataManager, * series: [{ * xName: 'Id', * yName: 'Estimate', * query: query * }], * ... * }); * financial.appendTo('#financial'); * ``` * * @default '' */ @Property('') public dataSource: Object | DataManager; /** * Options to customize left, right, top and bottom margins of the stockChart. */ @Complex<StockMarginModel>({}, StockMargin) public margin: StockMarginModel; /** * Options for customizing the color and width of the stockChart border. */ @Complex<StockChartBorderModel>({ color: '#DDDDDD', width: 1 }, StockChartBorder) public border: StockChartBorderModel; /** * The background color of the stockChart that accepts value in hex and rgba as a valid CSS color string. * * @default null */ @Property(null) public background: string; /** * Specifies the theme for the stockChart. * * @default 'Material' */ @Property('Material') public theme: ChartTheme; /** * Options to configure the horizontal axis. */ @Complex<StockChartAxisModel>({ name: 'primaryXAxis', valueType: 'DateTime' }, StockChartAxis) public primaryXAxis: StockChartAxisModel; /** * Options for configuring the border and background of the stockChart area. */ @Complex<StockChartAreaModel>({ border: { color: null, width: 0.5 }, background: 'transparent' }, StockChartArea) public chartArea: StockChartAreaModel; /** * Options to configure the vertical axis. * * @complex {opposedPosition=true, labelPosition=AxisPosition.Outside} */ @Complex<StockChartAxisModel>({ name: 'primaryYAxis', opposedPosition: true, labelPosition: 'Inside' }, StockChartAxis) public primaryYAxis: StockChartAxisModel; /** * Options to split stockChart into multiple plotting areas horizontally. * Each object in the collection represents a plotting area in the stockChart. */ @Collection<StockChartRowModel>([{}], StockChartRow) public rows: StockChartRowModel[]; /** * Secondary axis collection for the stockChart. */ @Collection<StockChartAxisModel>([{ opposedPosition: true }], StockChartAxis) public axes: StockChartAxisModel[]; /** * The configuration for series in the stockChart. */ @Collection<StockSeriesModel>([], StockSeries) public series: StockSeriesModel[]; /** * The configuration for stock events in the stockChart. */ @Collection<StockEventsSettingsModel>([], StockEventsSettings) public stockEvents: StockEventsSettingsModel[]; /** * It specifies whether the stockChart should be render in transposed manner or not. * * @default false */ @Property(false) public isTransposed: boolean; /** * Title of the chart * * @default '' */ @Property('') public title: string; /** * Options for customizing the title of the Chart. */ @Complex<StockChartFontModel>({ size: '15px', fontWeight: '500', color: null, fontStyle: 'Normal', fontFamily: 'Segoe UI' }, StockChartFont) public titleStyle: StockChartFontModel; /** * Defines the collection of technical indicators, that are used in financial markets */ @Collection<StockChartIndicatorModel>([], StockChartIndicator) public indicators: StockChartIndicatorModel[]; /** * Options for customizing the tooltip of the chart. */ @Complex<TooltipSettingsModel>({ shared: true, enableMarker: false }, TooltipSettings) public tooltip: TooltipSettingsModel; /** * Options for customizing the crosshair of the chart. */ @Complex<CrosshairSettingsModel>({ dashArray: '5' }, CrosshairSettings) public crosshair: CrosshairSettingsModel; /** * Options for customizing the legend of the stockChart. */ @Complex<StockChartLegendSettingsModel>({}, StockChartLegendSettings) public legendSettings: StockChartLegendSettingsModel; /** * Options to enable the zooming feature in the chart. */ @Complex<ZoomSettingsModel>({}, ZoomSettings) public zoomSettings: ZoomSettingsModel; /** * It specifies whether the periodSelector to be rendered in financial chart * * @default true */ @Property(true) public enablePeriodSelector: boolean; /** * Custom Range * * @default true */ @Property(true) public enableCustomRange: boolean; /** * If set true, enables the animation in chart. * * @default false */ @Property(false) public isSelect: boolean; /** * It specifies whether the range navigator to be rendered in financial chart * * @default true */ @Property(true) public enableSelector: boolean; /** * To configure period selector options. */ @Collection<PeriodsModel>([], Periods) public periods: PeriodsModel[]; /** * The configuration for annotation in chart. */ @Collection<StockChartAnnotationSettingsModel>([{}], StockChartAnnotationSettings) public annotations: StockChartAnnotationSettingsModel[]; /** * Triggers before render the selector * * @event selectorRender * @deprecated */ @Event() public selectorRender: EmitType<IRangeSelectorRenderEventArgs>; /** * Triggers on hovering the stock chart. * * @event stockChartMouseMove * @blazorProperty 'OnStockChartMouseMove' */ @Event() public stockChartMouseMove: EmitType<IMouseEventArgs>; /** * Triggers when cursor leaves the chart. * * @event stockChartMouseLeave * @blazorProperty 'OnStockChartMouseLeave' */ @Event() public stockChartMouseLeave: EmitType<IMouseEventArgs>; /** * Triggers on mouse down. * * @event stockChartMouseDown * @blazorProperty 'OnStockChartMouseDown' */ @Event() public stockChartMouseDown: EmitType<IMouseEventArgs>; /** * Triggers on mouse up. * * @event stockChartMouseUp * @blazorProperty 'OnStockChartMouseUp' */ @Event() public stockChartMouseUp: EmitType<IMouseEventArgs>; /** * Triggers on clicking the stock chart. * * @event stockChartMouseClick * @blazorProperty 'OnStockChartMouseClick' */ @Event() public stockChartMouseClick: EmitType<IMouseEventArgs>; /** * Triggers on point click. * * @event pointClick * @blazorProperty 'OnPointClick' */ @Event() public pointClick: EmitType<IPointEventArgs>; /** * Triggers on point move. * * @event pointMove * @blazorProperty 'PointMoved' */ @Event() public pointMove: EmitType<IPointEventArgs>; /** * Triggers after the zoom selection is completed. * * @event onZooming */ @Event() public onZooming: EmitType<IZoomingEventArgs>; /** * Triggers before the legend is rendered. * * @event legendRender * @deprecated */ @Event() public legendRender: EmitType<IStockLegendRenderEventArgs>; /** * Triggers after click on legend * * @event legendClick */ @Event() public legendClick: EmitType<IStockLegendClickEventArgs>; /** * Specifies whether series or data point has to be selected. They are, * * none: Disables the selection. * * series: selects a series. * * point: selects a point. * * cluster: selects a cluster of point * * dragXY: selects points by dragging with respect to both horizontal and vertical axes * * dragX: selects points by dragging with respect to horizontal axis. * * dragY: selects points by dragging with respect to vertical axis. * * @default None */ @Property('None') public selectionMode: SelectionMode; /** * If set true, enables the multi selection in chart. It requires `selectionMode` to be `Point` | `Series` | or `Cluster`. * * @default false */ @Property(false) public isMultiSelect: boolean; /** * Triggers before the range navigator rendering * * @event load */ @Event() public load: EmitType<IStockChartEventArgs>; /** * Triggers after the range navigator rendering * * @event loaded * @blazorProperty 'Loaded' */ @Event() public loaded: EmitType<IStockChartEventArgs>; /** * Triggers if the range is changed * * @event rangeChange * @blazorProperty 'RangeChange' */ @Event() public rangeChange: EmitType<IRangeChangeEventArgs>; /** * Triggers before each axis label is rendered. * * @event axisLabelRender * @deprecated */ @Event() public axisLabelRender: EmitType<IAxisLabelRenderEventArgs>; /** * Triggers before the tooltip for series is rendered. * * @event tooltipRender * @deprecated */ @Event() public tooltipRender: EmitType<ITooltipRenderEventArgs>; /** * Triggers before the series is rendered. * * @event seriesRender * @deprecated */ @Event() public seriesRender: EmitType<ISeriesRenderEventArgs>; /** * Triggers before the series is rendered. * * @event stockEventRender * @deprecated */ @Event() public stockEventRender: EmitType<IStockEventRenderArgs>; /** * Specifies the point indexes to be selected while loading a chart. * It requires `selectionMode` to be `Point` | `Series` | or `Cluster`. * ```html * <div id='Chart'></div> * ``` * ```typescript * let chart: Chart = new Chart({ * ... * selectionMode: 'Point', * selectedDataIndexes: [ { series: 0, point: 1}, * { series: 2, point: 3} ], * ... * }); * chart.appendTo('#Chart'); * ``` * * @default [] */ @Collection<StockChartIndexesModel>([], StockChartIndexes) public selectedDataIndexes: StockChartIndexesModel[]; /** * It specifies the types of series in financial chart. */ @Property(['Line', 'Hilo', 'OHLC', 'Hollow Candle', 'Spline', 'Candle']) public seriesType: ChartSeriesType[]; /** * It specifies the types of indicators in financial chart. */ @Property(['EMA', 'TMA', 'SMA', 'Momentum', 'ATR', 'Accumulation Distribution', 'Bollinger Bands', 'MACD', 'Stochastic', 'RSI']) public indicatorType: TechnicalIndicators[]; /** * It specifies the types of Export types in financial chart. */ @Property(['PNG', 'JPEG', 'SVG', 'PDF', 'Print']) public exportType: ExportType[]; /** * It specifies the types of trendline types in financial chart. */ @Property(['Linear', 'Exponential', 'Polynomial', 'Logarithmic', 'Moving Average']) public trendlineType: TrendlineTypes[]; /** * Gets the current visible series of the Chart. * * @hidden */ public visibleSeries: Series[]; /** @private */ public startValue: number; /** @private */ public isSingleAxis: boolean = false; /** @private */ public endValue: number; /** @private */ public seriesXMax: number; /** @private */ public seriesXMin: number; /** @private */ public currentEnd: number; /** Overall SVG */ public mainObject: Element; /** @private */ public selectorObject: Element; /** @private */ public chartObject: Element; /** @private */ public svgObject: Element; /** @private */ public isTouch: boolean; /** @private */ public renderer: SvgRenderer; /** @private */ public animateSeries: boolean; /** @private */ public availableSize: Size; /** @private */ public titleSize: Size; /** @private */ public chartSize: Size; /** @private */ public intl: Internationalization; /** @private */ public isDoubleTap: boolean; /** @private */ private threshold: number; /** @private */ public isChartDrag: boolean; public resizeTo: number; /** @private */ public disableTrackTooltip: boolean; /** @private */ public startMove: boolean; /** @private */ public yAxisElements: Element; /** @private */ public themeStyle: IThemeStyle; /** @private */ public scrollElement: Element; private chartid: number = 57723; public tempSeriesType: ChartSeriesType[] = []; /** @private */ public chart: Chart; /** @private */ public rangeNavigator: RangeNavigator; /** @private */ public periodSelector: PeriodSelector; /** @private */ public cartesianChart: CartesianChart; /** @private */ public rangeSelector: RangeSelector; /** @private */ public toolbarSelector: ToolBarSelector; /** @private */ public stockEvent: StockEvents; /** private */ public zoomChange: boolean = false; /** @private */ public mouseDownX: number; /** @private */ public mouseDownY: number; /** @private */ public previousMouseMoveX: number; /** @private */ public previousMouseMoveY: number; /** @private */ public mouseDownXPoint: number; /** @private */ public mouseUpXPoint: number; /** @private */ public allowPan: boolean = false; /** @private */ public onPanning: boolean = false; /** @private */ public referenceXAxis: Axis; /** @private */ public mouseX: number; /** @private */ public mouseY: number; /** @private */ public indicatorElements: Element; /** @private */ public trendlinetriggered: boolean = true; /** @private */ public periodSelectorHeight: number; /** @private */ public toolbarHeight: number; /** @private */ public stockChartTheme: IThemeStyle; /** @private */ public initialRender: boolean = true; /** @private */ public rangeFound: boolean = false; /** @private */ public tempPeriods: PeriodsModel[] = []; /** @private */ public legend: StockLegend; /** @private */ public visibleSeriesCount: number; /** @private */ public redraw: boolean; /** @private */ public initialClipRect: Rect; /** @private */ public tempAvailableSize: Size; /** * Constructor for creating the widget * * @hidden */ constructor(options?: StockChartModel, element?: string | HTMLElement) { super(options, <HTMLElement | string>element); this.toolbarHeight = this.enablePeriodSelector ? (Browser.isDevice ? 56 : 42) : 0; } /** * Called internally if any of the property value changed. * * @private */ // eslint-disable-next-line public onPropertyChanged(newProp: StockChartModel, oldProp: StockChartModel): void { // on property changes for (const property of Object.keys(newProp)) { switch (property) { case 'series': this.render(); break; } } } /** * To change the range for chart */ public rangeChanged(updatedStart: number, updatedEnd: number): void { // manage chart refresh const chartElement: Element = document.getElementById(this.chartObject.id); if (chartElement) { while (chartElement.firstChild) { chartElement.removeChild(chartElement.firstChild); } } this.startValue = updatedStart; this.endValue = updatedEnd; this.cartesianChart.initializeChart(); this.periodSelector.datePicker.startDate = new Date(updatedStart); this.periodSelector.datePicker.endDate = new Date(updatedEnd); this.periodSelector.datePicker.dataBind(); } /** * Pre render for financial Chart */ protected preRender(): void { this.unWireEvents(); this.initPrivateVariable(); this.allowServerDataBinding = false; this.isProtectedOnChange = true; this.setCulture(); this.wireEvents(); } /** * Method to bind events for chart */ private unWireEvents(): void { /*! Find the Events type */ const startEvent: string = Browser.touchStartEvent; const moveEvent: string = Browser.touchMoveEvent; const stopEvent: string = Browser.touchEndEvent; const cancelEvent: string = Browser.isPointer ? 'pointerleave' : 'mouseleave'; /*! UnBind the Event handler */ EventHandler.remove(this.element, startEvent, this.stockChartOnMouseDown); EventHandler.remove(this.element, moveEvent, this.stockChartOnMouseMove); EventHandler.remove(this.element, stopEvent, this.stockChartMouseEnd); EventHandler.remove(this.element, 'click', this.stockChartOnMouseClick); EventHandler.remove(this.element, 'contextmenu', this.stockChartRightClick); EventHandler.remove(this.element, cancelEvent, this.stockChartOnMouseLeave); window.removeEventListener( (Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.stockChartResize ); } private wireEvents(): void { /*! Find the Events type */ const cancelEvent: string = Browser.isPointer ? 'pointerleave' : 'mouseleave'; /*! Bind the Event handler */ EventHandler.add(this.element, Browser.touchStartEvent, this.stockChartOnMouseDown, this); EventHandler.add(this.element, Browser.touchMoveEvent, this.stockChartOnMouseMove, this); EventHandler.add(this.element, Browser.touchEndEvent, this.stockChartMouseEnd, this); EventHandler.add(this.element, 'click', this.stockChartOnMouseClick, this); EventHandler.add(this.element, 'contextmenu', this.stockChartRightClick, this); EventHandler.add(this.element, cancelEvent, this.stockChartOnMouseLeave, this); window.addEventListener( (Browser.isTouch && ('orientation' in window && 'onorientationchange' in window)) ? 'orientationchange' : 'resize', this.stockChartResize.bind(this) ); this.setStyle(this.element); } private initPrivateVariable(): void { if (this.element.id === '') { const collection: number = document.getElementsByClassName('e-stockChart').length; this.element.id = 'stockChart_' + this.chartid + '_' + collection; } this.seriesXMax = null; this.seriesXMin = null; this.startValue = null; this.endValue = null; this.currentEnd = null; } /** * Method to set culture for chart */ private setCulture(): void { this.intl = new Internationalization(); } private storeDataSource(): void { for (let i: number = 0; i < this.series.length; i++) { const series: StockSeries = this.series[i] as StockSeries; this.tempSeriesType.push(series.type); series.localData = undefined; } if (this.series.length === 0) { this.series.push({}); } this.initialRender = true; this.rangeFound = false; this.resizeTo = null; this.startValue = null; this.endValue = null; } /** * To Initialize the control rendering. */ protected render(): void { const loadEventData: IStockChartEventArgs = { name: 'load', stockChart: this, theme: this.theme }; this.trigger('load', loadEventData, () => { this.theme = this.theme; this.themeStyle = getThemeColor(this.theme); this.storeDataSource(); this.drawSVG(); this.renderTitle(); this.renderLegend(); this.chartModuleInjection(); this.chartRender(); if (!(this.dataSource instanceof DataManager) || !(this.series[0].dataSource instanceof DataManager)) { this.stockChartDataManagerSuccess(); this.initialRender = false; } this.renderComplete(); this.allowServerDataBinding = true; this.isProtectedOnChange = false; }); } /** * DataManager Success */ public stockChartDataManagerSuccess(): void { this.findRange(); this.renderRangeSelector(); this.renderPeriodSelector(); this.trigger('loaded', { stockChart: this }); } /** * To set styles to resolve mvc width issue. * * @param {HTMLElement} element html element */ private setStyle(element: HTMLElement): void { const zooming: ZoomSettingsModel = this.zoomSettings; const disableScroll: boolean = zooming.enableSelectionZooming || zooming.enablePinchZooming || this.selectionMode !== 'None' || this.crosshair.enable; element.style.msTouchAction = disableScroll ? 'none' : 'element'; element.style.touchAction = disableScroll ? 'none' : 'element'; element.style.msUserSelect = 'none'; element.style.msContentZooming = 'none'; element.style.position = 'relative'; element.style.display = 'block'; element.style.webkitUserSelect = 'none'; } private drawSVG(): void { this.removeSvg(); calculateSize(this); this.renderer = new SvgRenderer(this.element.id); this.renderBorder(); this.createSecondaryElements(); this.calculateVisibleSeries(); this.calculateLegendBounds(); //overall svg in which chart and selector appened this.mainObject = this.renderer.createSvg({ id: this.element.id + '_stockChart_svg', width: this.availableSize.width, height: this.availableSize.height - (this.enablePeriodSelector ? this.toolbarHeight : 0) - this.titleSize.height }); this.svgObject = this.mainObject; this.element.appendChild(this.mainObject); } private calculateVisibleSeries(): void { this.visibleSeries = []; let series: Series; const color: string[] = getSeriesColor(this.theme); const count: number = color.length; const seriesCollections: SeriesModel[] = this.series.sort((a: SeriesModel, b: SeriesModel) => { return a.zOrder - b.zOrder; }); for (let i: number = 0, len: number = seriesCollections.length; i < len; i++) { series = <Series>seriesCollections[i]; series.category = 'Series'; series.index = i; series.interior = series.fill || color[i % count]; this.visibleSeries.push(series); seriesCollections[i] = series; } } private createSecondaryElements(): void { const tooltipDiv: Element = redrawElement(false, this.element.id + '_Secondary_Element') || this.createElement('div'); tooltipDiv.id = this.element.id + '_Secondary_Element'; if (this.title) { this.titleSize = measureText(this.title, this.titleStyle); this.titleSize.height += 15; // for title padding } else { this.titleSize = { height: null, width: null }; } const height: number = (this.enablePeriodSelector ? this.toolbarHeight : 0) + this.titleSize.height; tooltipDiv.setAttribute('style', 'position: relative; height:' + height + 'px'); appendChildElement(false, this.element, tooltipDiv, false); } /** * To provide the array of modules needed for control rendering * * @returns {ModuleDeclaration[]} required modules * @private */ public requiredModules(): ModuleDeclaration[] { const modules: ModuleDeclaration[] = []; if(this.legendSettings.visible) { modules.push({ member: 'StockLegend', args: [this] }); } return modules; } public findCurrentData(totalData: Object, xName: string): Object { let tempData: Object; if (totalData && this.startValue && this.endValue) { tempData = (totalData as Object[]) .filter((data: Object) => { return ( new Date(Date.parse(data[xName])).getTime() >= this.startValue && new Date(Date.parse(data[xName])).getTime() <= this.endValue ); }); } return tempData; } /** * Render period selector */ public renderPeriodSelector(): void { if (this.enablePeriodSelector) { this.toolbarSelector.initializePeriodSelector(); this.periodSelector.toolbar.refreshOverflow(); //to avoid overlapping toolbar elements if (!this.enableSelector) { this.cartesianChart.cartesianChartRefresh(this); } } } private chartRender(): void { this.cartesianChart = new CartesianChart(this); this.cartesianChart.initializeChart(); } /** * To render range Selector */ private renderRangeSelector(): void { //SVG in which range navigator is going to append if (this.enableSelector) { this.rangeSelector = new RangeSelector(this); this.rangeSelector.initializeRangeNavigator(); } } /** * Get component name */ public getModuleName(): string { return 'stockChart'; } /** * Get the properties to be maintained in the persisted state. * * @private */ public getPersistData(): string { return ''; } /** * To Remove the SVG. * * @returns {void} * @private */ public removeSvg(): void { if (document.getElementById(this.element.id + '_Secondary_Element')) { remove(document.getElementById(this.element.id + '_Secondary_Element')); } const removeLength: number = 0; if (this.mainObject) { while (this.mainObject.childNodes.length > removeLength) { this.mainObject.removeChild(this.mainObject.firstChild); } if (!this.mainObject.hasChildNodes() && this.mainObject.parentNode) { remove(this.mainObject); this.mainObject = null; this.selectorObject = null; this.chartObject = null; } } } /** * Module Injection for components */ public chartModuleInjection(): void { let moduleName: string; for (const modules of this.getInjectedModules()) { moduleName = modules.prototype.getModuleName().toLowerCase(); if (moduleName.indexOf('rangetooltip') === -1) { Chart.Inject(modules); } else { RangeNavigator.Inject(modules); } if (moduleName === 'datetime' || moduleName === 'areaseries' || moduleName === 'steplineseries') { RangeNavigator.Inject(modules); } } } /** * find range for financal chart */ private findRange(): void { this.seriesXMin = Infinity; this.seriesXMax = -Infinity; for (const value of this.chart.series as Series[]) { if (value.visible) { this.seriesXMin = Math.min(this.seriesXMin, value.xMin); this.seriesXMax = Math.max(this.seriesXMax, value.xMax); } } this.endValue = this.currentEnd = this.seriesXMax; if (this.enablePeriodSelector) { this.toolbarSelector = new ToolBarSelector(this); this.periodSelector = new PeriodSelector(this); this.tempPeriods = this.periods.length ? this.periods : this.toolbarSelector.calculateAutoPeriods(); this.tempPeriods.map((period: PeriodsModel) => { if (period.selected && period.text.toLowerCase() === 'ytd') { this.startValue = new Date(new Date(this.currentEnd).getFullYear().toString()).getTime(); } else if (period.selected && period.text.toLowerCase() === 'all') { this.startValue = this.seriesXMin; } else if (period.selected) { this.startValue = this.periodSelector.changedRange( period.intervalType, this.endValue, period.interval ).getTime(); } }); } else { this.startValue = this.seriesXMin; } this.rangeFound = true; } /** * Handles the chart resize. * * @returns {boolean} false * @private */ public stockChartResize(): boolean { // To avoid resize console error if (!document.getElementById(this.element.id)) { return false; } this.animateSeries = false; if (this.resizeTo) { clearTimeout(this.resizeTo); } this.resizeTo = +setTimeout( (): void => { calculateSize(this); this.renderBorder(); this.calculateLegendBounds(); this.renderTitle(); this.renderLegend(); this.cartesianChart.cartesianChartRefresh(this); this.mainObject.setAttribute('width', this.availableSize.width.toString()); if (this.enablePeriodSelector) { this.renderPeriodSelector(); } }, 500); return false; } /** * Handles the mouse down on chart. * * @returns {boolean} false * @private */ public stockChartOnMouseDown(e: PointerEvent): boolean { let pageX: number; let pageY: number; let target: Element; let touchArg: TouchEvent; const rect: ClientRect = this.chart.element.getBoundingClientRect(); const element: Element = <Element>e.target; this.trigger('stockChartMouseDown', { target: element.id, x: this.mouseX, y: this.mouseY }); if (e.type === 'touchstart') { this.isTouch = true; touchArg = <TouchEvent & PointerEvent>e; pageX = touchArg.changedTouches[0].clientX; target = <Element>touchArg.target; pageY = touchArg.changedTouches[0].clientY; } else { this.isTouch = e.pointerType === 'touch'; pageX = e.clientX; pageY = e.clientY; target = <Element>e.target; } if (target.id.indexOf(this.element.id + '_stockChart_chart') > -1) { const svgRect: ClientRect = getElement(this.element.id + '_stockChart_chart').getBoundingClientRect(); this.mouseDownY = this.previousMouseMoveY = (pageY - rect.top) - Math.max(svgRect.top - rect.top, 0); this.mouseDownX = this.previousMouseMoveX = (pageX - rect.left) - Math.max(svgRect.left - rect.left, 0); this.setMouseXY(this.mouseDownX, this.mouseDownY); this.referenceXAxis = this.chart.primaryXAxis as Axis; getElement(this.element.id + '_stockChart_chart').setAttribute('cursor', 'pointer'); this.mouseDownXPoint = getRangeValueXByPoint(this.mouseX - this.referenceXAxis.rect.x, this.referenceXAxis.rect.width, this.referenceXAxis.visibleRange, this.referenceXAxis.isInversed); this.allowPan = true; this.notify(Browser.touchStartEvent, e); } return false; } /** * Handles the mouse up. * * @returns {boolean} false * @private */ public stockChartMouseEnd(e: PointerEvent): boolean { let pageY: number; let pageX: number; let touchArg: TouchEvent; if (e.type === 'touchend') { touchArg = <TouchEvent & PointerEvent>e; pageX = touchArg.changedTouches[0].clientX; pageY = touchArg.changedTouches[0].clientY; this.isTouch = true; } else { pageY = e.clientY; pageX = e.clientX; this.isTouch = e.pointerType === 'touch' || e.pointerType === '2'; } getElement(this.element.id + '_stockChart_chart').setAttribute('cursor', 'auto'); this.onPanning = false; this.setMouseXY(pageX, pageY); this.stockChartOnMouseUp(e); return false; } /** * Handles the mouse up. * * @returns {boolean} false * @private */ public stockChartOnMouseUp(e: PointerEvent | TouchEvent): boolean { const element: Element = <Element>e.target; this.trigger('stockChartMouseUp', { target: element.id, x: this.mouseX, y: this.mouseY }); this.isChartDrag = false; this.allowPan = false; if (this.isTouch) { this.threshold = new Date().getTime() + 300; } this.notify(Browser.touchEndEvent, e); if (this.stockEvent) { this.stockEvent.removeStockEventTooltip(0); } return false; } /** * To find mouse x, y for aligned chart element svg position */ private setMouseXY(pageX: number, pageY: number): void { const svgRectElement: Element = getElement(this.element.id + '_stockChart_chart'); if (this.element && svgRectElement) { const stockRect: ClientRect = this.element.getBoundingClientRect(); const svgRect: ClientRect = svgRectElement.getBoundingClientRect(); this.mouseX = (pageX - stockRect.left) - Math.max(svgRect.left - stockRect.left, 0); this.mouseY = (pageY - stockRect.top) - Math.max(svgRect.top - stockRect.top, 0); } } /** * Handles the mouse move. * * @returns {boolean} false * @private */ public stockChartOnMouseMove(e: PointerEvent): boolean { let pageX: number; let touchArg: TouchEvent; let pageY: number; if (e.type === 'touchmove') { this.isTouch = true; touchArg = <TouchEvent & PointerEvent>e; pageY = touchArg.changedTouches[0].clientY; pageX = touchArg.changedTouches[0].clientX; } else { this.isTouch = e.pointerType === 'touch' || e.pointerType === '2' || this.isTouch; pageX = e.clientX; pageY = e.clientY; } this.trigger('stockChartMouseMove', { target: (e.target as Element).id, x: this.mouseX, y: this.mouseY }); if (getElement(this.element.id + '_stockChart_chart')) { this.setMouseXY(pageX, pageY); this.chartOnMouseMove(e); } return false; } /** * Handles the mouse move on chart. * * @returns {boolean} false * @private */ public chartOnMouseMove(e: PointerEvent | TouchEvent): boolean { if (this.allowPan && this.mouseDownXPoint && this.mouseX !== this.previousMouseMoveX && this.zoomSettings.enablePan) { this.onPanning = true; getElement(this.element.id + '_stockChart_chart').setAttribute('cursor', 'pointer'); this.mouseUpXPoint = getRangeValueXByPoint(this.mouseX - this.referenceXAxis.rect.x, this.referenceXAxis.rect.width, this.referenceXAxis.visibleRange, this.referenceXAxis.isInversed); const diff: number = Math.abs(this.mouseUpXPoint - this.mouseDownXPoint); if (this.mouseDownXPoint < this.mouseUpXPoint) { if (this.seriesXMin <= this.referenceXAxis.visibleRange.min - diff) { this.startValue = this.referenceXAxis.visibleRange.min - diff; this.endValue = this.referenceXAxis.visibleRange.max - diff; this.cartesianChart.cartesianChartRefresh(this); this.rangeSelector.sliderChange(this.referenceXAxis.visibleRange.min - diff, this.referenceXAxis.visibleRange.max - diff); } } else { if (this.seriesXMax >= this.referenceXAxis.visibleRange.max + diff) { this.startValue = this.referenceXAxis.visibleRange.min + diff; this.endValue = this.referenceXAxis.visibleRange.max + diff; this.cartesianChart.cartesianChartRefresh(this); this.rangeSelector.sliderChange(this.referenceXAxis.visibleRange.min + diff, this.referenceXAxis.visibleRange.max + diff); } } } this.notify(Browser.touchMoveEvent, e); if ((<HTMLElement>e.target).id === '') { //to remove the tooltip when hover on mouse move let element: HTMLElement; if (this.chart.tooltip.enable || this.crosshair.enable) { element = document.getElementById(this.element.id + '_stockChart_chart_tooltip'); if (element) { remove(element); } } if (getElement(this.element.id + '_StockEvents_Tooltip')) { this.stockEvent.removeStockEventTooltip(0); } } if ((<HTMLElement>e.target).id.indexOf('StockEvents') !== -1) { clearInterval(this.stockEvent.toolTipInterval); this.stockEvent.renderStockEventTooltip((e.target as HTMLElement).id); } else { if (this.stockEvent) { this.stockEvent.removeStockEventTooltip(1000); } } this.isTouch = false; return false; } /** * Handles the mouse click on chart. * * @returns {boolean} false * @private */ public stockChartOnMouseClick(e: PointerEvent | TouchEvent): boolean { const element: Element = <Element>e.target; this.trigger('stockChartMouseClick', { target: element.id, x: this.mouseX, y: this.mouseY }); this.notify('click', e); return false; } private stockChartRightClick(event: MouseEvent | PointerEvent): boolean { if (this.crosshair.enable && (event.buttons === 2 || event.which === 0 || (<PointerEvent>event).pointerType === 'touch')) { event.preventDefault(); event.stopPropagation(); return false; } return true; } /** * Handles the mouse leave. * * @returns {boolean} false * @private */ public stockChartOnMouseLeave(e: PointerEvent): boolean { let touchArg: TouchEvent; let pageX: number; let pageY: number; if (e.type === 'touchleave') { this.isTouch = true; touchArg = <TouchEvent & PointerEvent>e; pageX = touchArg.changedTouches[0].clientX; pageY = touchArg.changedTouches[0].clientY; } else { pageX = e.clientX; pageY = e.clientY; this.isTouch = e.pointerType === 'touch' || e.pointerType === '2'; } this.setMouseXY(pageX, pageY); this.allowPan = false; this.stockChartOnMouseLeaveEvent(e); return false; } /** * Handles the mouse leave on chart. * * @returns {boolean} false * @private */ public stockChartOnMouseLeaveEvent(e: PointerEvent | TouchEvent): boolean { const cancelEvent: string = Browser.isPointer ? 'pointerleave' : 'mouseleave'; //this.trigger(chartMouseLeave, { target: element.id, x: this.mouseX, y: this.mouseY }); this.isChartDrag = false; this.notify(cancelEvent, e); if (this.stockEvent) { this.stockEvent.removeStockEventTooltip(1000); } return false; } /** * Destroy method */ public destroy(): void { //Perform destroy here } private renderBorder(): void { if (this.border.width) { const border: HTMLElement = this.createElement('div'); border.id = this.element.id + '_stock_border'; border.style.width = (this.availableSize.width) + 'px'; border.style.height = (this.availableSize.height) + 'px'; border.style.position = 'absolute'; border.style.border = this.border.width + 'px solid ' + this.border.color; border.style.pointerEvents = 'none'; appendChildElement(false, getElement(this.element.id), border); } } /** * Render title for chart */ private renderTitle(): void { let rect: Rect; if (this.title) { appendChildElement( false, getElement(this.element.id + '_Secondary_Element'), this.renderer.createSvg({ id: this.element.id + '_stockChart_Title', width: this.availableSize.width, height: this.titleSize.height, fill: this.background || this.themeStyle.background }), false); const alignment: Alignment = this.titleStyle.textAlignment; const getAnchor: string = alignment === 'Near' ? 'start' : alignment === 'Far' ? 'end' : 'middle'; rect = new Rect( 0, 0, this.availableSize.width, 0 ); const options: TextOption = new TextOption( this.element.id + '_ChartTitle', titlePositionX(rect, this.titleStyle), ((this.titleSize.height - 10)), getAnchor, this.title, '', 'auto' ); textElement( this.renderer as unknown as SvgRenderer, options, this.titleStyle, this.titleStyle.color || this.findTitleColor(), getElement(this.element.id + '_stockChart_Title'), false, false ); this.availableSize.height -= (this.titleSize.height + 5); } } /** * @private */ public calculateLegendBounds(): void { if (this.stockLegendModule && this.legendSettings.visible) { this.stockLegendModule.getLegendOptions(this.visibleSeries, this); } const titleHeight: number = this.titleSize.height; const left: number = this.border.width; const width: number = this.availableSize.width - this.border.width - left; const top: number = this.chartArea.border.width * 0.5 + this.border.width; const height: number = this.availableSize.height - top - this.border.width - (this.enablePeriodSelector ? this.toolbarHeight : 0) - titleHeight; this.initialClipRect = new Rect(left, top, width, height); this.tempAvailableSize = new Size(this.availableSize.width, this.availableSize.height - (this.enablePeriodSelector ? this.toolbarHeight : 0) - titleHeight) if (this.stockLegendModule && this.legendSettings.visible) { this.stockLegendModule.calculateLegendBounds(this.initialClipRect, this.tempAvailableSize, null); } } /** * To render the legend * @private */ public renderLegend(): void { if (this.stockLegendModule && this.stockLegendModule.legendCollections.length && this.legendSettings.visible) { this.stockLegendModule.calTotalPage = true; const bounds: Rect = this.stockLegendModule.legendBounds; this.stockLegendModule.renderLegend(this, this.legendSettings, bounds); if (this.legendSettings.position === "Auto" || this.legendSettings.position === "Bottom" || this.legendSettings.position === "Top") { this.availableSize.height -= this.stockLegendModule.legendBounds.height; } else if (this.legendSettings.position === "Left" || this.legendSettings.position === "Right") { this.availableSize.width -= this.stockLegendModule.legendBounds.width; } } } private findTitleColor(): string { if (this.theme.toLocaleLowerCase().indexOf('highcontrast') > -1 || this.theme.indexOf('Dark') > -1) { return '#ffffff'; } return '#424242'; } /** * @private */ public calculateStockEvents(): void { if (this.stockEvents.length) { this.stockEvent = new StockEvents(this); appendChildElement(false, this.chartObject, this.stockEvent.renderStockEvents()); } } }
the_stack
import { Observable, from } from 'rxjs'; import * as scrapeIt from 'scrape-it'; import * as puppeteer from 'puppeteer'; import { JsonDB } from 'node-json-db'; import { inject, injectable } from 'inversify'; import SERVICE_IDENTIFIER from '../../common/constants/identifiers'; import ILogger from '../../common/interfaces/ilogger'; import { IScraper, ScrapeData } from '../interfaces'; const supportedCountries = ['US', 'IN']; const supportedMarketPlaces = ['AMAZON']; const marketplaceConfig = [ { marketplace: 'AMAZON', country: 'IN', url: 'https://www.amazon.in/dp/' }, { marketplace: 'AMAZON', country: 'US', url: 'https://www.amazon.com/dp/' }, { marketplace: 'FLIPKART', country: 'IN', url: 'https://www.flipkart.com/' } ]; const amazonConfig = { title: '#productTitle', salePrice: 'tr#priceblock_ourprice_row td.a-span12 span#priceblock_ourprice', salePriceDesc: 'tr#priceblock_ourprice_row span.a-size-small.a-color-price', dealPrice: 'span#priceblock_dealprice', sellerPrice: { selector: 'div#toggleBuyBox span.a-color-price', convert: x => { if (x.charAt(0) === '$') { return x.slice(1); } return x; } }, mrpPrice: 'div#price span.a-text-strike', savings: 'tr#regularprice_savings td.a-span12.a-color-price.a-size-base', brand: 'div#bylineInfo_feature_div a#bylineInfo', vat: 'tr#vatMessage', availiability: 'div#availability', vnv: 'div#vnv-container', features: { listItem: 'div#feature-bullets ul li', name: 'features', data: { feature: 'span.a-list-item' } }, images: { listItem: 'div#imageBlock div#altImages ul li', name: 'altImages', data: { url: { selector: 'img', attr: 'src', convert: x => x.replace(/_[S][A-Z][0-9][0-9]_./g, '') } } }, brandUrl: { selector: 'div#bylineInfo_feature_div a#bylineInfo', attr: 'href' }, image: { selector: 'img#landingImage', attr: 'src' } }; const flipkartConfig = { title: '._35KyD6', salePrice: { selector: '._1vC4OE._3qQ9m1', convert: x => { if (x) { return x.replace(/\D/g, ''); } return x; } }, salePriceDesc: '#tobedone', dealPrice: '#tobedone', sellerPrice: { selector: '#tobedone', convert: x => { if (x.charAt(0) === '$') { return x.slice(1); } return x; } }, mrpPrice: { selector: '._3auQ3N._1POkHg', convert: x => { if (x) { return x.replace(/\D/g, ''); } return x; } }, savings: { selector: '.VGWI6T._1iCvwn span', convert: x => { if (x) { return x.replace(/\D/g, ''); } return x; } }, brand: '._3Rrcbo > ._2RngUh:nth-child(2) table tbody > tr:nth-child(1) ul> li._3YhLQA', vat: '#tobedone', availiability: 'div.mBwvBe', availiabilityMessage: 'div._37bjSl', //For Flipkart vnv: '#tobedone', features: { listItem: '#tobedone', name: 'features', data: { feature: '#tobedone' } }, images: { listItem: '._1HmYoV ._2rDnao ._3BTv9X', name: 'altImages', data: { url: { selector: 'img', attr: 'src', convert: x => x.replace(/_[S][A-Z][0-9][0-9]_./g, '') } } }, brandUrl: { selector: '._1joEet > ._1HEvv0:nth-last-child(2) a', attr: 'href' }, image: { selector: 'img._1Nyybr', attr: 'src' } }; const defaultConfig = amazonConfig; /** * Starwars Service Implementation */ @injectable() class ScraperService implements IScraper { public loggerService: ILogger; public db: JsonDB; public dbPublish: JsonDB; public constructor( @inject(SERVICE_IDENTIFIER.LOGGER) loggerService: ILogger ) { this.loggerService = loggerService; } public getScrapedData = (url: string, headless?: string): Observable<any> => { return from( new Promise((resolve, reject) => { if (typeof headless !== 'undefined' && headless === 'true') { // console.log('using Puppeteer'); puppeteer .launch() .then(browser => { return browser.newPage(); }) .then(page => { return page.goto(url).then(() => { return page.content(); }); }) .then(html => { const data = scrapeIt.scrapeHTML( html, this.getConfiguration(url) ); const updatedData = this.transformScrapedData( data, url, null, url ); resolve(updatedData); }) .catch(err => { this.loggerService.error(err); reject(err); }); } else { // console.log('using Ajax'); scrapeIt(url, this.getConfiguration(url)).then( ({ data, response }) => { const updatedData = this.transformScrapedData( data, url, null, url ); resolve(updatedData); }, error => { this.loggerService.error(error); } ); } }) ); }; public getScrapedListData = ( { country, marketplace, baseUrl, asinList }, withURL: boolean ): Observable<any> => { const res = asinList.split(','); const defaultUrl = this.getBaseURLFor(country, marketplace); // override country,market place if the url is provided const scrapeBaseUrl = typeof baseUrl !== 'undefined' ? baseUrl : defaultUrl; const scrapeMarketplace = typeof marketplace !== 'undefined' ? marketplace : this.getMarketPlace(scrapeBaseUrl); const scrappedList = res.map( asin => new Promise((resolve, reject) => { const asinUrl = withURL ? asin : `${scrapeBaseUrl}${asin}`; scrapeIt(asinUrl, this.getConfiguration(asinUrl)).then( ({ data, response }) => { const updatedData = this.transformScrapedData( data, asinUrl, scrapeMarketplace, asin ); resolve(updatedData); }, error => { reject(error); } ); }) ); return from( new Promise((resolve, reject) => Promise.all(scrappedList).then( values => resolve(values), error => reject(error) ) ) ); }; public push(name: string, data: any, replace?: boolean): Observable<any> { this.initDb(); return from( new Promise((resolve, reject) => { try { this.loggerService.info(name); if (replace) { this.db.push(`/${name}`, { ...data }); resolve(data); return; } // current scraped data let currentData = null; // New updates const newData = data.data; try { // Check if an entry exists currentData = this.db.getData(`/${name}/`); } catch (error) {} // If exists if (currentData !== null && currentData.data !== null) { newData.map(elem => { const index = currentData.data.findIndex( item => item.title === elem.title && item.marketplace === elem.marketplace ); // Update existing entries if (index > -1) { currentData.data[index] = elem; } else { // Add new entry currentData.data.push(elem); } }); } else { // No previous entry to use as is currentData = data; } /* if (allData) { currentData = { ...currentData, ...data, data: currentData.data } } */ this.db.push(`/${name}`, { ...currentData }); resolve(newData); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. reject(error); } }) ); } public pushProduct(name: string, data: any): Observable<any> { this.initDb(); return from( new Promise((resolve, reject) => { try { this.loggerService.info(name); let currentData = null; // Check if preview values exist try { currentData = this.db.getData(`/${name}/data/`); } catch (error) {} const { title, marketplace } = data.data; const index = currentData === null ? -1 : currentData.findIndex( item => item.title === title && item.marketplace === marketplace ); // If exist overwrite value if (index > -1) { this.db.push(`/${name}/data[${index}]/`, { ...data.data }); } else { // Create new entry / append this.db.push(`/${name}/data[]/`, { ...data.data }); } resolve(data); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. // console.log('Got an Error'); reject(error); } }) ); } public deleteMicrositeByID(name: string): Observable<any> { this.initDb(); return from( new Promise((resolve, reject) => { try { this.loggerService.info(name); this.db.getData(`/${name}`); this.db.delete(`/${name}`); resolve({ message: `Campaign ${name} deleted` }); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. reject(error); } }) ); } public deleteMicrositePublishByID(name: string): Observable<any> { this.initPublishDb(); return from( new Promise((resolve, reject) => { try { this.loggerService.info(name); this.dbPublish.getData(`/${name}`); this.dbPublish.delete(`/${name}`); resolve({ message: `Campaign Publish record: ${name} deleted` }); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. reject(error); } }) ); } public byMicrositeByID(name: string): Observable<any> { this.initDb(); return from( new Promise((resolve, reject) => { try { this.loggerService.info(name); const data = this.db.getData(`/${name}`); this.loggerService.info(data); resolve(data); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. reject(error); } }) ); } public getAll(): Observable<any> { this.initDb(); return from( new Promise((resolve, reject) => { try { const data = this.db.getData(`/`); this.loggerService.info(data); resolve(data); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. reject(error); } }) ); } public getAllSites(): Observable<any> { this.initPublishDb(); return from( new Promise((resolve, reject) => { try { const data = this.dbPublish.getData(`/`); this.loggerService.info(data); resolve(data); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. reject(error); } }) ); } public pushSite(name: string, data: string): Observable<any> { this.initPublishDb(); return from( new Promise((resolve, reject) => { try { this.loggerService.info(name); this.dbPublish.push(`/${name}`, data); resolve(data); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. reject(error); } }) ); } public byPublishedMicrositeByID(name: string): Observable<any> { this.initPublishDb(); return from( new Promise((resolve, reject) => { try { this.loggerService.info(name); const data = this.dbPublish.getData(`/${name}`); this.loggerService.info(data); resolve(data); } catch (error) { // The error will tell you where the DataPath stopped. In this case test1 // Since /test1/test does't exist. reject(error); } }) ); } private transformScrapedData = (data, url, marketPlace?, id?): any => { const scrapeMarketplace = marketPlace ? marketPlace : this.getMarketPlace(url); const scrapedData: any = data; const { dealPrice, salePrice, sellerPrice } = scrapedData; // if there is a deal then show that if (dealPrice.length > 0) { scrapedData.salePrice = dealPrice; } else if ( // if sale price and deal price // are not available then fall back // on seller price salePrice.length === 0 && dealPrice.length === 0 && sellerPrice.length > 0 ) { scrapedData.salePrice = sellerPrice; } const updatedData = { ...scrapedData, id, scrapedUrl: url, marketplace: scrapeMarketplace, scrapeDate: new Date() }; return updatedData; }; private initDb = () => { if (this.db === undefined) { this.db = new JsonDB('productsDB', true, false); } }; private initPublishDb = () => { if (this.dbPublish === undefined) { this.dbPublish = new JsonDB('publishDB', true, false); } }; private getConfiguration = (url: string) => { if (url.toUpperCase().includes('AMAZON')) { return amazonConfig; } else if (url.toUpperCase().includes('FLIPKART')) { return flipkartConfig; } else { return defaultConfig; } }; private getMarketPlace = (url: string) => { let defaultMarketPlace = 'Amazon'; if (url.toUpperCase().includes('FLIPKART')) { defaultMarketPlace = 'Flipkart'; } return defaultMarketPlace; }; /** * Get the base URL based on the country and marketplace * In the country or marketplace are not supported return the default * url based on amazon india */ private getBaseURLFor = (country: string, marketplace: string) => { let currentMarketPlace = 'AMAZON'; let currentCountry = 'IN'; const defaultURL = 'https://www.amazon.in/dp/'; if ( typeof marketplace !== 'undefined' && supportedMarketPlaces.indexOf(marketplace.toUpperCase()) > -1 ) { currentMarketPlace = marketplace.toUpperCase(); } if ( typeof country !== 'undefined' && supportedCountries.indexOf(country.toUpperCase()) > -1 ) { currentCountry = country.toUpperCase(); } const marketplaceInfo = marketplaceConfig.find( item => item.country === currentCountry && item.marketplace === currentMarketPlace ); return typeof marketplaceInfo !== 'undefined' ? marketplaceInfo.url : defaultURL; }; } export default ScraperService;
the_stack
import * as vscode from 'vscode'; import * as util from './utility'; import * as parse from './parsing'; import SourceFile from './SourceFile'; import SourceSymbol from './SourceSymbol'; import CSymbol from './CSymbol'; import SubSymbol from './SubSymbol'; import { ProposedPosition } from './ProposedPosition'; const re_preprocessorDirective = /(?<=^\s*)#.*\S(?=\s*$)/gm; interface PreprocessorConditional { start: SubSymbol; end: SubSymbol; } /** * Represents a C/C++ source file that has access to the contents of the file. */ export default class SourceDocument extends SourceFile implements vscode.TextDocument { private readonly doc: vscode.TextDocument; private readonly proposedDefinitions = new WeakMap<vscode.Position, vscode.Location>(); // Don't use these, use their getters instead. private _preprocessorDirectives?: SubSymbol[]; private _conditionals?: PreprocessorConditional[]; private _includedFiles?: string[]; private _headerGuardDirectives?: SubSymbol[]; constructor(document: vscode.TextDocument, sourceFile?: SourceFile) { super(document.uri); this.doc = document; this.symbols = sourceFile?.symbols; } static async open(uri: vscode.Uri): Promise<SourceDocument> { const document = await vscode.workspace.openTextDocument(uri); return new SourceDocument(document); } // Pass through to the provided TextDocument in order to implement. get isUntitled(): boolean { return this.doc.isUntitled; } get languageId(): string { return this.doc.languageId; } get version(): number { return this.doc.version; } get isDirty(): boolean { return this.doc.isDirty; } get isClosed(): boolean { return this.doc.isClosed; } save(): Thenable<boolean> { return this.doc.save(); } get eol(): vscode.EndOfLine { return this.doc.eol; } get lineCount(): number { return this.doc.lineCount; } lineAt(lineOrPos: number | vscode.Position): vscode.TextLine { return this.doc.lineAt(lineOrPos as any); } offsetAt(position: vscode.Position): number { return this.doc.offsetAt(position); } positionAt(offset: number): vscode.Position { return this.doc.positionAt(offset); } getText(range?: vscode.Range): string { return this.doc.getText(range); } validateRange(range: vscode.Range): vscode.Range { return this.doc.validateRange(range); } validatePosition(position: vscode.Position): vscode.Position { return this.doc.validatePosition(position); } getWordRangeAtPosition(position: vscode.Position, regex?: RegExp): vscode.Range | undefined { return this.doc.getWordRangeAtPosition(position, regex); } get endOfLine(): string { return util.endOfLine(this); } rangeAt(startOffset: number, endOffset: number): vscode.Range { const start = this.positionAt(startOffset); const end = this.positionAt(endOffset); return new vscode.Range(start, end); } async getSymbol(position: vscode.Position): Promise<CSymbol | undefined> { const symbol = await super.getSymbol(position); return symbol ? new CSymbol(symbol, this) : undefined; } static async getSymbol(location: vscode.Location): Promise<CSymbol | undefined> { const sourceDoc = await SourceDocument.open(location.uri); return sourceDoc.getSymbol(location.range.start); } async findMatchingSymbol(target: CSymbol): Promise<CSymbol | undefined> { if (!this.symbols) { this.symbols = await this.executeSourceSymbolProvider(); } return SourceFile.findMatchingSymbol(target, this.symbols, this) as CSymbol | undefined; } async allFunctions(): Promise<CSymbol[]> { if (!this.symbols) { this.symbols = await this.executeSourceSymbolProvider(); } const sourceDoc = this; return function findFunctions(symbols: SourceSymbol[]): CSymbol[] { const functions: CSymbol[] = []; symbols.forEach(symbol => { if (symbol.isFunction()) { functions.push(new CSymbol(symbol, sourceDoc)); } else if (symbol.children.length > 0) { functions.push(...findFunctions(symbol.children)); } }); return functions; } (this.symbols); } async namespaces(): Promise<CSymbol[]> { if (!this.symbols) { this.symbols = await this.executeSourceSymbolProvider(); } const namespaces: CSymbol[] = []; this.symbols.forEach(symbol => { if (symbol.isNamespace()) { namespaces.push(new CSymbol(symbol, this)); } }); return namespaces; } get preprocessorDirectives(): SubSymbol[] { if (this._preprocessorDirectives) { return this._preprocessorDirectives; } this._preprocessorDirectives = []; const maskedText = parse.maskNonSourceText(this.getText()); for (const match of maskedText.matchAll(re_preprocessorDirective)) { if (match.index !== undefined) { const range = this.rangeAt(match.index, match.index + match[0].length); this._preprocessorDirectives.push(new SubSymbol(this, range)); } } return this._preprocessorDirectives; } private get conditionals(): PreprocessorConditional[] { if (this._conditionals) { return this._conditionals; } this._conditionals = []; const openConditionals: SubSymbol[] = []; for (const directive of this.preprocessorDirectives) { const keywordMatch = directive.text().match(/(?<=^#\s*)[\w_][\w\d_]*\b/); if (keywordMatch) { switch (keywordMatch[0]) { case 'if': case 'ifdef': case 'ifndef': openConditionals.push(directive); break; case 'elif': case 'else': if (openConditionals.length > 0) { this._conditionals.push({ start: openConditionals.pop()!, end: directive }); } openConditionals.push(directive); break; case 'endif': if (openConditionals.length > 0) { this._conditionals.push({ start: openConditionals.pop()!, end: directive }); } break; } } } return this._conditionals; } get includedFiles(): string[] { if (this._includedFiles) { return this._includedFiles; } this._includedFiles = []; for (const directive of this.preprocessorDirectives) { const fileMatch = directive.text().match(/(?<=^#\s*include\s*[<"]).+(?=[>"])/); if (fileMatch) { this._includedFiles.push(fileMatch[0]); } } return this._includedFiles; } get headerGuardDirectives(): SubSymbol[] { if (this._headerGuardDirectives) { return this._headerGuardDirectives; } this._headerGuardDirectives = []; if (!this.isHeader()) { return this._headerGuardDirectives; } for (let i = 0; i < this.preprocessorDirectives.length; ++i) { if (/^#\s*pragma\s+once\b/.test(this.preprocessorDirectives[i].text())) { this._headerGuardDirectives.push(this.preprocessorDirectives[i]); } const match = this.preprocessorDirectives[i].text().match(/(?<=^#\s*ifndef\s+)[\w_][\w\d_]*\b/); if (match && i + 1 < this.preprocessorDirectives.length) { const re_headerGuardDefine = new RegExp(`^#\\s*define\\s+${match[0]}\\b`); if (re_headerGuardDefine.test(this.preprocessorDirectives[i + 1].text())) { this._headerGuardDirectives.push(this.preprocessorDirectives[i]); this._headerGuardDirectives.push(this.preprocessorDirectives[i + 1]); // The header guard conditional should be the last in the array, so we walk backwards. for (let j = this.conditionals.length - 1; j >= 0; --j) { if (this.conditionals[j].start === this.preprocessorDirectives[i]) { this._headerGuardDirectives.push(this.conditionals[j].end); break; } } break; } } } return this._headerGuardDirectives; } get hasHeaderGuard(): boolean { return this.headerGuardDirectives.length > 0; } get hasPragmaOnce(): boolean { for (const directive of this.headerGuardDirectives) { if (/^#\s*pragma\s+once\b/.test(directive.text())) { return true; } } return false; } get headerGuardDefine(): string { for (const directive of this.headerGuardDirectives) { const match = directive.text().match(/(?<=^#\s*define\s+)[\w_][\w\d_]*\b/); if (match) { return match[0]; } } return ''; } positionAfterHeaderGuard(): vscode.Position | undefined { for (let i = this.headerGuardDirectives.length - 1; i >= 0; --i) { if (!/^#\s*endif\b/.test(this.headerGuardDirectives[i].text())) { return new vscode.Position(this.headerGuardDirectives[i].range.start.line + 1, 0); } } } positionAfterHeaderComment(): ProposedPosition { const text = this.getText(); const maskedText = parse.maskComments(text, false); const offset = maskedText.search(/\S/); if (offset !== -1) { // Return position before first non-comment text. return new ProposedPosition(this.positionAt(offset), { before: true }); } // Return position after header comment when there is no non-comment text in the file. const endTrimmedTextLength = text.trimEnd().length; return new ProposedPosition(this.positionAt(endTrimmedTextLength), { after: endTrimmedTextLength !== 0 }); } /** * Returns the best positions to place new includes (system and project includes). * Optionally provide a beforePos to enforce that the positions returned are before it. */ findPositionForNewInclude(beforePos?: vscode.Position): { system: vscode.Position; project: vscode.Position } { let systemIncludeLine: number | undefined; let projectIncludeLine: number | undefined; for (const directive of this.preprocessorDirectives) { if (beforePos?.isBefore(directive.range.end)) { break; } const directiveText = directive.text(); if (/^#\s*include\s*<.+>/.test(directiveText)) { systemIncludeLine = directive.range.start.line; } else if (/^#\s*include\s*".+"/.test(directiveText)) { projectIncludeLine = directive.range.start.line; } } if (systemIncludeLine === undefined) { systemIncludeLine = projectIncludeLine; } if (projectIncludeLine === undefined) { projectIncludeLine = systemIncludeLine; } if (systemIncludeLine === undefined || projectIncludeLine === undefined) { let position = this.positionAfterHeaderGuard(); if (!position) { position = this.positionAfterHeaderComment(); } return { system: position, project: position }; } return { system: new vscode.Position(systemIncludeLine + 1, 0), project: new vscode.Position(projectIncludeLine + 1, 0) }; } async findSmartPositionForFunctionDeclaration( definition: CSymbol, targetDoc?: SourceDocument, parentClass?: CSymbol, access?: util.AccessLevel ): Promise<ProposedPosition> { if (!this.symbols) { this.symbols = await this.executeSourceSymbolProvider(); } if (!targetDoc) { targetDoc = this; } if (!targetDoc.symbols) { await targetDoc.executeSourceSymbolProvider(); } if (!targetDoc.symbols || targetDoc.symbols.length === 0) { return util.positionAfterLastNonEmptyLine(targetDoc); } else if (definition?.uri.fsPath !== this.uri.fsPath || (!definition.parent && this.symbols.length === 0)) { return targetDoc.positionAfterLastSymbol(targetDoc.symbols); } if (access !== undefined) { const memberPos = await targetDoc.findPositionForMemberFunction(definition, parentClass, access); if (memberPos) { return memberPos; } } const siblingFunctions = SourceDocument.siblingFunctions(definition, this.symbols); const definitionIndex = SourceDocument.indexOfSymbol(definition, siblingFunctions); const before = siblingFunctions.slice(0, definitionIndex).reverse(); const after = siblingFunctions.slice(definitionIndex + 1); const siblingPos = await this.findPositionRelativeToSiblings( definition, before, after, targetDoc, false, parentClass); if (siblingPos) { return siblingPos; } if (access === undefined) { const memberPos = await targetDoc.findPositionForMemberFunction(definition, parentClass, access); if (memberPos) { return memberPos; } } // If a sibling declaration couldn't be found in targetDoc, look for a position in a parent namespace. const namespacePos = await targetDoc.findPositionInParentNamespace(definition); if (namespacePos) { return namespacePos; } // If all else fails then return a position after the last symbol in the document. return targetDoc.positionAfterLastSymbol(targetDoc.symbols); } /** * Returns the best position to place the definition for a function declaration. * If targetDoc is undefined then this SourceDocument will be used. */ async findSmartPositionForFunctionDefinition( declarationOrPosition: SourceSymbol | CSymbol | ProposedPosition, targetDoc?: SourceDocument ): Promise<ProposedPosition> { if (!this.symbols) { this.symbols = await this.executeSourceSymbolProvider(); } const declaration = await async function (sourceDoc: SourceDocument): Promise<CSymbol | undefined> { if (declarationOrPosition instanceof ProposedPosition) { return declarationOrPosition.options.relativeTo !== undefined ? sourceDoc.getSymbol(declarationOrPosition.options.relativeTo.start) : sourceDoc.getSymbol(declarationOrPosition); } else if (declarationOrPosition instanceof CSymbol) { return declarationOrPosition; } else { return new CSymbol(declarationOrPosition, sourceDoc); } } (this); if (!targetDoc) { targetDoc = this; } if (!targetDoc.symbols) { await targetDoc.executeSourceSymbolProvider(); } if (!targetDoc.symbols || targetDoc.symbols.length === 0) { return util.positionAfterLastNonEmptyLine(targetDoc); } else if (declaration?.uri.fsPath !== this.uri.fsPath || (!declaration.parent && this.symbols.length === 0)) { return targetDoc.positionAfterLastSymbol(targetDoc.symbols); } const siblingFunctions = SourceDocument.siblingFunctions(declaration, this.symbols); const declarationIndex = SourceDocument.indexOfSymbol(declaration, siblingFunctions); const before = siblingFunctions.slice(0, declarationIndex).reverse(); const after = siblingFunctions.slice(declarationIndex + 1); if (declarationOrPosition instanceof ProposedPosition) { const position = declarationOrPosition; if (position.options.after) { before.push(declaration); before.shift(); } else if (position.options.before) { after.unshift(declaration); after.pop(); } } const position = await this.findPositionRelativeToSiblings(declaration, before, after, targetDoc, true); if (position) { return position; } // If a sibling definition couldn't be found in targetDoc, look for a position in a parent namespace. const namespacePos = await targetDoc.findPositionInParentNamespace(declaration); if (namespacePos) { return namespacePos; } // If all else fails then return a position after the last symbol in the document. return targetDoc.positionAfterLastSymbol(targetDoc.symbols); } async findPositionForFunctionDefinition( declaration: CSymbol, targetDoc?: SourceDocument ): Promise<ProposedPosition> { if (!this.symbols) { this.symbols = await this.executeSourceSymbolProvider(); } if (!targetDoc) { targetDoc = this; } if (!targetDoc.symbols) { await targetDoc.executeSourceSymbolProvider(); } if (!targetDoc.symbols || targetDoc.symbols.length === 0) { return util.positionAfterLastNonEmptyLine(targetDoc); } else if (declaration?.uri.fsPath !== this.uri.fsPath || (!declaration.parent && this.symbols.length === 0)) { return targetDoc.positionAfterLastSymbol(targetDoc.symbols); } // If a sibling definition couldn't be found in targetDoc, look for a position in a parent namespace. const namespacePos = await targetDoc.findPositionInParentNamespace(declaration); if (namespacePos) { return namespacePos; } // If all else fails then return a position after the last symbol in the document. return targetDoc.positionAfterLastSymbol(targetDoc.symbols); } /** * Returns a position after the last symbol in this SourceDocument, or after the last non-empty line. */ async findPositionForNewSymbol(): Promise<ProposedPosition> { if (!this.symbols) { this.symbols = await this.executeSourceSymbolProvider(); } return this.positionAfterLastSymbol(this.symbols); } // TODO: Give this function a better name or refactor this to not be so terrible. private async findPositionRelativeToSiblings( anchorSymbol: CSymbol, before: SourceSymbol[], after: SourceSymbol[], targetDoc: SourceDocument, findDefinition: boolean, parentClass?: CSymbol ): Promise<ProposedPosition | undefined> { const anchorSymbolAllScopes = anchorSymbol.allScopes(); let checkedFunctionCount = 0; for (const symbol of before) { if (checkedFunctionCount > 5) { break; } const functionSymbol = new CSymbol(symbol, this); const isDeclOrDef = findDefinition ? functionSymbol.isFunctionDeclaration() : functionSymbol.isFunctionDefinition(); if (isDeclOrDef) { ++checkedFunctionCount; const location = findDefinition ? await this.findDefinition(functionSymbol) : await functionSymbol.findDeclaration(); if (!location || location.uri.fsPath !== targetDoc.uri.fsPath) { continue; } const linkedSymbol = await targetDoc.getSymbol(location.range.start); if (!linkedSymbol || linkedSymbol.isClassType()) { /* cpptools is dumb and will return the class when finding the * declaration/definition of an undeclared member function. */ continue; } if (!util.arraysIntersect(linkedSymbol.allScopes(), anchorSymbolAllScopes)) { continue; } if (!(anchorSymbol.uri.fsPath === linkedSymbol.uri.fsPath && anchorSymbol.parent?.range.contains(linkedSymbol.selectionRange)) && parentClass?.matches(linkedSymbol) !== false) { this.proposedDefinitions.set( anchorSymbol.selectionRange.start, new vscode.Location(targetDoc.uri, linkedSymbol.selectionRange) ); return new ProposedPosition(linkedSymbol.trailingCommentEnd(), { relativeTo: linkedSymbol.range, after: true }); } } } checkedFunctionCount = 0; for (const symbol of after) { if (checkedFunctionCount > 5) { break; } const functionSymbol = new CSymbol(symbol, this); const isDeclOrDef = findDefinition ? functionSymbol.isFunctionDeclaration() : functionSymbol.isFunctionDefinition(); if (isDeclOrDef) { ++checkedFunctionCount; const location = findDefinition ? await this.findDefinition(functionSymbol) : await functionSymbol.findDeclaration(); if (!location || location.uri.fsPath !== targetDoc.uri.fsPath) { continue; } const linkedSymbol = await targetDoc.getSymbol(location.range.start); if (!linkedSymbol || linkedSymbol.isClassType()) { /* cpptools is dumb and will return the class when finding the * declaration/definition of an undeclared member function. */ continue; } if (!util.arraysIntersect(linkedSymbol.allScopes(), anchorSymbolAllScopes)) { continue; } if (!(anchorSymbol.uri.fsPath === linkedSymbol.uri.fsPath && anchorSymbol.parent?.range.contains(linkedSymbol.selectionRange)) && parentClass?.matches(linkedSymbol) !== false) { this.proposedDefinitions.set( anchorSymbol.selectionRange.start, new vscode.Location(targetDoc.uri, linkedSymbol.selectionRange) ); return new ProposedPosition(linkedSymbol.leadingCommentStart, { relativeTo: linkedSymbol.range, before: true }); } } } } private async findPositionForMemberFunction( symbol: CSymbol, parentClass?: CSymbol, access?: util.AccessLevel ): Promise<ProposedPosition | undefined> { if (!access) { access = util.AccessLevel.public; } if (parentClass) { return parentClass.findPositionForNewMemberFunction(access); } const immediateScope = symbol.immediateScope(); if (immediateScope) { const parentClassLocation = await immediateScope.findDefinition(); if (parentClassLocation?.uri.fsPath === this.uri.fsPath) { parentClass = await this.getSymbol(parentClassLocation.range.start); if (parentClass?.isClassType()) { return parentClass.findPositionForNewMemberFunction(access); } } } } private async findPositionInParentNamespace(symbol: CSymbol): Promise<ProposedPosition | undefined> { let previousChild = symbol; for (const scope of symbol.scopes().reverse()) { if (scope.isNamespace()) { const targetNamespace = await this.findMatchingSymbol(scope); if (targetNamespace) { if (targetNamespace.children.length === 0) { return new ProposedPosition(targetNamespace.bodyStart(), { after: true, indent: previousChild.trueStart.character > scope.trueStart.character }); } const lastChild = new CSymbol(targetNamespace.children[targetNamespace.children.length - 1], this); return new ProposedPosition(lastChild.trailingCommentEnd(), { relativeTo: lastChild.range, after: true }); } } if (!scope.isQualifiedNamespace()) { previousChild = scope; } } } private positionAfterLastSymbol(symbols: SourceSymbol[]): ProposedPosition { if (symbols.length > 0) { const lastSymbol = new CSymbol(symbols[symbols.length - 1], this); return new ProposedPosition(lastSymbol.trailingCommentEnd(), { relativeTo: lastSymbol.range, after: true }); } return util.positionAfterLastNonEmptyLine(this); } private async findDefinition(symbol: SourceSymbol): Promise<vscode.Location | undefined> { const definition = this.proposedDefinitions.get(symbol.selectionRange.start); if (definition) { return definition; } return symbol.findDefinition(); } private static siblingFunctions(symbol: SourceSymbol, topLevelSymbols: SourceSymbol[]): SourceSymbol[] { return (symbol.parent ? symbol.parent.children : topLevelSymbols).filter(sibling => { return sibling.isFunction(); }); } private static indexOfSymbol(symbol: SourceSymbol, siblings: SourceSymbol[]): number { const declarationSelectionRange = symbol.selectionRange; return siblings.findIndex(sibling => { return sibling.selectionRange.start.isEqual(declarationSelectionRange.start); }); } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace LuckyStar { namespace FormAccount { interface Header extends DevKit.Controls.IHeader { /** Type the number of employees that work at the account for use in marketing segmentation and demographic analysis. */ NumberOfEmployees: DevKit.Controls.Integer; /** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */ OwnerId: DevKit.Controls.Lookup; /** Type the annual revenue for the account, used as an indicator in financial performance analysis. */ Revenue: DevKit.Controls.Money; } interface tab_SUMMARY_TAB_Sections { ACCOUNT_INFORMATION: DevKit.Controls.Section; ADDRESS: DevKit.Controls.Section; MapSection: DevKit.Controls.Section; SOCIAL_PANE_TAB: DevKit.Controls.Section; Summary_section_6: DevKit.Controls.Section; SUMMARY_TAB_section_6: DevKit.Controls.Section; } interface tab_DETAILS_TAB_Sections { COMPANY_PROFILE: DevKit.Controls.Section; DETAILS_TAB_section_6: DevKit.Controls.Section; CONTACT_PREFERENCES: DevKit.Controls.Section; BILLING: DevKit.Controls.Section; SHIPPING: DevKit.Controls.Section; ChildAccounts: DevKit.Controls.Section; } interface tab__64BC19B9_1311_4B93_BE4C_6407B98D2AB3_Sections { _64BC19B9_1311_4B93_BE4C_6407B98D2AB4: DevKit.Controls.Section; } interface tab_SUMMARY_TAB extends DevKit.Controls.ITab { Section: tab_SUMMARY_TAB_Sections; } interface tab_DETAILS_TAB extends DevKit.Controls.ITab { Section: tab_DETAILS_TAB_Sections; } interface tab__64BC19B9_1311_4B93_BE4C_6407B98D2AB3 extends DevKit.Controls.ITab { Section: tab__64BC19B9_1311_4B93_BE4C_6407B98D2AB3_Sections; } interface Tabs { SUMMARY_TAB: tab_SUMMARY_TAB; DETAILS_TAB: tab_DETAILS_TAB; _64BC19B9_1311_4B93_BE4C_6407B98D2AB3: tab__64BC19B9_1311_4B93_BE4C_6407B98D2AB3; } interface Body { Tab: Tabs; mapcontrol: DevKit.Controls.Map; notescontrol: DevKit.Controls.Note; ActionCards: DevKit.Controls.ActionCards; /** Shows the complete primary address. */ Address1_Composite: DevKit.Controls.String; /** Select the freight terms for the primary address to make sure shipping orders are processed correctly. */ Address1_FreightTermsCode: DevKit.Controls.OptionSet; /** Select a shipping method for deliveries sent to this address. */ Address1_ShippingMethodCode: DevKit.Controls.OptionSet; /** Type the credit limit of the account. This is a useful reference when you address invoice and accounting issues with the customer. */ CreditLimit: DevKit.Controls.Money; /** Select whether the credit for the account is on hold. This is a useful reference while addressing the invoice and accounting issues with the customer. */ CreditOnHold: DevKit.Controls.Boolean; /** Type additional information to describe the account, such as an excerpt from the company's website. */ Description: DevKit.Controls.String; /** Select whether the account allows bulk email sent through campaigns. If Do Not Allow is selected, the account can be added to marketing lists, but is excluded from email. */ DoNotBulkEMail: DevKit.Controls.Boolean; /** Select whether the account allows direct email sent from Microsoft Dynamics 365. */ DoNotEMail: DevKit.Controls.Boolean; /** Select whether the account allows faxes. If Do Not Allow is selected, the account will be excluded from fax activities distributed in marketing campaigns. */ DoNotFax: DevKit.Controls.Boolean; /** Select whether the account allows phone calls. If Do Not Allow is selected, the account will be excluded from phone call activities distributed in marketing campaigns. */ DoNotPhone: DevKit.Controls.Boolean; /** Select whether the account allows direct mail. If Do Not Allow is selected, the account will be excluded from letter activities distributed in marketing campaigns. */ DoNotPostalMail: DevKit.Controls.Boolean; /** Type the fax number for the account. */ Fax: DevKit.Controls.String; /** Information about whether to allow following email activity like opens, attachment views and link clicks for emails sent to the account. */ FollowEmail: DevKit.Controls.Boolean; /** Select the account's primary industry for use in marketing segmentation and demographic analysis. */ IndustryCode: DevKit.Controls.OptionSet; /** Type the company or business name. */ Name: DevKit.Controls.String; /** Type the company or business name. */ Name_1: DevKit.Controls.String; /** Select the account's ownership structure, such as public or private. */ OwnershipCode: DevKit.Controls.OptionSet; /** Choose the parent account associated with this account to show parent and child businesses in reporting and analytics. */ ParentAccountId: DevKit.Controls.Lookup; /** Select the payment terms to indicate when the customer needs to pay the total amount. */ PaymentTermsCode: DevKit.Controls.OptionSet; /** Select the preferred method of contact. */ PreferredContactMethodCode: DevKit.Controls.OptionSet; /** Choose the primary contact for the account to provide quick access to contact details. */ PrimaryContactId: DevKit.Controls.Lookup; /** Type the Standard Industrial Classification (SIC) code that indicates the account's primary industry of business, for use in marketing segmentation and demographic analysis. */ SIC: DevKit.Controls.String; /** Type the main phone number for this account. */ Telephone1: DevKit.Controls.String; /** Type the stock exchange symbol for the account to track financial performance of the company. You can click the code entered in this field to access the latest trading information from MSN Money. */ TickerSymbol: DevKit.Controls.String; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; /** Type the account's website URL to get quick details about the company profile. */ WebSiteURL: DevKit.Controls.String; } interface Navigation { nav_devkit_account_devkit_webapi_Customer: DevKit.Controls.NavigationItem } interface quickForm_contactquickform_Body { EMailAddress1: DevKit.Controls.QuickView; Telephone1: DevKit.Controls.QuickView; } interface quickForm_contactquickform extends DevKit.Controls.IQuickView { Body: quickForm_contactquickform_Body; } interface QuickForm { contactquickform: quickForm_contactquickform; } interface ProcessBPF_Account_3 { /** Type an number or code for the account to quickly search and identify the account in system views. */ AccountNumber: DevKit.Controls.String; /** Type the company or business name. */ Name: DevKit.Controls.String; } interface ProcessBPF_Account_1 { /** Select a category to indicate whether the customer account is standard or preferred. */ AccountCategoryCode: DevKit.Controls.OptionSet; /** Type an number or code for the account to quickly search and identify the account in system views. */ AccountNumber: DevKit.Controls.String; /** Type the company or business name. */ Name: DevKit.Controls.String; /** Type the main phone number for this account. */ Telephone1: DevKit.Controls.String; /** Type a second phone number for this account. */ Telephone2: DevKit.Controls.String; } interface Process extends DevKit.Controls.IProcess { BPF_Account_3: ProcessBPF_Account_3; BPF_Account_1: ProcessBPF_Account_1; } interface Grid { ChildAccounts: DevKit.Controls.Grid; Contacts: DevKit.Controls.Grid; } } class FormAccount extends DevKit.IForm { /** * DynamicsCrm.DevKit form Account * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Account */ Body: LuckyStar.FormAccount.Body; /** The Header section of form Account */ Header: LuckyStar.FormAccount.Header; /** The Navigation of form Account */ Navigation: LuckyStar.FormAccount.Navigation; /** The QuickForm of form Account */ QuickForm: LuckyStar.FormAccount.QuickForm; /** The Process of form Account */ Process: LuckyStar.FormAccount.Process; /** The Grid of form Account */ Grid: LuckyStar.FormAccount.Grid; } namespace FormAccount_Quick_Create { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; tab_1_column_2_section_1: DevKit.Controls.Section; tab_1_column_3_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Type the city for the primary address. */ Address1_City: DevKit.Controls.String; /** Type the first line of the primary address. */ Address1_Line1: DevKit.Controls.String; /** Type the second line of the primary address. */ Address1_Line2: DevKit.Controls.String; /** Type the ZIP Code or postal code for the primary address. */ Address1_PostalCode: DevKit.Controls.String; /** Type additional information to describe the account, such as an excerpt from the company's website. */ Description: DevKit.Controls.String; /** Type the company or business name. */ Name: DevKit.Controls.String; /** Type the number of employees that work at the account for use in marketing segmentation and demographic analysis. */ NumberOfEmployees: DevKit.Controls.Integer; /** Choose the primary contact for the account to provide quick access to contact details. */ PrimaryContactId: DevKit.Controls.Lookup; /** Type the annual revenue for the account, used as an indicator in financial performance analysis. */ Revenue: DevKit.Controls.Money; /** Type the main phone number for this account. */ Telephone1: DevKit.Controls.String; } } class FormAccount_Quick_Create extends DevKit.IForm { /** * DynamicsCrm.DevKit form Account_Quick_Create * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** Provides properties and methods to use Web API to create and manage records and execute Web API actions and functions in Customer Engagement */ WebApi: DevKit.WebApi; /** The Body section of form Account_Quick_Create */ Body: LuckyStar.FormAccount_Quick_Create.Body; } class AccountApi { /** * DynamicsCrm.DevKit AccountApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Select a category to indicate whether the customer account is standard or preferred. */ AccountCategoryCode: DevKit.WebApi.OptionSetValue; /** Select a classification code to indicate the potential value of the customer account based on the projected return on investment, cooperation level, sales cycle length or other criteria. */ AccountClassificationCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the account. */ AccountId: DevKit.WebApi.GuidValue; /** Type an number or code for the account to quickly search and identify the account in system views. */ AccountNumber: DevKit.WebApi.StringValue; /** Select a rating to indicate the value of the customer account. */ AccountRatingCode: DevKit.WebApi.OptionSetValue; /** Unique identifier for address 1. */ Address1_AddressId: DevKit.WebApi.GuidValue; /** Select the primary address type. */ Address1_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** Type the city for the primary address. */ Address1_City: DevKit.WebApi.StringValue; /** Shows the complete primary address. */ Address1_Composite: DevKit.WebApi.StringValueReadonly; /** Type the country or region for the primary address. */ Address1_Country: DevKit.WebApi.StringValue; /** Type the county for the primary address. */ Address1_County: DevKit.WebApi.StringValue; /** Type the fax number associated with the primary address. */ Address1_Fax: DevKit.WebApi.StringValue; /** Select the freight terms for the primary address to make sure shipping orders are processed correctly. */ Address1_FreightTermsCode: DevKit.WebApi.OptionSetValue; /** Type the latitude value for the primary address for use in mapping and other applications. */ Address1_Latitude: DevKit.WebApi.DoubleValue; /** Type the first line of the primary address. */ Address1_Line1: DevKit.WebApi.StringValue; /** Type the second line of the primary address. */ Address1_Line2: DevKit.WebApi.StringValue; /** Type the third line of the primary address. */ Address1_Line3: DevKit.WebApi.StringValue; /** Type the longitude value for the primary address for use in mapping and other applications. */ Address1_Longitude: DevKit.WebApi.DoubleValue; /** Type a descriptive name for the primary address, such as Corporate Headquarters. */ Address1_Name: DevKit.WebApi.StringValue; /** Type the ZIP Code or postal code for the primary address. */ Address1_PostalCode: DevKit.WebApi.StringValue; /** Type the post office box number of the primary address. */ Address1_PostOfficeBox: DevKit.WebApi.StringValue; /** Type the name of the main contact at the account's primary address. */ Address1_PrimaryContactName: DevKit.WebApi.StringValue; /** Select a shipping method for deliveries sent to this address. */ Address1_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** Type the state or province of the primary address. */ Address1_StateOrProvince: DevKit.WebApi.StringValue; /** Type the main phone number associated with the primary address. */ Address1_Telephone1: DevKit.WebApi.StringValue; /** Type a second phone number associated with the primary address. */ Address1_Telephone2: DevKit.WebApi.StringValue; /** Type a third phone number associated with the primary address. */ Address1_Telephone3: DevKit.WebApi.StringValue; /** Type the UPS zone of the primary address to make sure shipping charges are calculated correctly and deliveries are made promptly, if shipped by UPS. */ Address1_UPSZone: DevKit.WebApi.StringValue; /** Select the time zone, or UTC offset, for this address so that other people can reference it when they contact someone at this address. */ Address1_UTCOffset: DevKit.WebApi.IntegerValue; /** Unique identifier for address 2. */ Address2_AddressId: DevKit.WebApi.GuidValue; /** Select the secondary address type. */ Address2_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** Type the city for the secondary address. */ Address2_City: DevKit.WebApi.StringValue; /** Shows the complete secondary address. */ Address2_Composite: DevKit.WebApi.StringValueReadonly; /** Type the country or region for the secondary address. */ Address2_Country: DevKit.WebApi.StringValue; /** Type the county for the secondary address. */ Address2_County: DevKit.WebApi.StringValue; /** Type the fax number associated with the secondary address. */ Address2_Fax: DevKit.WebApi.StringValue; /** Select the freight terms for the secondary address to make sure shipping orders are processed correctly. */ Address2_FreightTermsCode: DevKit.WebApi.OptionSetValue; /** Type the latitude value for the secondary address for use in mapping and other applications. */ Address2_Latitude: DevKit.WebApi.DoubleValue; /** Type the first line of the secondary address. */ Address2_Line1: DevKit.WebApi.StringValue; /** Type the second line of the secondary address. */ Address2_Line2: DevKit.WebApi.StringValue; /** Type the third line of the secondary address. */ Address2_Line3: DevKit.WebApi.StringValue; /** Type the longitude value for the secondary address for use in mapping and other applications. */ Address2_Longitude: DevKit.WebApi.DoubleValue; /** Type a descriptive name for the secondary address, such as Corporate Headquarters. */ Address2_Name: DevKit.WebApi.StringValue; /** Type the ZIP Code or postal code for the secondary address. */ Address2_PostalCode: DevKit.WebApi.StringValue; /** Type the post office box number of the secondary address. */ Address2_PostOfficeBox: DevKit.WebApi.StringValue; /** Type the name of the main contact at the account's secondary address. */ Address2_PrimaryContactName: DevKit.WebApi.StringValue; /** Select a shipping method for deliveries sent to this address. */ Address2_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** Type the state or province of the secondary address. */ Address2_StateOrProvince: DevKit.WebApi.StringValue; /** Type the main phone number associated with the secondary address. */ Address2_Telephone1: DevKit.WebApi.StringValue; /** Type a second phone number associated with the secondary address. */ Address2_Telephone2: DevKit.WebApi.StringValue; /** Type a third phone number associated with the secondary address. */ Address2_Telephone3: DevKit.WebApi.StringValue; /** Type the UPS zone of the secondary address to make sure shipping charges are calculated correctly and deliveries are made promptly, if shipped by UPS. */ Address2_UPSZone: DevKit.WebApi.StringValue; /** Select the time zone, or UTC offset, for this address so that other people can reference it when they contact someone at this address. */ Address2_UTCOffset: DevKit.WebApi.IntegerValue; /** For system use only. */ Aging30: DevKit.WebApi.MoneyValueReadonly; /** The base currency equivalent of the aging 30 field. */ Aging30_Base: DevKit.WebApi.MoneyValueReadonly; /** For system use only. */ Aging60: DevKit.WebApi.MoneyValueReadonly; /** The base currency equivalent of the aging 60 field. */ Aging60_Base: DevKit.WebApi.MoneyValueReadonly; /** For system use only. */ Aging90: DevKit.WebApi.MoneyValueReadonly; /** The base currency equivalent of the aging 90 field. */ Aging90_Base: DevKit.WebApi.MoneyValueReadonly; /** Select the legal designation or other business type of the account for contracts or reporting purposes. */ BusinessTypeCode: DevKit.WebApi.OptionSetValue; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the external party who created the record. */ CreatedByExternalParty: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type the credit limit of the account. This is a useful reference when you address invoice and accounting issues with the customer. */ CreditLimit: DevKit.WebApi.MoneyValue; /** Shows the credit limit converted to the system's default base currency for reporting purposes. */ CreditLimit_Base: DevKit.WebApi.MoneyValueReadonly; /** Select whether the credit for the account is on hold. This is a useful reference while addressing the invoice and accounting issues with the customer. */ CreditOnHold: DevKit.WebApi.BooleanValue; /** Select the size category or range of the account for segmentation and reporting purposes. */ CustomerSizeCode: DevKit.WebApi.OptionSetValue; /** Select the category that best describes the relationship between the account and your organization. */ CustomerTypeCode: DevKit.WebApi.OptionSetValue; /** Type additional information to describe the account, such as an excerpt from the company's website. */ Description: DevKit.WebApi.StringValue; devkit_LocationId: DevKit.WebApi.LookupValue; /** Select whether the account allows bulk email sent through campaigns. If Do Not Allow is selected, the account can be added to marketing lists, but is excluded from email. */ DoNotBulkEMail: DevKit.WebApi.BooleanValue; /** Select whether the account allows bulk postal mail sent through marketing campaigns or quick campaigns. If Do Not Allow is selected, the account can be added to marketing lists, but will be excluded from the postal mail. */ DoNotBulkPostalMail: DevKit.WebApi.BooleanValue; /** Select whether the account allows direct email sent from Microsoft Dynamics 365. */ DoNotEMail: DevKit.WebApi.BooleanValue; /** Select whether the account allows faxes. If Do Not Allow is selected, the account will be excluded from fax activities distributed in marketing campaigns. */ DoNotFax: DevKit.WebApi.BooleanValue; /** Select whether the account allows phone calls. If Do Not Allow is selected, the account will be excluded from phone call activities distributed in marketing campaigns. */ DoNotPhone: DevKit.WebApi.BooleanValue; /** Select whether the account allows direct mail. If Do Not Allow is selected, the account will be excluded from letter activities distributed in marketing campaigns. */ DoNotPostalMail: DevKit.WebApi.BooleanValue; /** Select whether the account accepts marketing materials, such as brochures or catalogs. */ DoNotSendMM: DevKit.WebApi.BooleanValue; /** Type the primary email address for the account. */ EMailAddress1: DevKit.WebApi.StringValue; /** Type the secondary email address for the account. */ EMailAddress2: DevKit.WebApi.StringValue; /** Type an alternate email address for the account. */ EMailAddress3: DevKit.WebApi.StringValue; /** Shows the default image for the record. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Type the fax number for the account. */ Fax: DevKit.WebApi.StringValue; /** Information about whether to allow following email activity like opens, attachment views and link clicks for emails sent to the account. */ FollowEmail: DevKit.WebApi.BooleanValue; /** Type the URL for the account's FTP site to enable users to access data and share documents. */ FtpSiteURL: DevKit.WebApi.StringValue; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Select the account's primary industry for use in marketing segmentation and demographic analysis. */ IndustryCode: DevKit.WebApi.OptionSetValue; IsPrivate: DevKit.WebApi.BooleanValueReadonly; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the date when the account was last included in a marketing campaign or quick campaign. */ LastUsedInCampaign_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Type the market capitalization of the account to identify the company's equity, used as an indicator in financial performance analysis. */ MarketCap: DevKit.WebApi.MoneyValue; /** Shows the market capitalization converted to the system's default base currency. */ MarketCap_Base: DevKit.WebApi.MoneyValueReadonly; /** Whether is only for marketing */ MarketingOnly: DevKit.WebApi.BooleanValue; MasterAccountIdName: DevKit.WebApi.StringValueReadonly; /** Shows the master account that the account was merged with. */ MasterId: DevKit.WebApi.LookupValueReadonly; /** Shows whether the account has been merged with another account. */ Merged: DevKit.WebApi.BooleanValueReadonly; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the external party who modified the record. */ ModifiedByExternalParty: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Type the company or business name. */ Name: DevKit.WebApi.StringValue; /** Type the number of employees that work at the account for use in marketing segmentation and demographic analysis. */ NumberOfEmployees: DevKit.WebApi.IntegerValue; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Select the account's ownership structure, such as public or private. */ OwnershipCode: DevKit.WebApi.OptionSetValue; /** Shows the business unit that the record owner belongs to. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the account. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the account. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Choose the parent account associated with this account to show parent and child businesses in reporting and analytics. */ ParentAccountId: DevKit.WebApi.LookupValue; /** For system use only. Legacy Microsoft Dynamics CRM 3.0 workflow data. */ ParticipatesInWorkflow: DevKit.WebApi.BooleanValue; /** Select the payment terms to indicate when the customer needs to pay the total amount. */ PaymentTermsCode: DevKit.WebApi.OptionSetValue; /** Select the preferred day of the week for service appointments. */ PreferredAppointmentDayCode: DevKit.WebApi.OptionSetValue; /** Select the preferred time of day for service appointments. */ PreferredAppointmentTimeCode: DevKit.WebApi.OptionSetValue; /** Select the preferred method of contact. */ PreferredContactMethodCode: DevKit.WebApi.OptionSetValue; /** Choose the preferred service representative for reference when you schedule service activities for the account. */ PreferredSystemUserId: DevKit.WebApi.LookupValue; /** Choose the primary contact for the account to provide quick access to contact details. */ PrimaryContactId: DevKit.WebApi.LookupValue; /** Primary Satori ID for Account */ PrimarySatoriId: DevKit.WebApi.StringValue; /** Primary Twitter ID for Account */ PrimaryTwitterId: DevKit.WebApi.StringValue; /** Shows the ID of the process. */ ProcessId: DevKit.WebApi.GuidValue; /** Type the annual revenue for the account, used as an indicator in financial performance analysis. */ Revenue: DevKit.WebApi.MoneyValue; /** Shows the annual revenue converted to the system's default base currency. The calculations use the exchange rate specified in the Currencies area. */ Revenue_Base: DevKit.WebApi.MoneyValueReadonly; /** Type the number of shares available to the public for the account. This number is used as an indicator in financial performance analysis. */ SharesOutstanding: DevKit.WebApi.IntegerValue; /** Select a shipping method for deliveries sent to the account's address to designate the preferred carrier or other delivery option. */ ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** Type the Standard Industrial Classification (SIC) code that indicates the account's primary industry of business, for use in marketing segmentation and demographic analysis. */ SIC: DevKit.WebApi.StringValue; /** Choose the service level agreement (SLA) that you want to apply to the Account record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this case. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the ID of the stage. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the account is active or inactive. Inactive accounts are read-only and can't be edited unless they are reactivated. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the account's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Type the stock exchange at which the account is listed to track their stock and financial performance of the company. */ StockExchange: DevKit.WebApi.StringValue; /** Type the main phone number for this account. */ Telephone1: DevKit.WebApi.StringValue; /** Type a second phone number for this account. */ Telephone2: DevKit.WebApi.StringValue; /** Type a third phone number for this account. */ Telephone3: DevKit.WebApi.StringValue; /** Select a region or territory for the account for use in segmentation and analysis. */ TerritoryCode: DevKit.WebApi.OptionSetValue; /** Type the stock exchange symbol for the account to track financial performance of the company. You can click the code entered in this field to access the latest trading information from MSN Money. */ TickerSymbol: DevKit.WebApi.StringValue; /** Total time spent for emails (read and write) and meetings by me in relation to account record. */ TimeSpentByMeOnEmailAndMeetings: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the account. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** Type the account's website URL to get quick details about the company profile. */ WebSiteURL: DevKit.WebApi.StringValue; /** Type the phonetic spelling of the company name, if specified in Japanese, to make sure the name is pronounced correctly in phone calls and other communications. */ YomiName: DevKit.WebApi.StringValue; } } declare namespace OptionSet { namespace Account { enum AccountCategoryCode { /** 100000001 */ Other, /** 1 */ Preferred_Customer, /** 2 */ Standard_2, /** 3 */ Standard_3 } enum AccountClassificationCode { /** 1 */ Default_Value } enum AccountRatingCode { /** 1 */ Default_Value } enum Address1_AddressTypeCode { /** 1 */ Bill_To, /** 4 */ Other, /** 3 */ Primary, /** 2 */ Ship_To } enum Address1_FreightTermsCode { /** 1 */ FOB, /** 2 */ No_Charge } enum Address1_ShippingMethodCode { /** 1 */ Airborne, /** 2 */ DHL, /** 3 */ FedEx, /** 6 */ Full_Load, /** 5 */ Postal_Mail, /** 4 */ UPS, /** 7 */ Will_Call } enum Address2_AddressTypeCode { /** 1 */ Default_Value } enum Address2_FreightTermsCode { /** 1 */ Default_Value } enum Address2_ShippingMethodCode { /** 1 */ Default_Value } enum BusinessTypeCode { /** 1 */ Default_Value } enum CustomerSizeCode { /** 1 */ Default_Value } enum CustomerTypeCode { /** 1 */ Competitor, /** 2 */ Consultant, /** 3 */ Customer, /** 6 */ Influencer, /** 4 */ Investor, /** 12 */ Other, /** 5 */ Partner, /** 7 */ Press, /** 8 */ Prospect, /** 9 */ Reseller, /** 10 */ Supplier, /** 11 */ Vendor } enum IndustryCode { /** 1 */ Accounting, /** 2 */ Agriculture_and_Non_petrol_Natural_Resource_Extraction, /** 3 */ Broadcasting_Printing_and_Publishing, /** 4 */ Brokers, /** 5 */ Building_Supply_Retail, /** 6 */ Business_Services, /** 7 */ Consulting, /** 8 */ Consumer_Services, /** 9 */ Design_Direction_and_Creative_Management, /** 10 */ Distributors_Dispatchers_and_Processors, /** 11 */ Doctors_Offices_and_Clinics, /** 12 */ Durable_Manufacturing, /** 13 */ Eating_and_Drinking_Places, /** 14 */ Entertainment_Retail, /** 15 */ Equipment_Rental_and_Leasing, /** 16 */ Financial, /** 17 */ Food_and_Tobacco_Processing, /** 18 */ Inbound_Capital_Intensive_Processing, /** 19 */ Inbound_Repair_and_Services, /** 20 */ Insurance, /** 21 */ Legal_Services, /** 22 */ Non_Durable_Merchandise_Retail, /** 23 */ Outbound_Consumer_Service, /** 24 */ Petrochemical_Extraction_and_Distribution, /** 25 */ Service_Retail, /** 26 */ SIG_Affiliations, /** 27 */ Social_Services, /** 28 */ Special_Outbound_Trade_Contractors, /** 29 */ Specialty_Realty, /** 30 */ Transportation, /** 31 */ Utility_Creation_and_Distribution, /** 32 */ Vehicle_Retail, /** 33 */ Wholesale } enum OwnershipCode { /** 4 */ Other, /** 2 */ Private, /** 1 */ Public, /** 3 */ Subsidiary } enum PaymentTermsCode { /** 2 */ _2_10_Net_30, /** 1 */ Net_30, /** 3 */ Net_45, /** 4 */ Net_60 } enum PreferredAppointmentDayCode { /** 5 */ Friday, /** 1 */ Monday, /** 6 */ Saturday, /** 0 */ Sunday, /** 4 */ Thursday, /** 2 */ Tuesday, /** 3 */ Wednesday } enum PreferredAppointmentTimeCode { /** 2 */ Afternoon, /** 3 */ Evening, /** 1 */ Morning } enum PreferredContactMethodCode { /** 1 */ Any, /** 2 */ Email, /** 4 */ Fax, /** 5 */ Mail, /** 3 */ Phone } enum ShippingMethodCode { /** 1 */ Default_Value } enum StateCode { /** 0 */ Active, /** 1 */ Inactive } enum StatusCode { /** 1 */ Active, /** 2 */ Inactive } enum TerritoryCode { /** 1 */ Default_Value } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Account','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.10.31','JsFormVersion':'v2'}
the_stack
import { Observable } from 'rxjs'; import { makeExecutableSchema } from 'graphql-tools'; import { executeRx, subscribeRx, graphqlRx, prepareSchema, validate, } from '..'; import { parse, introspectionQuery, GraphQLInt, GraphQLSchema, GraphQLObjectType, } from 'graphql'; import 'jest'; const counterSource = Observable.interval(10); describe('graphql-rxjs import tests', () => { it("can work with graphql-tools", () => { const typeDefs = ` # Root Subscription type Query { someInt: Int } `; const resolvers = { Query: { someInt(root, args, ctx) { return Observable.of(1); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); const query = ` query { someInt } `; return graphqlRx(scheme, query) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it("introspectionQuery works as expected", () => { const typeDefs = ` # Root Subscription type Query { someInt: Int } `; const resolvers = { Query: { someInt(root, args, ctx) { return Observable.of(1); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); return graphqlRx(scheme, introspectionQuery) .take(1) .toPromise().then((values) => { expect(values.errors).toBeUndefined(); expect(values.data).toMatchSnapshot(); }); }); it("also works with vanilla graphql objects", () => { const QueryType = new GraphQLObjectType({ name: 'Query', fields: { someInt: { type: GraphQLInt, resolve: (root, args, ctx) => { return Observable.of(123); }, } } }); const scheme = new GraphQLSchema({ query: QueryType, }); prepareSchema(scheme); const query = ` query { someInt } `; return graphqlRx(scheme, query, null) .bufferCount(3) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it("can also query static values", () => { const QueryType = new GraphQLObjectType({ name: 'Query', fields: { someInt: { type: GraphQLInt, resolve: (root, args, ctx) => { return 123321; }, } } }); const scheme = new GraphQLSchema({ query: QueryType, }); prepareSchema(scheme); const query = ` query { someInt } `; return graphqlRx(scheme, query) .bufferCount(3) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it("unsubscribe from observable as expected", () => { let unsubscribe = false; const QueryType = new GraphQLObjectType({ name: 'Query', fields: { counter: { type: GraphQLInt, resolve: (root, args, ctx) => { return new Observable((observer) => { let i = 0; const to = setInterval(() => { try { expect(unsubscribe).toBe(false); if ( i >= 15 ) { return; } observer.next(i); i ++; } catch (e) { observer.error(e); } }, 10); return () => { unsubscribe = true; clearInterval(to); }; }); }, } } }); const scheme = new GraphQLSchema({ query: QueryType, }); prepareSchema(scheme); const query = ` query { counter @live } `; return graphqlRx(scheme, query, null) .bufferCount(10) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); expect(unsubscribe).toBe(true); }); }); it("able to add reactive directives to schema", () => { const QueryType = new GraphQLObjectType({ name: 'Query', fields: { counter: { type: GraphQLInt, resolve: (root, args, ctx) => { return Observable.interval(10); }, } } }); const scheme = new GraphQLSchema({ query: QueryType, }); prepareSchema(scheme); const query = ` query { counter @live } `; return graphqlRx(scheme, query, null) .bufferCount(10) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it("reactive directives works without prepareSchema", () => { const QueryType = new GraphQLObjectType({ name: 'Query', fields: { counter: { type: GraphQLInt, resolve: (root, args, ctx) => { return Observable.interval(10); }, } } }); const scheme = new GraphQLSchema({ query: QueryType, }); const query = ` query { counter @live } `; return graphqlRx(scheme, query, null) .bufferCount(10) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it("also works for subscriptions", () => { const SubscriptionType = new GraphQLObjectType({ name: 'Subscription', fields: { counter: { type: GraphQLInt, resolve: (root) => root, subscribe: (root, args, ctx) => { return ctx.counterSource; }, } } }); const QueryType = new GraphQLObjectType({ name: 'Query', fields: { someInt: { type: GraphQLInt, resolve: (root, args, ctx) => { return 123321; }, } } }); const scheme = new GraphQLSchema({ query: QueryType, subscription: SubscriptionType, }); prepareSchema(scheme); const query = ` subscription { counter } `; return graphqlRx(scheme, query, null, { counterSource }) .bufferCount(3) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); }); describe('import-tests Rx Engines', () => { it('subscribeRx works as expected', () => { const SubscriptionType = new GraphQLObjectType({ name: 'Subscription', fields: { counter: { type: GraphQLInt, resolve: (root) => root, subscribe: (root, args, ctx) => { return ctx.counterSource; }, } } }); const QueryType = new GraphQLObjectType({ name: 'Query', fields: { someInt: { type: GraphQLInt, resolve: (root, args, ctx) => { return 123321; }, } } }); const scheme = new GraphQLSchema({ query: QueryType, subscription: SubscriptionType, }); prepareSchema(scheme); const query = ` subscription { counter } `; return subscribeRx(scheme, parse(query), null, { counterSource }) .bufferCount(3) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it('executeRx works as expected', () => { const typeDefs = ` # Root Subscription type Query { someInt: Int } `; const resolvers = { Query: { someInt(root, args, ctx) { return Observable.of(1); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); const query = ` query { someInt } `; return executeRx(scheme, parse(query)) .take(1) .toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it("validation works as expected", () => { const typeDefs = ` type Query { someInt: Int } `; const resolvers = { Query: { someInt(root, args, ctx) { return Observable.of(1); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); const query = parse(` query { someInt @defer } `); const validationErrors = validate(scheme, query); expect(validationErrors).toHaveLength(0); return executeRx(scheme, query) .toArray().toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it("mutation is not allowed to use reactive directives", () => { const typeDefs = ` type Query { someInt: Int } type Mutation { shouldntDefer: Int } `; const resolvers = { Query: { someInt(root, args, ctx) { return Observable.of(1); }, }, Mutation: { shouldntDefer(root, args, ctx) { return Promise.resolve(1); } } }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); const query = ` mutation { shouldntDefer @defer } `; return graphqlRx(scheme, query) .toArray().toPromise().then((values) => { expect(values).toMatchSnapshot(); }); }); it("nested @live unsubscribes as expected", () => { const obs = []; const typeDefs = ` type Nested { root: Int liveInt: Int } type Query { nestedType: Nested } `; const trackObservable = (observable) => new Observable((observer) => { const sub = observable.subscribe(observer); const id = obs.length; obs.push(true); return () => { obs[id] = false; sub.unsubscribe(); }; }); const resolvers = { Nested: { root(root) { return root; }, liveInt(root, args, ctx) { return trackObservable(Observable.interval(20).map((i) => i * root)); } }, Query: { nestedType(root, args, ctx) { return trackObservable(Observable.interval(100).skip(1)); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); const query = ` query { nestedType @live { root liveInt @live } } `; return graphqlRx(scheme, query) .map((v) => v.data.nestedType) .take(10) .toArray().toPromise().then((values) => { // If something left it means unsubscribe was not called for it. expect(obs .map((v, i) => ({ v, i })) .filter((m) => m.v) .map((m) => m.i) ).toHaveLength(0); expect(values).toMatchSnapshot(); }); }); it("nested @live with lists unsubscribes as expected", () => { const obs = []; const typeDefs = ` type Nested { root: Int liveInt: Int } type Query { nestedType: [Nested] } `; const trackObservable = (observable) => new Observable((observer) => { const sub = observable.subscribe(observer); const id = obs.length; obs.push(true); return () => { obs[id] = false; sub.unsubscribe(); }; }); const resolvers = { Nested: { root(root) { return root; }, liveInt(root, args, ctx) { return trackObservable(Observable.interval(20).map((i) => i * root)); } }, Query: { nestedType(root, args, ctx) { return trackObservable(Observable.interval(100).skip(1).scan((o, v) => [...o, v], [])); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); const query = ` query { nestedType @live { root liveInt @live } } `; return graphqlRx(scheme, query) .map((v) => v.data.nestedType) .take(10) .toArray().toPromise().then((values) => { // If something left it means unsubscribe was not called for it. expect(obs .map((v, i) => ({ v, i })) .filter((m) => m.v) .map((m) => m.i) ).toHaveLength(0); expect(values).toMatchSnapshot(); }); }); it("nested @live as expected", () => { const obs = []; const typeDefs = ` type FinalObject { root: Int value: Int } type Nested { root: Int liveInt: FinalObject } type Query { nestedType: [Nested] } `; const trackObservable = (observable) => new Observable((observer) => { const sub = observable.subscribe(observer); const id = obs.length; obs.push(true); return () => { obs[id] = false; sub.unsubscribe(); }; }); const resolvers = { FinalObject: { value: (root, args, ctx) => Observable.of(root.value), root: (root, args, ctx) => Observable.of(root.root), }, Nested: { root(root) { return root; }, liveInt(root, args, ctx) { return trackObservable(Observable.interval(20).map((i) => ({ root: root, value: i * root }))); } }, Query: { nestedType(root, args, ctx) { return trackObservable(new Observable((observer) => { observer.next([2]); })); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); const query = `query { nestedType @live { root liveInt @live { root value } } }`; return graphqlRx(scheme, query) .map((v) => v.data.nestedType) .take(10) .toArray().toPromise().then((values) => { // If something left it means unsubscribe was not called for it. expect(obs .map((v, i) => ({ v, i })) .filter((m) => m.v) .map((m) => m.i) ).toHaveLength(0); expect(values).toMatchSnapshot(); }); }); it("@live with infinate result sibling", () => { const obs = []; const typeDefs = ` type OtherType { value: String } type FinalObject { root: Int value: Int } type Nested { inf: OtherType liveInt: FinalObject } type Query { nestedType: [Nested] } `; const trackObservable = (observable) => new Observable((observer) => { const sub = observable.subscribe(observer); const id = obs.length; obs.push(true); return () => { obs[id] = false; sub.unsubscribe(); }; }); const resolvers = { OtherType: { value: (root) => Promise.resolve(root.value), }, Nested: { inf(root) { return trackObservable(new Observable((observer) => { observer.next({ value: root }); // No Complete. })); }, liveInt(root, args, ctx) { return trackObservable(Observable.interval(20).map((i) => ({ root: root, value: i * root }))); } }, Query: { nestedType(root, args, ctx) { return trackObservable(new Observable((observer) => { observer.next([2]); })); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); const query = `query mixedLive { nestedType @live { inf { value } liveInt { root value } } }`; return graphqlRx(scheme, query) .map((v) => v.data.nestedType) .take(10) .toArray().toPromise().then((values) => { // If something left it means unsubscribe was not called for it. expect(obs .map((v, i) => ({ v, i })) .filter((m) => m.v) .map((m) => m.i) ).toHaveLength(0); expect(values).toMatchSnapshot(); }); }); it("@live with infinate + static result sibling", () => { const obs = []; const typeDefs = ` type OtherType { value: String } type FinalObject { root: Int value: Int } type Nested { root: Int inf: OtherType liveInt: FinalObject } type Query { nestedType: [Nested] } `; const trackObservable = (observable) => new Observable((observer) => { const sub = observable.subscribe(observer); const id = obs.length; obs.push(true); return () => { obs[id] = false; sub.unsubscribe(); }; }); const resolvers = { OtherType: { value: (root) => Promise.resolve(root.value), }, Nested: { root(root) { return root; }, inf(root) { return trackObservable(new Observable((observer) => { observer.next({ value: root }); // No Complete. })); }, liveInt(root, args, ctx) { return trackObservable(Observable.interval(20).map((i) => ({ root: root, value: i * root }))); } }, Query: { nestedType(root, args, ctx) { return trackObservable(new Observable((observer) => { observer.next([2]); })); }, }, }; const scheme = makeExecutableSchema({typeDefs, resolvers}); prepareSchema(scheme); const query = `query mixedLive { nestedType @live { root inf { value } liveInt { root value } } }`; return graphqlRx(scheme, query) .map((v) => v.data.nestedType) .take(10) .toArray().toPromise().then((values) => { // If something left it means unsubscribe was not called for it. expect(obs .map((v, i) => ({ v, i })) .filter((m) => m.v) .map((m) => m.i) ).toHaveLength(0); expect(values).toMatchSnapshot(); }); }); });
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * ## Import * * Project-level logging sinks can be imported using their URI, e.g. * * ```sh * $ pulumi import gcp:logging/projectSink:ProjectSink my_sink projects/my-project/sinks/my-sink * ``` */ export class ProjectSink extends pulumi.CustomResource { /** * Get an existing ProjectSink resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ProjectSinkState, opts?: pulumi.CustomResourceOptions): ProjectSink { return new ProjectSink(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:logging/projectSink:ProjectSink'; /** * Returns true if the given object is an instance of ProjectSink. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ProjectSink { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ProjectSink.__pulumiType; } /** * Options that affect sinks exporting data to BigQuery. Structure documented below. */ public readonly bigqueryOptions!: pulumi.Output<outputs.logging.ProjectSinkBigqueryOptions>; /** * A description of this exclusion. */ public readonly description!: pulumi.Output<string | undefined>; /** * The destination of the sink (or, in other words, where logs are written to). Can be a * Cloud Storage bucket, a PubSub topic, a BigQuery dataset or a Cloud Logging bucket . Examples: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` * The writer associated with the sink must have access to write to the above resource. */ public readonly destination!: pulumi.Output<string>; /** * If set to True, then this exclusion is disabled and it does not exclude any log entries. */ public readonly disabled!: pulumi.Output<boolean | undefined>; /** * Log entries that match any of the exclusion filters will not be exported. If a log entry is matched by both filter and one of exclusionFilters it will not be exported. Can be repeated multiple times for multiple exclusions. Structure is documented below. */ public readonly exclusions!: pulumi.Output<outputs.logging.ProjectSinkExclusion[] | undefined>; /** * An advanced logs filter that matches the log entries to be excluded. By using the sample function, you can exclude less than 100% of the matching log entries. See [Advanced Log Filters](https://cloud.google.com/logging/docs/view/advanced_filters) for information on how to * write a filter. */ public readonly filter!: pulumi.Output<string | undefined>; /** * A client-assigned identifier, such as `load-balancer-exclusion`. Identifiers are limited to 100 characters and can include only letters, digits, underscores, hyphens, and periods. First character has to be alphanumeric. */ public readonly name!: pulumi.Output<string>; /** * The ID of the project to create the sink in. If omitted, the project associated with the provider is * used. */ public readonly project!: pulumi.Output<string>; /** * Whether or not to create a unique identity associated with this sink. If `false` * (the default), then the `writerIdentity` used is `serviceAccount:cloud-logs@system.gserviceaccount.com`. If `true`, * then a unique service account is created and used for this sink. If you wish to publish logs across projects or utilize * `bigqueryOptions`, you must set `uniqueWriterIdentity` to true. */ public readonly uniqueWriterIdentity!: pulumi.Output<boolean | undefined>; /** * The identity associated with this sink. This identity must be granted write access to the * configured `destination`. */ public /*out*/ readonly writerIdentity!: pulumi.Output<string>; /** * Create a ProjectSink resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ProjectSinkArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ProjectSinkArgs | ProjectSinkState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ProjectSinkState | undefined; inputs["bigqueryOptions"] = state ? state.bigqueryOptions : undefined; inputs["description"] = state ? state.description : undefined; inputs["destination"] = state ? state.destination : undefined; inputs["disabled"] = state ? state.disabled : undefined; inputs["exclusions"] = state ? state.exclusions : undefined; inputs["filter"] = state ? state.filter : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["uniqueWriterIdentity"] = state ? state.uniqueWriterIdentity : undefined; inputs["writerIdentity"] = state ? state.writerIdentity : undefined; } else { const args = argsOrState as ProjectSinkArgs | undefined; if ((!args || args.destination === undefined) && !opts.urn) { throw new Error("Missing required property 'destination'"); } inputs["bigqueryOptions"] = args ? args.bigqueryOptions : undefined; inputs["description"] = args ? args.description : undefined; inputs["destination"] = args ? args.destination : undefined; inputs["disabled"] = args ? args.disabled : undefined; inputs["exclusions"] = args ? args.exclusions : undefined; inputs["filter"] = args ? args.filter : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["uniqueWriterIdentity"] = args ? args.uniqueWriterIdentity : undefined; inputs["writerIdentity"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ProjectSink.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ProjectSink resources. */ export interface ProjectSinkState { /** * Options that affect sinks exporting data to BigQuery. Structure documented below. */ bigqueryOptions?: pulumi.Input<inputs.logging.ProjectSinkBigqueryOptions>; /** * A description of this exclusion. */ description?: pulumi.Input<string>; /** * The destination of the sink (or, in other words, where logs are written to). Can be a * Cloud Storage bucket, a PubSub topic, a BigQuery dataset or a Cloud Logging bucket . Examples: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` * The writer associated with the sink must have access to write to the above resource. */ destination?: pulumi.Input<string>; /** * If set to True, then this exclusion is disabled and it does not exclude any log entries. */ disabled?: pulumi.Input<boolean>; /** * Log entries that match any of the exclusion filters will not be exported. If a log entry is matched by both filter and one of exclusionFilters it will not be exported. Can be repeated multiple times for multiple exclusions. Structure is documented below. */ exclusions?: pulumi.Input<pulumi.Input<inputs.logging.ProjectSinkExclusion>[]>; /** * An advanced logs filter that matches the log entries to be excluded. By using the sample function, you can exclude less than 100% of the matching log entries. See [Advanced Log Filters](https://cloud.google.com/logging/docs/view/advanced_filters) for information on how to * write a filter. */ filter?: pulumi.Input<string>; /** * A client-assigned identifier, such as `load-balancer-exclusion`. Identifiers are limited to 100 characters and can include only letters, digits, underscores, hyphens, and periods. First character has to be alphanumeric. */ name?: pulumi.Input<string>; /** * The ID of the project to create the sink in. If omitted, the project associated with the provider is * used. */ project?: pulumi.Input<string>; /** * Whether or not to create a unique identity associated with this sink. If `false` * (the default), then the `writerIdentity` used is `serviceAccount:cloud-logs@system.gserviceaccount.com`. If `true`, * then a unique service account is created and used for this sink. If you wish to publish logs across projects or utilize * `bigqueryOptions`, you must set `uniqueWriterIdentity` to true. */ uniqueWriterIdentity?: pulumi.Input<boolean>; /** * The identity associated with this sink. This identity must be granted write access to the * configured `destination`. */ writerIdentity?: pulumi.Input<string>; } /** * The set of arguments for constructing a ProjectSink resource. */ export interface ProjectSinkArgs { /** * Options that affect sinks exporting data to BigQuery. Structure documented below. */ bigqueryOptions?: pulumi.Input<inputs.logging.ProjectSinkBigqueryOptions>; /** * A description of this exclusion. */ description?: pulumi.Input<string>; /** * The destination of the sink (or, in other words, where logs are written to). Can be a * Cloud Storage bucket, a PubSub topic, a BigQuery dataset or a Cloud Logging bucket . Examples: * ```typescript * import * as pulumi from "@pulumi/pulumi"; * ``` * The writer associated with the sink must have access to write to the above resource. */ destination: pulumi.Input<string>; /** * If set to True, then this exclusion is disabled and it does not exclude any log entries. */ disabled?: pulumi.Input<boolean>; /** * Log entries that match any of the exclusion filters will not be exported. If a log entry is matched by both filter and one of exclusionFilters it will not be exported. Can be repeated multiple times for multiple exclusions. Structure is documented below. */ exclusions?: pulumi.Input<pulumi.Input<inputs.logging.ProjectSinkExclusion>[]>; /** * An advanced logs filter that matches the log entries to be excluded. By using the sample function, you can exclude less than 100% of the matching log entries. See [Advanced Log Filters](https://cloud.google.com/logging/docs/view/advanced_filters) for information on how to * write a filter. */ filter?: pulumi.Input<string>; /** * A client-assigned identifier, such as `load-balancer-exclusion`. Identifiers are limited to 100 characters and can include only letters, digits, underscores, hyphens, and periods. First character has to be alphanumeric. */ name?: pulumi.Input<string>; /** * The ID of the project to create the sink in. If omitted, the project associated with the provider is * used. */ project?: pulumi.Input<string>; /** * Whether or not to create a unique identity associated with this sink. If `false` * (the default), then the `writerIdentity` used is `serviceAccount:cloud-logs@system.gserviceaccount.com`. If `true`, * then a unique service account is created and used for this sink. If you wish to publish logs across projects or utilize * `bigqueryOptions`, you must set `uniqueWriterIdentity` to true. */ uniqueWriterIdentity?: pulumi.Input<boolean>; }
the_stack
import { assert, expect } from 'chai'; import * as Lint from 'tslint'; import * as fs from 'fs'; import * as path from 'path'; import * as BenchMark from 'benchmark'; const dedent = Lint.Utils.dedent; const empty = '░'; class Position { private line: number | undefined; private character: number | undefined; private position: number | undefined; constructor(line?: number, character?: number, position?: number) { this.line = line; this.character = character; this.position = position; } /** * Returns the string representation of a Position in the form of `[line:char|pos]`. If * any of its properties is undefined an empty block will appear. For instance, if we only * provide only the line then the result will be `[line:░|░]`. * @returns {string} */ public toString(): string { const line = this.line === undefined ? empty : this.line; const char = this.character === undefined ? empty : this.character; const pos = this.position === undefined ? empty : this.position; return `[${line}:${char}|${pos}]`; } /** * A comparable Position to the calling object is a Position that has the same undefined * properties. For instance, `new Position(1)` and `new Position(10, 2)` are not comparable * since the second position defines its character location. * * Returns a copy of the Position parameter object with some properties set to undefined. Those * properties are set to undefined only in the case the calling object has them to set to * undefined. Thus, the returned object will be comparable to the calling object. * * @param pos The object we wish to compare. * @returns {Position} A comparable position. */ public getComparablePosition(obj: Position): Position { const line = this.line === undefined ? undefined : obj.line; const char = this.character === undefined ? undefined : obj.character; const pos = this.position === undefined ? undefined : obj.position; return new Position(line, char, pos); } } interface Failure { failure: string; startPosition: Position; endPosition: Position; } class LintFailure { private name: string; private ruleName: string; private failure: string; private startPosition: Position; private endPosition: Position; constructor(name: string, ruleName: string, failure: string, start?: Position, end?: Position) { this.name = name; this.ruleName = ruleName; this.failure = failure; this.startPosition = start || new Position(); this.endPosition = end || new Position(); } /** * Returns the string representation of the Failure object in the following form: * * ``` * [name@{startPos -> endPos}] ruleName: failure * ``` * * @returns {string} */ public toString(): string { const pos = `${this.name}@{${this.startPosition} -> ${this.endPosition}}`; return `[${pos}] ${this.ruleName}: ${this.failure}`; } /** * Return a clone of the Failure where the start and end positions are comparable to the * ones of the calling Failure. * @param obj The Failure to compare. * @returns {Failure} A comparable Failure. */ public getComparableFailure(obj: LintFailure): LintFailure { return new LintFailure( obj.name, obj.ruleName, obj.failure, this.startPosition.getComparablePosition(obj.startPosition), this.endPosition.getComparablePosition(obj.endPosition) ); } } interface ITest { code: string; output?: string; options?: any; errors?: Failure[]; } class Test { private name: string; private testFixer: boolean; public code: string; public output: string; public options: Lint.Configuration.IConfigurationFile; public errors: LintFailure[]; constructor( name: string, code: string, output: string, options: Lint.Configuration.IConfigurationFile, errors: LintFailure[], testFixer: boolean = false ) { this.name = name; this.code = code; this.output = output; this.options = options; this.errors = errors; this.testFixer = testFixer; } public runTest(skipErrorCheck: boolean = false): void { const options: Lint.ILinterOptions = { fix: false, formatter: 'json', formattersDirectory: 'dist/formatters/', rulesDirectory: 'dist/rules/' }; const linter = new Lint.Linter(options); linter.lint(this.name, this.code, this.options); // May need to exit early when doing benchmarks since we only care about the linting process. if (skipErrorCheck) return; const failures = JSON.parse(linter.getResult().output); this.compareErrors( this.errors || [], failures.map((error: any) => { const start = error.startPosition; const end = error.endPosition; return new LintFailure( error.name, error.ruleName, error.failure, new Position(start.line, start.character, start.position), new Position(end.line, end.character, end.position) ); }), linter ); } private compareErrors( expectedErrors: LintFailure[], foundErrors: LintFailure[], linter: Lint.Linter ): void { const expected = this.arrayDiff(expectedErrors, foundErrors); const found = this.arrayDiff(foundErrors, expectedErrors, false); const codeLines = this.code.split('\n'); const total = codeLines.length.toString().length; const codeStr = codeLines.map((x, i) => ` ${this.pad(i, total)}| ${x}`).join('\n'); const expectedStr = expected.length ? `Expected:\n ${expected.join('\n ')}` : ''; const foundStr = found.length ? `Found:\n ${found.join('\n ')}` : ''; const msg = [ `Error mismatch in ${this.name}:`, '', codeStr, '', ` ${expectedStr}`, '', ` ${foundStr}`, '' ].join('\n'); assert(expected.length === 0 && found.length === 0, msg); if (this.testFixer && this.output) { const fixes = linter.getResult().failures.filter(f => f.hasFix()).map(f => f.getFix()!); const fixedCode = Lint.Replacement.applyFixes(this.code, fixes); const fixerMsg = [ `Fixer output mismatch in ${this.name}:`, '', codeStr, '', ' ' ].join('\n'); expect(fixedCode).to.equal(this.output, fixerMsg); } } private arrayDiff(source: LintFailure[], target: LintFailure[], compareToTarget: boolean = true) { return source .filter(item => this.findIndex(target, item, compareToTarget) === -1) .map((x) => { if (compareToTarget) { return x.toString(); } else { return target.length ? target[0].getComparableFailure(x).toString() : x.toString(); } }); } private findIndex(source: LintFailure[], error: LintFailure, compareToError: boolean = true) { const len = source.length; let k = 0; while (k < len) { if (compareToError && `${error}` === `${error.getComparableFailure(source[k])}`) { return k; } else if (`${source[k]}` === `${source[k].getComparableFailure(error)}`) { return k; } k++; } return -1; } private pad(n: number, width: number) { const numStr: string = n.toString(); const padding: string = new Array(width - numStr.length + 1).join(' '); return numStr.length >= width ? numStr : padding + numStr; } } class TestGroup { public name: string; public ruleName: string; public description: string; public tests: Test[]; constructor( name: string, description: string, ruleName: string, tests: (ITest | string)[], testFixer: boolean = false, groupConfig: any = null ) { this.name = name; this.ruleName = ruleName; this.description = description; this.tests = tests.map((test: ITest | string, index) => { const config: any = { rules: { [ruleName]: true } }; const codeFileName = `${name}-${index}.ts`; if (typeof test === 'string') { if (groupConfig) { config.rules[ruleName] = [true, ...groupConfig]; } const configuration = Lint.Configuration.parseConfigFile(config); return new Test(codeFileName, test, '', configuration, []); } if (test.options) { config.rules[ruleName] = [true, ...test.options]; } else if (groupConfig) { config.rules[ruleName] = [true, ...groupConfig]; } const configFile = Lint.Configuration.parseConfigFile(config); const failures: LintFailure[] = (test.errors || []).map((error) => { return new LintFailure( codeFileName, ruleName, error.failure, error.startPosition, error.endPosition ); }); return new Test(codeFileName, test.code, test.output || '', configFile, failures, testFixer); }); } } class RuleTester { private ruleName: string; private testFixer: boolean; private groups: TestGroup[] = []; constructor(ruleName: string, testFixer: boolean = false) { this.ruleName = ruleName; this.testFixer = testFixer; } public addTestGroup(name: string, description: string, tests: (ITest | string)[]): this { this.groups.push(new TestGroup(name, description, this.ruleName, tests, this.testFixer)); return this; } /** * Appends a test group to run under a configuration. This configuration can be overwritten * by providing a configuration in the test. * * @param name Test identifier * @param description Test description * @param groupConfig The configuration for the group * @param tests A list of string or ITest objects. * @return {RuleTester} */ public addTestGroupWithConfig( name: string, description: string, groupConfig: any, tests: (ITest | string)[] ): this { this.groups.push(new TestGroup(name, description, this.ruleName, tests, this.testFixer, groupConfig)); return this; } public runTests(): void { const singleTest = JSON.parse(process.env.SINGLE_TEST || 'null'); const runGroup = singleTest === null || singleTest.group === null; const runIndex = singleTest === null || singleTest.num === null; const benchmark = process.env.BENCHMARK !== 'undefined'; describe(this.ruleName, () => { this.groups.forEach((group) => { if (runGroup || group.name === singleTest.group) { it(`${group.name} - ${group.description}`, () => { if (benchmark) { console.log(''); } group.tests.forEach((test, index) => { if (runIndex || singleTest.num === index) { test.runTest(); if (benchmark) { const suite = new BenchMark.Suite(); suite .add(` [${index}]:`, () => test.runTest(true)) .on('cycle', (event: any) => console.log(String(event.target))) .run({ async: false }); } } }); }); } }); }); } } function readFixture(name: string): string { return fs.readFileSync(path.join(__dirname, `../../../src/test/fixtures/${name}`), 'utf8'); } export { dedent, Position, Failure, TestGroup, RuleTester, readFixture };
the_stack
import { createElement } from '../createElement'; import { Commit, DeltaOperation, DeltaTypes, DOMNode, DOMOperation, Driver, Flags, NODE_OBJECT_POOL_FIELD, VElement, VNode, } from '../types/base'; /** * Diffs two VNode children and modifies the DOM node based on the necessary changes */ export const useChildren = (): Partial<Driver> => ( el: HTMLElement | SVGElement, newVNode: VElement, oldVNode?: VElement, effects: DOMOperation[] = [], commit: Commit = (work: () => void) => work(), driver?: Driver, ): ReturnType<Driver> => { const data = { el, newVNode, oldVNode, effects, commit, driver, }; if (newVNode.flag === Flags.IGNORE_NODE) return data; if (newVNode.flag === Flags.REPLACE_NODE) { el.replaceWith(createElement(newVNode)); return data; } const oldVNodeChildren: VNode[] = oldVNode?.children ?? []; const newVNodeChildren: VNode[] | undefined = newVNode.children; const delta: DeltaOperation[] | undefined = newVNode.delta; const diff = (el: DOMNode, newVNode: VNode, oldVNode?: VNode) => driver!(el, newVNode, oldVNode, effects, commit).effects!; // Deltas are a way for the compile-time to optimize runtime operations // by providing a set of predefined operations. This is useful for cases // where you are performing consistent, predictable operations at a high // interval, low payload situation. if (delta) { for (let i = 0; i < delta.length; ++i) { const [deltaType, deltaPosition] = delta[i]; const child = el.childNodes[deltaPosition]; if (deltaType === DeltaTypes.INSERT) { effects.push(() => el.insertBefore(createElement(newVNodeChildren![deltaPosition], false), child), ); } if (deltaType === DeltaTypes.UPDATE) { commit(() => { effects = diff( <DOMNode>child, newVNodeChildren![deltaPosition], oldVNodeChildren[deltaPosition], ); }); } if (deltaType === DeltaTypes.DELETE) { effects.push(() => el.removeChild(child)); } } return data; } // Flags allow for greater optimizability by reducing condition branches. // Generally, you should use a compiler to generate these flags, but // hand-writing them is also possible if (!newVNodeChildren || newVNode.flag === Flags.NO_CHILDREN) { if (!oldVNodeChildren) return data; effects.push(() => (el.textContent = '')); return data; } /** * ∆drown - "diff or drown" * * Million's keyed children diffing is a variant of Hunt-Szymanski[1] algorithm. They * both are in O(ND) time to find shortest edit distance. However, instead of using a * longest increasing subsequence algorithm, it generates a key map and deals with * it linearly. Additionally, Million holds removed keyed nodes in an mapped object * pool, recycling DOM nodes to reduce unnecessary element creation computation. * * [1] Hunt-Szymanski algorithm: * - https://neil.fraser.name/writing/diff * - https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.608.1614&rep=rep1&type=pdf * - https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.4.6927&rep=rep1&type=pdf * * This diffing algorithm attempts to reduce the number of DOM operations that * need to be performed by leveraging keys. It works in several steps: * * 1. Common end optimization * * This optimization technique is looking for nodes with identical keys by * simultaneously iterating through nodes in the old children list `oldVNodeChildren` * and new children list `newVNodeChildren` from both the suffix[2] and prefix[3]. * * oldVNodeChildren: -> [a b c d] <- * newVNodeChildren: -> [a b d] <- * * Skip nodes "a" and "b" at the start, and node "d" at the end. * * oldVNodeChildren: -> [c] <- * newVNodeChildren: -> [] <- * * 2. Right/left move optimization * * This optimization technique allows for nodes to be shifted right[4] or left[5] without * the generation of a key map. This technique works for both R->L and L->R traversals, * and can significantly reduce the number of DOM operations necesssary without the LIS * technique. * * oldVNodeChildren: [a b c X] * ^ * newVNodeChildren: [X a b c] * ^ * * 3. Zero length optimization * * Check if the size of one of the list is equal to zero. When length of the old * children list `oldVNodeChildren` is zero, insert remaining nodes from the new * list `newVNodeChildren`[6]. When length of `newVNodeChildren` is zero, remove * remaining nodes from `oldVNodeChildren`[7]. * * oldVNodeChildren: -> [a b c d] <- * newVNodeChildren: -> [a d] <- * * Skip nodes "a" and "d" (prefix and suffix optimization). * * oldVNodeChildren: [b c] * newVNodeChildren: [] * * Remove nodes "b" and "c". * * 4. Index and reorder continuous DOM nodes optimization * * Assign original positions of the nodes from the old children list `oldVNodeChildren` * to key map `oldKeyMap`[8]. * * oldVNodeChildren: [b c d e f] * newVNodeChildren: [c b h f e] * oldKeyMap: { * b: 0, // newVNodeChildren[0] == b * c: 1, // newVNodeChildren[1] == c * d: 2, * e: 3, * f: 4, * } * * Iterate through `newVNodeChildren` (bounded by common end optimizations) and * check if the new child key is in the `oldKeyMap`. If it is, then fetch the old * node and insert the node at the new index[9]. * * "c" is in the `oldKeyMap`, so fetch the old node at index `oldKeyMap[c] == 1` * and insert it in the DOM at index 0, or the new child index. * * oldVNodeChildren: [b c d e f] * newVNodeChildren: [c b h f e] * ^ * oldKeyMap: { * b: 0, * c: 1, // <- delete * d: 2, * e: 3, * f: 4, * } * * "b" is in the oldKeyMap, so fetch the old node at index `oldKeyMap[b] == 0` * and insert it in the DOM at index 1, or the new child index. * * oldVNodeChildren: [b c d e f] * newVNodeChildren: [c b h f e] * ^ * oldKeyMap: { * b: 0, // <- delete * d: 2, * e: 3, * f: 4, * } * * "h" is not in the oldKeyMap, create a new node and insert it in the * DOM at index 2, or the new child index [10]. * * oldVNodeChildren: [b c d e f] * newVNodeChildren: [c b h f e] * ^ * oldKeyMap: { * d: 2, * e: 3, * f: 4, * } * * "f" is in the oldKeyMap, so fetch the old node at index `oldKeyMap[f] == 4` * and insert it in the DOM at index 3, or the new child index. * * oldVNodeChildren: [b c d e f] * newVNodeChildren: [c b h f e] * ^ * oldKeyMap: { * d: 2, * e: 3, * f: 4, // <- delete * } * * "e" is in the oldKeyMap, so fetch the old node at index `oldKeyMap[e] == 3` * and insert it in the DOM at index 4, or the new child index. * * oldVNodeChildren: [b c d e f] * newVNodeChildren: [c b h f e] * ^ * oldKeyMap: { * d: 2, * e: 3, // <- delete * } * * 5. Index and delete removed nodes. * * Iterate through `oldKeyMap` values and remove DOM nodes at those indicies[11]. * * "d" is remaining in `oldKeyMap`, so remove old DOM node at index. * * oldVNodeChildren: [b c d e f] * ^ * newVNodeChildren: [c b h f e] * oldKeyMap: { * d: 2, // <- check * } */ if (newVNode.flag === Flags.ONLY_KEYED_CHILDREN) { if (!el[NODE_OBJECT_POOL_FIELD]) el[NODE_OBJECT_POOL_FIELD] = {}; let oldHead = 0; let newHead = 0; let oldTail = oldVNodeChildren.length - 1; let newTail = newVNodeChildren.length - 1; while (oldHead <= oldTail && newHead <= newTail) { const oldTailVNode = <VElement>oldVNodeChildren[oldTail]; const newTailVNode = <VElement>newVNodeChildren[newTail]; const oldHeadVNode = <VElement>oldVNodeChildren[oldHead]; const newHeadVNode = <VElement>newVNodeChildren[newHead]; if (oldTailVNode.key === newTailVNode.key) { // [2] Suffix optimization oldTail--; newTail--; } else if (oldHeadVNode.key === newHeadVNode.key) { // [3] Prefix optimization oldHead++; newHead++; } else if (oldHeadVNode.key === newTailVNode.key) { // [4] Right move const node = el.childNodes[oldHead++]; const tail = newTail--; effects.push(() => el.insertBefore(node, el.childNodes[tail].nextSibling)); } else if (oldTailVNode.key === newHeadVNode.key) { // [5] Left move const node = el.childNodes[oldTail--]; const head = newHead++; effects.push(() => el.insertBefore(node, el.childNodes[head])); } else break; } if (oldHead > oldTail) { // [6] Old children optimization while (newHead <= newTail) { const head = newHead++; effects.push(() => el.insertBefore( el[NODE_OBJECT_POOL_FIELD][(<VElement>newVNodeChildren[head]).key!] ?? createElement(newVNodeChildren[head], false), el.childNodes[head], ), ); } } else if (newHead > newTail) { // [7] New children optimization while (oldHead <= oldTail) { const head = oldHead++; const node = el.childNodes[head]; el[NODE_OBJECT_POOL_FIELD][(<VElement>oldVNodeChildren[head]).key!] = node; effects.push(() => el.removeChild(node)); } } else { // [8] Indexing old children const oldKeyMap: Record<string, number> = {}; for (; oldHead <= oldTail; ) { oldKeyMap[(<VElement>oldVNodeChildren[oldHead]).key!] = oldHead++; } while (newHead <= newTail) { const head = newHead++; const newVNodeChild = <VElement>newVNodeChildren[head]; const oldVNodePosition = oldKeyMap[newVNodeChild.key!]; if (oldVNodePosition !== undefined) { // [9] Reordering continuous nodes const node = el.childNodes[oldVNodePosition]; effects.push(() => el.insertBefore(node, el.childNodes[head])); delete oldKeyMap[newVNodeChild.key!]; } else { // [10] Create new nodes effects.push(() => el.insertBefore( el[NODE_OBJECT_POOL_FIELD][newVNodeChild.key] ?? createElement(newVNodeChild, false), el.childNodes[head], ), ); } } // [11] Clean up removed nodes for (const oldVNodeKey in oldKeyMap) { const node = el.childNodes[oldKeyMap[oldVNodeKey]]; el[NODE_OBJECT_POOL_FIELD][oldVNodeKey] = node; effects.push(() => el.removeChild(node)); } } return data; } if (newVNode.flag === Flags.ONLY_TEXT_CHILDREN) { const oldString = Array.isArray(oldVNode?.children) ? oldVNode?.children.join('') : oldVNode?.children; const newString = Array.isArray(newVNode?.children) ? newVNode?.children.join('') : newVNode?.children; if (oldString !== newString) { effects.push(() => (el.textContent = newString!)); } return data; } if (newVNode.flag === undefined || newVNode.flag === Flags.ANY_CHILDREN) { if (oldVNodeChildren && newVNodeChildren) { const commonLength = Math.min(oldVNodeChildren.length, newVNodeChildren.length); // Interates backwards, so in case a childNode is destroyed, it will not shift the nodes // and break accessing by index for (let i = commonLength - 1; i >= 0; --i) { commit(() => { effects = diff(<DOMNode>el.childNodes[i], newVNodeChildren[i], oldVNodeChildren[i]); }); } if (newVNodeChildren.length > oldVNodeChildren.length) { for (let i = commonLength; i < newVNodeChildren.length; ++i) { const node = createElement(newVNodeChildren[i], false); effects.push(() => el.appendChild(node)); } } else if (newVNodeChildren.length < oldVNodeChildren.length) { for (let i = oldVNodeChildren.length - 1; i >= commonLength; --i) { effects.push(() => el.removeChild(el.childNodes[i])); } } } else if (newVNodeChildren) { for (let i = 0; i < newVNodeChildren.length; ++i) { const node = createElement(newVNodeChildren[i], false); effects.push(() => el.appendChild(node)); } } return data; } return data; };
the_stack
import { SupportedProvider } from '@0x/dev-utils'; import { SignedOrder } from '@0x/types'; import { BigNumber } from '@0x/utils'; import * as _ from 'lodash'; import { ERC20BridgeSamplerContract } from '../../wrappers'; import { BalancerPoolsCache, computeBalancerBuyQuote, computeBalancerSellQuote } from './balancer_utils'; import { BancorService } from './bancor_service'; import { MAINNET_SUSHI_SWAP_ROUTER, MAX_UINT256, NULL_BYTES, ZERO_AMOUNT } from './constants'; import { CreamPoolsCache } from './cream_utils'; import { getCurveInfosForPair, getSnowSwapInfosForPair, getSwerveInfosForPair } from './curve_utils'; import { getKyberReserveIdsForPair } from './kyber_utils'; import { getMultiBridgeIntermediateToken } from './multibridge_utils'; import { getIntermediateTokens } from './multihop_utils'; import { SamplerContractOperation } from './sampler_contract_operation'; import { SourceFilters } from './source_filters'; import { BalancerFillData, BancorFillData, BatchedOperation, CurveFillData, CurveInfo, DexSample, DODOFillData, ERC20BridgeSource, HopInfo, KyberFillData, LiquidityProviderFillData, MooniswapFillData, MultiBridgeFillData, MultiHopFillData, SnowSwapFillData, SnowSwapInfo, SourceQuoteOperation, SushiSwapFillData, SwerveFillData, SwerveInfo, TokenAdjacencyGraph, UniswapV2FillData, } from './types'; /** * Source filters for `getTwoHopBuyQuotes()` and `getTwoHopSellQuotes()`. */ export const TWO_HOP_SOURCE_FILTERS = SourceFilters.all().exclude([ ERC20BridgeSource.MultiHop, ERC20BridgeSource.MultiBridge, ERC20BridgeSource.Native, ]); /** * Source filters for `getSellQuotes()` and `getBuyQuotes()`. */ export const BATCH_SOURCE_FILTERS = SourceFilters.all().exclude([ERC20BridgeSource.MultiHop, ERC20BridgeSource.Native]); // tslint:disable:no-inferred-empty-object-type no-unbound-method /** * Composable operations that can be batched in a single transaction, * for use with `DexOrderSampler.executeAsync()`. */ export class SamplerOperations { protected _bancorService?: BancorService; public static constant<T>(result: T): BatchedOperation<T> { return { encodeCall: () => { return '0x'; }, handleCallResults: _callResults => { return result; }, }; } constructor( protected readonly _samplerContract: ERC20BridgeSamplerContract, public readonly provider?: SupportedProvider, public readonly balancerPoolsCache: BalancerPoolsCache = new BalancerPoolsCache(), public readonly creamPoolsCache: CreamPoolsCache = new CreamPoolsCache(), protected readonly getBancorServiceFn?: () => BancorService, // for dependency injection in tests ) {} public async getBancorServiceAsync(): Promise<BancorService> { if (this.getBancorServiceFn !== undefined) { return this.getBancorServiceFn(); } if (this.provider === undefined) { throw new Error('Cannot sample liquidity from Bancor; no provider supplied.'); } if (this._bancorService === undefined) { this._bancorService = await BancorService.createAsync(this.provider); } return this._bancorService; } public getTokenDecimals(makerTokenAddress: string, takerTokenAddress: string): BatchedOperation<BigNumber[]> { return new SamplerContractOperation({ source: ERC20BridgeSource.Native, contract: this._samplerContract, function: this._samplerContract.getTokenDecimals, params: [makerTokenAddress, takerTokenAddress], }); } public getOrderFillableTakerAmounts(orders: SignedOrder[], exchangeAddress: string): BatchedOperation<BigNumber[]> { return new SamplerContractOperation({ source: ERC20BridgeSource.Native, contract: this._samplerContract, function: this._samplerContract.getOrderFillableTakerAssetAmounts, params: [orders, orders.map(o => o.signature), exchangeAddress], }); } public getOrderFillableMakerAmounts(orders: SignedOrder[], exchangeAddress: string): BatchedOperation<BigNumber[]> { return new SamplerContractOperation({ source: ERC20BridgeSource.Native, contract: this._samplerContract, function: this._samplerContract.getOrderFillableMakerAssetAmounts, params: [orders, orders.map(o => o.signature), exchangeAddress], }); } public getKyberSellQuotes( reserveId: string, makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.Kyber, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromKyberNetwork, params: [reserveId, takerToken, makerToken, takerFillAmounts], callback: (callResults: string, fillData: KyberFillData): BigNumber[] => { const [hint, samples] = this._samplerContract.getABIDecodedReturnData<[string, BigNumber[]]>( 'sampleSellsFromKyberNetwork', callResults, ); fillData.hint = hint; fillData.reserveId = reserveId; return samples; }, }); } public getKyberBuyQuotes( reserveId: string, makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.Kyber, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromKyberNetwork, params: [reserveId, takerToken, makerToken, makerFillAmounts], callback: (callResults: string, fillData: KyberFillData): BigNumber[] => { const [hint, samples] = this._samplerContract.getABIDecodedReturnData<[string, BigNumber[]]>( 'sampleBuysFromKyberNetwork', callResults, ); fillData.hint = hint; fillData.reserveId = reserveId; return samples; }, }); } public getUniswapSellQuotes( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.Uniswap, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromUniswap, params: [takerToken, makerToken, takerFillAmounts], }); } public getUniswapBuyQuotes( makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.Uniswap, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromUniswap, params: [takerToken, makerToken, makerFillAmounts], }); } public getUniswapV2SellQuotes( tokenAddressPath: string[], takerFillAmounts: BigNumber[], ): SourceQuoteOperation<UniswapV2FillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.UniswapV2, fillData: { tokenAddressPath }, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromUniswapV2, params: [tokenAddressPath, takerFillAmounts], }); } public getUniswapV2BuyQuotes( tokenAddressPath: string[], makerFillAmounts: BigNumber[], ): SourceQuoteOperation<UniswapV2FillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.UniswapV2, fillData: { tokenAddressPath }, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromUniswapV2, params: [tokenAddressPath, makerFillAmounts], }); } public getLiquidityProviderSellQuotes( registryAddress: string, makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation<LiquidityProviderFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.LiquidityProvider, fillData: {} as LiquidityProviderFillData, // tslint:disable-line:no-object-literal-type-assertion contract: this._samplerContract, function: this._samplerContract.sampleSellsFromLiquidityProviderRegistry, params: [registryAddress, takerToken, makerToken, takerFillAmounts], callback: (callResults: string, fillData: LiquidityProviderFillData): BigNumber[] => { const [samples, poolAddress] = this._samplerContract.getABIDecodedReturnData<[BigNumber[], string]>( 'sampleSellsFromLiquidityProviderRegistry', callResults, ); fillData.poolAddress = poolAddress; return samples; }, }); } public getLiquidityProviderBuyQuotes( registryAddress: string, makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): SourceQuoteOperation<LiquidityProviderFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.LiquidityProvider, fillData: {} as LiquidityProviderFillData, // tslint:disable-line:no-object-literal-type-assertion contract: this._samplerContract, function: this._samplerContract.sampleBuysFromLiquidityProviderRegistry, params: [registryAddress, takerToken, makerToken, makerFillAmounts], callback: (callResults: string, fillData: LiquidityProviderFillData): BigNumber[] => { const [samples, poolAddress] = this._samplerContract.getABIDecodedReturnData<[BigNumber[], string]>( 'sampleBuysFromLiquidityProviderRegistry', callResults, ); fillData.poolAddress = poolAddress; return samples; }, }); } public getMultiBridgeSellQuotes( multiBridgeAddress: string, makerToken: string, intermediateToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation<MultiBridgeFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.MultiBridge, fillData: { poolAddress: multiBridgeAddress }, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromMultiBridge, params: [multiBridgeAddress, takerToken, intermediateToken, makerToken, takerFillAmounts], }); } public getEth2DaiSellQuotes( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.Eth2Dai, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromEth2Dai, params: [takerToken, makerToken, takerFillAmounts], }); } public getEth2DaiBuyQuotes( makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.Eth2Dai, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromEth2Dai, params: [takerToken, makerToken, makerFillAmounts], }); } public getCurveSellQuotes( pool: CurveInfo, fromTokenIdx: number, toTokenIdx: number, takerFillAmounts: BigNumber[], ): SourceQuoteOperation<CurveFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.Curve, fillData: { pool, fromTokenIdx, toTokenIdx, }, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromCurve, params: [ { poolAddress: pool.poolAddress, sellQuoteFunctionSelector: pool.sellQuoteFunctionSelector, buyQuoteFunctionSelector: pool.buyQuoteFunctionSelector, }, new BigNumber(fromTokenIdx), new BigNumber(toTokenIdx), takerFillAmounts, ], }); } public getCurveBuyQuotes( pool: CurveInfo, fromTokenIdx: number, toTokenIdx: number, makerFillAmounts: BigNumber[], ): SourceQuoteOperation<CurveFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.Curve, fillData: { pool, fromTokenIdx, toTokenIdx, }, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromCurve, params: [ { poolAddress: pool.poolAddress, sellQuoteFunctionSelector: pool.sellQuoteFunctionSelector, buyQuoteFunctionSelector: pool.buyQuoteFunctionSelector, }, new BigNumber(fromTokenIdx), new BigNumber(toTokenIdx), makerFillAmounts, ], }); } public getSwerveSellQuotes( pool: SwerveInfo, fromTokenIdx: number, toTokenIdx: number, takerFillAmounts: BigNumber[], ): SourceQuoteOperation<SwerveFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.Swerve, fillData: { pool, fromTokenIdx, toTokenIdx, }, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromCurve, params: [ { poolAddress: pool.poolAddress, sellQuoteFunctionSelector: pool.sellQuoteFunctionSelector, buyQuoteFunctionSelector: pool.buyQuoteFunctionSelector, }, new BigNumber(fromTokenIdx), new BigNumber(toTokenIdx), takerFillAmounts, ], }); } public getSwerveBuyQuotes( pool: SwerveInfo, fromTokenIdx: number, toTokenIdx: number, makerFillAmounts: BigNumber[], ): SourceQuoteOperation<SwerveFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.Swerve, fillData: { pool, fromTokenIdx, toTokenIdx, }, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromCurve, params: [ { poolAddress: pool.poolAddress, sellQuoteFunctionSelector: pool.sellQuoteFunctionSelector, buyQuoteFunctionSelector: pool.buyQuoteFunctionSelector, }, new BigNumber(fromTokenIdx), new BigNumber(toTokenIdx), makerFillAmounts, ], }); } public getSnowSwapSellQuotes( pool: SnowSwapInfo, fromTokenIdx: number, toTokenIdx: number, takerFillAmounts: BigNumber[], ): SourceQuoteOperation<SnowSwapFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.SnowSwap, fillData: { pool, fromTokenIdx, toTokenIdx, }, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromCurve, params: [ { poolAddress: pool.poolAddress, sellQuoteFunctionSelector: pool.sellQuoteFunctionSelector, buyQuoteFunctionSelector: pool.buyQuoteFunctionSelector, }, new BigNumber(fromTokenIdx), new BigNumber(toTokenIdx), takerFillAmounts, ], }); } public getSnowSwapBuyQuotes( pool: SnowSwapInfo, fromTokenIdx: number, toTokenIdx: number, makerFillAmounts: BigNumber[], ): SourceQuoteOperation<SnowSwapFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.SnowSwap, fillData: { pool, fromTokenIdx, toTokenIdx, }, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromCurve, params: [ { poolAddress: pool.poolAddress, sellQuoteFunctionSelector: pool.sellQuoteFunctionSelector, buyQuoteFunctionSelector: pool.buyQuoteFunctionSelector, }, new BigNumber(fromTokenIdx), new BigNumber(toTokenIdx), makerFillAmounts, ], }); } public getBalancerSellQuotes( poolAddress: string, makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], source: ERC20BridgeSource, ): SourceQuoteOperation<BalancerFillData> { return new SamplerContractOperation({ source, fillData: { poolAddress }, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromBalancer, params: [poolAddress, takerToken, makerToken, takerFillAmounts], }); } public getBalancerBuyQuotes( poolAddress: string, makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], source: ERC20BridgeSource, ): SourceQuoteOperation<BalancerFillData> { return new SamplerContractOperation({ source, fillData: { poolAddress }, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromBalancer, params: [poolAddress, takerToken, makerToken, makerFillAmounts], }); } public async getBalancerSellQuotesOffChainAsync( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): Promise<Array<Array<DexSample<BalancerFillData>>>> { const pools = await this.balancerPoolsCache.getPoolsForPairAsync(takerToken, makerToken); return pools.map(pool => takerFillAmounts.map(amount => ({ source: ERC20BridgeSource.Balancer, output: computeBalancerSellQuote(pool, amount), input: amount, fillData: { poolAddress: pool.id }, })), ); } public async getBalancerBuyQuotesOffChainAsync( makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): Promise<Array<Array<DexSample<BalancerFillData>>>> { const pools = await this.balancerPoolsCache.getPoolsForPairAsync(takerToken, makerToken); return pools.map(pool => makerFillAmounts.map(amount => ({ source: ERC20BridgeSource.Balancer, output: computeBalancerBuyQuote(pool, amount), input: amount, fillData: { poolAddress: pool.id }, })), ); } public async getCreamSellQuotesOffChainAsync( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): Promise<Array<Array<DexSample<BalancerFillData>>>> { const pools = await this.creamPoolsCache.getPoolsForPairAsync(takerToken, makerToken); return pools.map(pool => takerFillAmounts.map(amount => ({ source: ERC20BridgeSource.Cream, output: computeBalancerSellQuote(pool, amount), input: amount, fillData: { poolAddress: pool.id }, })), ); } public async getCreamBuyQuotesOffChainAsync( makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): Promise<Array<Array<DexSample<BalancerFillData>>>> { const pools = await this.creamPoolsCache.getPoolsForPairAsync(takerToken, makerToken); return pools.map(pool => makerFillAmounts.map(amount => ({ source: ERC20BridgeSource.Cream, output: computeBalancerBuyQuote(pool, amount), input: amount, fillData: { poolAddress: pool.id }, })), ); } public getMStableSellQuotes( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.MStable, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromMStable, params: [takerToken, makerToken, takerFillAmounts], }); } public getMStableBuyQuotes( makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.MStable, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromMStable, params: [takerToken, makerToken, makerFillAmounts], }); } public async getBancorSellQuotesOffChainAsync( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): Promise<Array<DexSample<BancorFillData>>> { const bancorService = await this.getBancorServiceAsync(); try { const quotes = await bancorService.getQuotesAsync(takerToken, makerToken, takerFillAmounts); return quotes.map((quote, i) => ({ source: ERC20BridgeSource.Bancor, output: quote.amount, input: takerFillAmounts[i], fillData: quote.fillData, })); } catch (e) { return takerFillAmounts.map(input => ({ source: ERC20BridgeSource.Bancor, output: ZERO_AMOUNT, input, fillData: { path: [], networkAddress: '' }, })); } } public getMooniswapSellQuotes( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation<MooniswapFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.Mooniswap, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromMooniswap, params: [takerToken, makerToken, takerFillAmounts], callback: (callResults: string, fillData: MooniswapFillData): BigNumber[] => { const [poolAddress, samples] = this._samplerContract.getABIDecodedReturnData<[string, BigNumber[]]>( 'sampleSellsFromMooniswap', callResults, ); fillData.poolAddress = poolAddress; return samples; }, }); } public getMooniswapBuyQuotes( makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): SourceQuoteOperation<MooniswapFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.Mooniswap, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromMooniswap, params: [takerToken, makerToken, makerFillAmounts], callback: (callResults: string, fillData: MooniswapFillData): BigNumber[] => { const [poolAddress, samples] = this._samplerContract.getABIDecodedReturnData<[string, BigNumber[]]>( 'sampleBuysFromMooniswap', callResults, ); fillData.poolAddress = poolAddress; return samples; }, }); } public getTwoHopSellQuotes( sources: ERC20BridgeSource[], makerToken: string, takerToken: string, sellAmount: BigNumber, tokenAdjacencyGraph: TokenAdjacencyGraph, wethAddress: string, liquidityProviderRegistryAddress?: string, ): BatchedOperation<Array<DexSample<MultiHopFillData>>> { const _sources = TWO_HOP_SOURCE_FILTERS.getAllowed(sources); if (_sources.length === 0) { return SamplerOperations.constant([]); } const intermediateTokens = getIntermediateTokens(makerToken, takerToken, tokenAdjacencyGraph, wethAddress); const subOps = intermediateTokens.map(intermediateToken => { const firstHopOps = this._getSellQuoteOperations( _sources, intermediateToken, takerToken, [ZERO_AMOUNT], wethAddress, liquidityProviderRegistryAddress, ); const secondHopOps = this._getSellQuoteOperations( _sources, makerToken, intermediateToken, [ZERO_AMOUNT], wethAddress, liquidityProviderRegistryAddress, ); return new SamplerContractOperation({ contract: this._samplerContract, source: ERC20BridgeSource.MultiHop, function: this._samplerContract.sampleTwoHopSell, params: [firstHopOps.map(op => op.encodeCall()), secondHopOps.map(op => op.encodeCall()), sellAmount], fillData: { intermediateToken } as MultiHopFillData, // tslint:disable-line:no-object-literal-type-assertion callback: (callResults: string, fillData: MultiHopFillData): BigNumber[] => { const [firstHop, secondHop, buyAmount] = this._samplerContract.getABIDecodedReturnData< [HopInfo, HopInfo, BigNumber] >('sampleTwoHopSell', callResults); // Ensure the hop sources are set even when the buy amount is zero fillData.firstHopSource = firstHopOps[firstHop.sourceIndex.toNumber()]; fillData.secondHopSource = secondHopOps[secondHop.sourceIndex.toNumber()]; if (buyAmount.isZero()) { return [ZERO_AMOUNT]; } fillData.firstHopSource.handleCallResults(firstHop.returnData); fillData.secondHopSource.handleCallResults(secondHop.returnData); return [buyAmount]; }, }); }); return { encodeCall: () => { const subCalls = subOps.map(op => op.encodeCall()); return this._samplerContract.batchCall(subCalls).getABIEncodedTransactionData(); }, handleCallResults: callResults => { const rawSubCallResults = this._samplerContract.getABIDecodedReturnData<string[]>( 'batchCall', callResults, ); return subOps.map((op, i) => { const [output] = op.handleCallResults(rawSubCallResults[i]); return { source: op.source, output, input: sellAmount, fillData: op.fillData, }; }); }, }; } public getTwoHopBuyQuotes( sources: ERC20BridgeSource[], makerToken: string, takerToken: string, buyAmount: BigNumber, tokenAdjacencyGraph: TokenAdjacencyGraph, wethAddress: string, liquidityProviderRegistryAddress?: string, ): BatchedOperation<Array<DexSample<MultiHopFillData>>> { const _sources = TWO_HOP_SOURCE_FILTERS.getAllowed(sources); if (_sources.length === 0) { return SamplerOperations.constant([]); } const intermediateTokens = getIntermediateTokens(makerToken, takerToken, tokenAdjacencyGraph, wethAddress); const subOps = intermediateTokens.map(intermediateToken => { const firstHopOps = this._getBuyQuoteOperations( _sources, intermediateToken, takerToken, [new BigNumber(0)], wethAddress, liquidityProviderRegistryAddress, ); const secondHopOps = this._getBuyQuoteOperations( _sources, makerToken, intermediateToken, [new BigNumber(0)], wethAddress, liquidityProviderRegistryAddress, ); return new SamplerContractOperation({ contract: this._samplerContract, source: ERC20BridgeSource.MultiHop, function: this._samplerContract.sampleTwoHopBuy, params: [firstHopOps.map(op => op.encodeCall()), secondHopOps.map(op => op.encodeCall()), buyAmount], fillData: { intermediateToken } as MultiHopFillData, // tslint:disable-line:no-object-literal-type-assertion callback: (callResults: string, fillData: MultiHopFillData): BigNumber[] => { const [firstHop, secondHop, sellAmount] = this._samplerContract.getABIDecodedReturnData< [HopInfo, HopInfo, BigNumber] >('sampleTwoHopBuy', callResults); if (sellAmount.isEqualTo(MAX_UINT256)) { return [sellAmount]; } fillData.firstHopSource = firstHopOps[firstHop.sourceIndex.toNumber()]; fillData.secondHopSource = secondHopOps[secondHop.sourceIndex.toNumber()]; fillData.firstHopSource.handleCallResults(firstHop.returnData); fillData.secondHopSource.handleCallResults(secondHop.returnData); return [sellAmount]; }, }); }); return { encodeCall: () => { const subCalls = subOps.map(op => op.encodeCall()); return this._samplerContract.batchCall(subCalls).getABIEncodedTransactionData(); }, handleCallResults: callResults => { const rawSubCallResults = this._samplerContract.getABIDecodedReturnData<string[]>( 'batchCall', callResults, ); return subOps.map((op, i) => { const [output] = op.handleCallResults(rawSubCallResults[i]); return { source: op.source, output, input: buyAmount, fillData: op.fillData, }; }); }, }; } public getSushiSwapSellQuotes( tokenAddressPath: string[], takerFillAmounts: BigNumber[], ): SourceQuoteOperation<SushiSwapFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.SushiSwap, fillData: { tokenAddressPath, router: MAINNET_SUSHI_SWAP_ROUTER }, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromSushiSwap, params: [MAINNET_SUSHI_SWAP_ROUTER, tokenAddressPath, takerFillAmounts], }); } public getSushiSwapBuyQuotes( tokenAddressPath: string[], makerFillAmounts: BigNumber[], ): SourceQuoteOperation<SushiSwapFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.SushiSwap, fillData: { tokenAddressPath, router: MAINNET_SUSHI_SWAP_ROUTER }, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromSushiSwap, params: [MAINNET_SUSHI_SWAP_ROUTER, tokenAddressPath, makerFillAmounts], }); } public getShellSellQuotes( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.Shell, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromShell, params: [takerToken, makerToken, takerFillAmounts], }); } public getShellBuyQuotes( makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): SourceQuoteOperation { return new SamplerContractOperation({ source: ERC20BridgeSource.Shell, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromShell, params: [takerToken, makerToken, makerFillAmounts], }); } public getDODOSellQuotes( makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], ): SourceQuoteOperation<DODOFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.Dodo, contract: this._samplerContract, function: this._samplerContract.sampleSellsFromDODO, params: [takerToken, makerToken, takerFillAmounts], callback: (callResults: string, fillData: DODOFillData): BigNumber[] => { const [isSellBase, pool, samples] = this._samplerContract.getABIDecodedReturnData< [boolean, string, BigNumber[]] >('sampleSellsFromDODO', callResults); fillData.isSellBase = isSellBase; fillData.poolAddress = pool; return samples; }, }); } public getDODOBuyQuotes( makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], ): SourceQuoteOperation<DODOFillData> { return new SamplerContractOperation({ source: ERC20BridgeSource.Dodo, contract: this._samplerContract, function: this._samplerContract.sampleBuysFromDODO, params: [takerToken, makerToken, makerFillAmounts], callback: (callResults: string, fillData: DODOFillData): BigNumber[] => { const [isSellBase, pool, samples] = this._samplerContract.getABIDecodedReturnData< [boolean, string, BigNumber[]] >('sampleBuysFromDODO', callResults); fillData.isSellBase = isSellBase; fillData.poolAddress = pool; return samples; }, }); } public getMedianSellRate( sources: ERC20BridgeSource[], makerToken: string, takerToken: string, takerFillAmount: BigNumber, wethAddress: string, liquidityProviderRegistryAddress?: string, multiBridgeAddress?: string, ): BatchedOperation<BigNumber> { if (makerToken.toLowerCase() === takerToken.toLowerCase()) { return SamplerOperations.constant(new BigNumber(1)); } const getSellQuotes = this.getSellQuotes( sources, makerToken, takerToken, [takerFillAmount], wethAddress, liquidityProviderRegistryAddress, multiBridgeAddress, ); return { encodeCall: () => { const encodedCall = getSellQuotes.encodeCall(); // All soures were excluded if (encodedCall === NULL_BYTES) { return NULL_BYTES; } return this._samplerContract.batchCall([encodedCall]).getABIEncodedTransactionData(); }, handleCallResults: callResults => { if (callResults === NULL_BYTES) { return ZERO_AMOUNT; } const rawSubCallResults = this._samplerContract.getABIDecodedReturnData<string[]>( 'batchCall', callResults, ); const samples = getSellQuotes.handleCallResults(rawSubCallResults[0]); if (samples.length === 0) { return ZERO_AMOUNT; } const flatSortedSamples = samples .reduce((acc, v) => acc.concat(...v)) .filter(v => !v.output.isZero()) .sort((a, b) => a.output.comparedTo(b.output)); if (flatSortedSamples.length === 0) { return ZERO_AMOUNT; } const medianSample = flatSortedSamples[Math.floor(flatSortedSamples.length / 2)]; return medianSample.output.div(medianSample.input); }, }; } public getSellQuotes( sources: ERC20BridgeSource[], makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], wethAddress: string, liquidityProviderRegistryAddress?: string, multiBridgeAddress?: string, ): BatchedOperation<DexSample[][]> { const subOps = this._getSellQuoteOperations( sources, makerToken, takerToken, takerFillAmounts, wethAddress, liquidityProviderRegistryAddress, multiBridgeAddress, ); return { encodeCall: () => { const subCalls = subOps.map(op => op.encodeCall()); return this._samplerContract.batchCall(subCalls).getABIEncodedTransactionData(); }, handleCallResults: callResults => { const rawSubCallResults = this._samplerContract.getABIDecodedReturnData<string[]>( 'batchCall', callResults, ); const samples = subOps.map((op, i) => op.handleCallResults(rawSubCallResults[i])); return subOps.map((op, i) => { return samples[i].map((output, j) => ({ source: op.source, output, input: takerFillAmounts[j], fillData: op.fillData, })); }); }, }; } public getBuyQuotes( sources: ERC20BridgeSource[], makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], wethAddress: string, liquidityProviderRegistryAddress?: string, ): BatchedOperation<DexSample[][]> { const subOps = this._getBuyQuoteOperations( sources, makerToken, takerToken, makerFillAmounts, wethAddress, liquidityProviderRegistryAddress, ); return { encodeCall: () => { const subCalls = subOps.map(op => op.encodeCall()); return this._samplerContract.batchCall(subCalls).getABIEncodedTransactionData(); }, handleCallResults: callResults => { const rawSubCallResults = this._samplerContract.getABIDecodedReturnData<string[]>( 'batchCall', callResults, ); const samples = subOps.map((op, i) => op.handleCallResults(rawSubCallResults[i])); return subOps.map((op, i) => { return samples[i].map((output, j) => ({ source: op.source, output, input: makerFillAmounts[j], fillData: op.fillData, })); }); }, }; } private _getSellQuoteOperations( sources: ERC20BridgeSource[], makerToken: string, takerToken: string, takerFillAmounts: BigNumber[], wethAddress: string, liquidityProviderRegistryAddress?: string, multiBridgeAddress?: string, ): SourceQuoteOperation[] { const _sources = BATCH_SOURCE_FILTERS.exclude( liquidityProviderRegistryAddress ? [] : [ERC20BridgeSource.LiquidityProvider], ) .exclude(multiBridgeAddress ? [] : [ERC20BridgeSource.MultiBridge]) .getAllowed(sources); return _.flatten( _sources.map( (source): SourceQuoteOperation | SourceQuoteOperation[] => { switch (source) { case ERC20BridgeSource.Eth2Dai: return this.getEth2DaiSellQuotes(makerToken, takerToken, takerFillAmounts); case ERC20BridgeSource.Uniswap: return this.getUniswapSellQuotes(makerToken, takerToken, takerFillAmounts); case ERC20BridgeSource.UniswapV2: const ops = [this.getUniswapV2SellQuotes([takerToken, makerToken], takerFillAmounts)]; if (takerToken !== wethAddress && makerToken !== wethAddress) { ops.push( this.getUniswapV2SellQuotes( [takerToken, wethAddress, makerToken], takerFillAmounts, ), ); } return ops; case ERC20BridgeSource.SushiSwap: const sushiOps = [this.getSushiSwapSellQuotes([takerToken, makerToken], takerFillAmounts)]; if (takerToken !== wethAddress && makerToken !== wethAddress) { sushiOps.push( this.getSushiSwapSellQuotes( [takerToken, wethAddress, makerToken], takerFillAmounts, ), ); } return sushiOps; case ERC20BridgeSource.Kyber: return getKyberReserveIdsForPair(takerToken, makerToken).map(reserveId => this.getKyberSellQuotes(reserveId, makerToken, takerToken, takerFillAmounts), ); case ERC20BridgeSource.Curve: return getCurveInfosForPair(takerToken, makerToken).map(pool => this.getCurveSellQuotes( pool, pool.tokens.indexOf(takerToken), pool.tokens.indexOf(makerToken), takerFillAmounts, ), ); case ERC20BridgeSource.Swerve: return getSwerveInfosForPair(takerToken, makerToken).map(pool => this.getSwerveSellQuotes( pool, pool.tokens.indexOf(takerToken), pool.tokens.indexOf(makerToken), takerFillAmounts, ), ); case ERC20BridgeSource.SnowSwap: return getSnowSwapInfosForPair(takerToken, makerToken).map(pool => this.getSnowSwapSellQuotes( pool, pool.tokens.indexOf(takerToken), pool.tokens.indexOf(makerToken), takerFillAmounts, ), ); case ERC20BridgeSource.LiquidityProvider: if (liquidityProviderRegistryAddress === undefined) { throw new Error( 'Cannot sample liquidity from a LiquidityProvider liquidity pool, if a registry is not provided.', ); } return this.getLiquidityProviderSellQuotes( liquidityProviderRegistryAddress, makerToken, takerToken, takerFillAmounts, ); case ERC20BridgeSource.MultiBridge: if (multiBridgeAddress === undefined) { throw new Error( 'Cannot sample liquidity from MultiBridge if an address is not provided.', ); } const intermediateToken = getMultiBridgeIntermediateToken(takerToken, makerToken); return this.getMultiBridgeSellQuotes( multiBridgeAddress, makerToken, intermediateToken, takerToken, takerFillAmounts, ); case ERC20BridgeSource.MStable: return this.getMStableSellQuotes(makerToken, takerToken, takerFillAmounts); case ERC20BridgeSource.Mooniswap: return this.getMooniswapSellQuotes(makerToken, takerToken, takerFillAmounts); case ERC20BridgeSource.Balancer: return this.balancerPoolsCache .getCachedPoolAddressesForPair(takerToken, makerToken)! .map(poolAddress => this.getBalancerSellQuotes( poolAddress, makerToken, takerToken, takerFillAmounts, ERC20BridgeSource.Balancer, ), ); case ERC20BridgeSource.Cream: return this.creamPoolsCache .getCachedPoolAddressesForPair(takerToken, makerToken)! .map(poolAddress => this.getBalancerSellQuotes( poolAddress, makerToken, takerToken, takerFillAmounts, ERC20BridgeSource.Cream, ), ); case ERC20BridgeSource.Shell: return this.getShellSellQuotes(makerToken, takerToken, takerFillAmounts); case ERC20BridgeSource.Dodo: return this.getDODOSellQuotes(makerToken, takerToken, takerFillAmounts); default: throw new Error(`Unsupported sell sample source: ${source}`); } }, ), ); } private _getBuyQuoteOperations( sources: ERC20BridgeSource[], makerToken: string, takerToken: string, makerFillAmounts: BigNumber[], wethAddress: string, liquidityProviderRegistryAddress?: string, ): SourceQuoteOperation[] { const _sources = BATCH_SOURCE_FILTERS.exclude( liquidityProviderRegistryAddress ? [] : [ERC20BridgeSource.LiquidityProvider], ).getAllowed(sources); return _.flatten( _sources.map( (source): SourceQuoteOperation | SourceQuoteOperation[] => { switch (source) { case ERC20BridgeSource.Eth2Dai: return this.getEth2DaiBuyQuotes(makerToken, takerToken, makerFillAmounts); case ERC20BridgeSource.Uniswap: return this.getUniswapBuyQuotes(makerToken, takerToken, makerFillAmounts); case ERC20BridgeSource.UniswapV2: const ops = [this.getUniswapV2BuyQuotes([takerToken, makerToken], makerFillAmounts)]; if (takerToken !== wethAddress && makerToken !== wethAddress) { ops.push( this.getUniswapV2BuyQuotes([takerToken, wethAddress, makerToken], makerFillAmounts), ); } return ops; case ERC20BridgeSource.SushiSwap: const sushiOps = [this.getSushiSwapBuyQuotes([takerToken, makerToken], makerFillAmounts)]; if (takerToken !== wethAddress && makerToken !== wethAddress) { sushiOps.push( this.getSushiSwapBuyQuotes([takerToken, wethAddress, makerToken], makerFillAmounts), ); } return sushiOps; case ERC20BridgeSource.Kyber: return getKyberReserveIdsForPair(takerToken, makerToken).map(reserveId => this.getKyberBuyQuotes(reserveId, makerToken, takerToken, makerFillAmounts), ); case ERC20BridgeSource.Curve: return getCurveInfosForPair(takerToken, makerToken).map(pool => this.getCurveBuyQuotes( pool, pool.tokens.indexOf(takerToken), pool.tokens.indexOf(makerToken), makerFillAmounts, ), ); case ERC20BridgeSource.Swerve: return getSwerveInfosForPair(takerToken, makerToken).map(pool => this.getSwerveBuyQuotes( pool, pool.tokens.indexOf(takerToken), pool.tokens.indexOf(makerToken), makerFillAmounts, ), ); case ERC20BridgeSource.SnowSwap: return getSnowSwapInfosForPair(takerToken, makerToken).map(pool => this.getSnowSwapBuyQuotes( pool, pool.tokens.indexOf(takerToken), pool.tokens.indexOf(makerToken), makerFillAmounts, ), ); case ERC20BridgeSource.LiquidityProvider: if (liquidityProviderRegistryAddress === undefined) { throw new Error( 'Cannot sample liquidity from a LiquidityProvider liquidity pool, if a registry is not provided.', ); } return this.getLiquidityProviderBuyQuotes( liquidityProviderRegistryAddress, makerToken, takerToken, makerFillAmounts, ); case ERC20BridgeSource.MStable: return this.getMStableBuyQuotes(makerToken, takerToken, makerFillAmounts); case ERC20BridgeSource.Mooniswap: return this.getMooniswapBuyQuotes(makerToken, takerToken, makerFillAmounts); case ERC20BridgeSource.Balancer: return this.balancerPoolsCache .getCachedPoolAddressesForPair(takerToken, makerToken)! .map(poolAddress => this.getBalancerBuyQuotes( poolAddress, makerToken, takerToken, makerFillAmounts, ERC20BridgeSource.Balancer, ), ); case ERC20BridgeSource.Cream: return this.creamPoolsCache .getCachedPoolAddressesForPair(takerToken, makerToken)! .map(poolAddress => this.getBalancerBuyQuotes( poolAddress, makerToken, takerToken, makerFillAmounts, ERC20BridgeSource.Cream, ), ); case ERC20BridgeSource.Shell: return this.getShellBuyQuotes(makerToken, takerToken, makerFillAmounts); case ERC20BridgeSource.Dodo: return this.getDODOBuyQuotes(makerToken, takerToken, makerFillAmounts); default: throw new Error(`Unsupported buy sample source: ${source}`); } }, ), ); } } // tslint:disable max-file-line-count
the_stack
import { ArmSiteDescriptor } from './../shared/resourceDescriptors'; import { EmbeddedFunctionsNode } from './../tree-view/embedded-functions-node'; import { ScenarioService } from './../shared/services/scenario/scenario.service'; import { LogService } from './../shared/services/log.service'; import { Router, ActivatedRoute } from '@angular/router'; import { BroadcastEvent } from 'app/shared/models/broadcast-event'; import { StoredSubscriptions } from './../shared/models/localStorage/local-storage'; import { Dom } from './../shared/Utilities/dom'; import { SubUtil } from './../shared/Utilities/sub-util'; import { SearchBoxComponent } from './../search-box/search-box.component'; import { Component, ViewChild, AfterViewInit, Injector, OnDestroy } from '@angular/core'; import { Http } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import { TranslateService } from '@ngx-translate/core'; import { ConfigService } from './../shared/services/config.service'; import { PortalResources } from './../shared/models/portal-resources'; import { AuthzService } from './../shared/services/authz.service'; import { LanguageService } from './../shared/services/language.service'; import { LocalStorageKeys, ARM, LogCategories, ScenarioIds } from './../shared/models/constants'; import { PortalService } from './../shared/services/portal.service'; import { LocalStorageService } from './../shared/services/local-storage.service'; import { TreeNode } from '../tree-view/tree-node'; import { AppsNode } from '../tree-view/apps-node'; import { ArmService } from '../shared/services/arm.service'; import { CacheService } from '../shared/services/cache.service'; import { UserService } from '../shared/services/user.service'; import { TryFunctionsService } from '../shared/services/try-functions.service'; import { GlobalStateService } from '../shared/services/global-state.service'; import { BroadcastService } from '../shared/services/broadcast.service'; import { AiService } from '../shared/services/ai.service'; import { DropDownElement } from '../shared/models/drop-down-element'; import { TreeViewInfo } from '../tree-view/models/tree-view-info'; import { DashboardType } from '../tree-view/models/dashboard-type'; import { Subscription } from '../shared/models/subscription'; import { Url } from 'app/shared/Utilities/url'; import { StartupInfo } from 'app/shared/models/portal'; @Component({ selector: 'side-nav', templateUrl: './side-nav.component.html', styleUrls: ['./side-nav.component.scss'], }) export class SideNavComponent implements AfterViewInit, OnDestroy { @ViewChild('treeViewContainer') treeViewContainer; @ViewChild(SearchBoxComponent) searchBox: SearchBoxComponent; public rootNode: TreeNode; public subscriptionOptions: DropDownElement<Subscription>[] = []; public selectedSubscriptions: Subscription[] = []; public subscriptionsDisplayText = ''; public allSubscriptions = this.translateService.instant(PortalResources.sideNav_AllSubscriptions); public numberSubscriptions = this.translateService.instant(PortalResources.sideNav_SubscriptionCount); public resourceId: string; public initialResourceId: string; public searchTerm = ''; public hasValue = false; public headerOnTopOfSideNav = false; public noPaddingOnSideNav = false; public selectedNode: TreeNode; public selectedDashboardType: DashboardType; private _subscriptionsStream = new ReplaySubject<Subscription[]>(1); private _searchTermStream = new ReplaySubject<string>(1); private _ngUnsubscribe = new Subject(); private _initialized = false; constructor( public injector: Injector, public configService: ConfigService, public armService: ArmService, public cacheService: CacheService, public tryFunctionsSevice: TryFunctionsService, public http: Http, public globalStateService: GlobalStateService, public broadcastService: BroadcastService, public translateService: TranslateService, public userService: UserService, public aiService: AiService, public localStorageService: LocalStorageService, public portalService: PortalService, public languageService: LanguageService, public authZService: AuthzService, public logService: LogService, public router: Router, public route: ActivatedRoute, private _scenarioService: ScenarioService ) { this.headerOnTopOfSideNav = this._scenarioService.checkScenario(ScenarioIds.headerOnTopOfSideNav).status === 'enabled'; this.noPaddingOnSideNav = this._scenarioService.checkScenario(ScenarioIds.noPaddingOnSideNav).status === 'enabled'; userService.getStartupInfo().subscribe(info => { const sitenameIncoming = !!info.resourceId ? new ArmSiteDescriptor(info.resourceId).site.toLocaleLowerCase() : null; const initialSiteName = !!this.initialResourceId ? new ArmSiteDescriptor(this.initialResourceId).site.toLocaleLowerCase() : null; if (sitenameIncoming !== initialSiteName) { this.portalService.sendTimerEvent({ timerId: 'TreeViewLoad', timerAction: 'start', }); } // This is a workaround for the fact that Ibiza sends us an updated info whenever // child blades close. If we get a new info object, then we'll rebuild the tree. // The true fix would be to make sure that we never set the resourceId of the hosting // blade, but that's a pretty large change and this should be sufficient for now. if (!this._initialized && !this.globalStateService.showTryView) { this._initializeTree(info); } if (this._scenarioService.checkScenario(ScenarioIds.addTopLevelAppsNode).status !== 'disabled') { this._updateSubscriptions(info); this.initialResourceId = info.resourceId; if (this.initialResourceId) { const descriptor = new ArmSiteDescriptor(this.initialResourceId); if (descriptor.site) { this._searchTermStream.next(`"${descriptor.site}"`); this.hasValue = true; } else { this._searchTermStream.next(''); } } else if (!this.searchTerm) { // Ensure that we don't override existing search term if we get a startupInfo update this._searchTermStream.next(''); } } }); } ngAfterViewInit() { // Search box is not available for Try Functions if (this.searchBox) { this.searchBox.focus(); } } private _initializeTree(info: StartupInfo<void>) { this._initialized = true; this.rootNode = new TreeNode(this, null, null); if (this._scenarioService.checkScenario(ScenarioIds.addTopLevelAppsNode).status !== 'disabled') { const appsNode = new AppsNode(this, this.rootNode, this._subscriptionsStream, this._searchTermStream, info.resourceId); this.rootNode.children = [appsNode]; this.rootNode.isExpanded = true; appsNode.parent = this.rootNode; // Need to allow the appsNode to wire up its subscriptions setTimeout(() => { appsNode.select(); }, 10); this._searchTermStream.subscribe(term => { this.searchTerm = term; }); } else { const resourceIdMatch = /\/resources([a-z0-9\-\/]+)/gi.exec(this.router.url); if (resourceIdMatch && resourceIdMatch.length > 1) { const smallerMatch = resourceIdMatch[1] .split('/') .filter(part => !!part) .slice(0, 4) .join('/'); const smallerId = `/providers/Microsoft.BlueRidge/${smallerMatch}`; const functionsNode = new EmbeddedFunctionsNode(this, this.rootNode, smallerId); this.rootNode.children = [functionsNode]; this.rootNode.isExpanded = true; functionsNode.toggle(null); functionsNode.select(); } else { // log error } } } private _getViewContainer(): HTMLDivElement { const treeViewContainer = this.treeViewContainer && <HTMLDivElement>this.treeViewContainer.nativeElement; if (!treeViewContainer) { return null; } return <HTMLDivElement>treeViewContainer.querySelector('.top-level-children'); } ngOnDestroy() { this._ngUnsubscribe.next(); } public scrollIntoView() { setTimeout(() => { const containerElement = this._getViewContainer(); if (!containerElement) { return; } const node = <HTMLDivElement>containerElement.querySelector(':focus'); if (!node) { return; } Dom.scrollIntoView(node, containerElement); }, 0); } updateView( newSelectedNode: TreeNode, newDashboardType: DashboardType, resourceId: string, force?: boolean, keepChildBladesOpen?: boolean ): Observable<boolean> { if (this.selectedNode) { if (!force && this.selectedNode === newSelectedNode && this.selectedDashboardType === newDashboardType) { return Observable.of(false); } else { if (this.selectedNode.shouldBlockNavChange()) { return Observable.of(false); } this.selectedNode.handleDeselection(newSelectedNode); this.selectedNode.showMenu = false; } } this._logDashboardTypeChange( this.selectedDashboardType, newDashboardType, this.selectedNode && this.selectedNode.resourceId, newSelectedNode && newSelectedNode.resourceId ); this.selectedNode = newSelectedNode; this.selectedDashboardType = newDashboardType; this.resourceId = newSelectedNode.resourceId; // TODO: should this be updated to resourceId passed in or is this fine? this.selectedNode.showMenu = true; const viewInfo = <TreeViewInfo<any>>{ resourceId: resourceId, dashboardType: newDashboardType, node: newSelectedNode, data: {}, }; this.globalStateService.setDisabledMessage(null); // TODO: I can't seem to get Angular to handle case-insensitive routes properly, even if // I follow the example from here: https://stackoverflow.com/questions/36154672/angular2-make-route-paths-case-insensitive // BUG: For now we need to remove the "microsoft.web" piece from the URL or Kudu won't list functions properly: // https://github.com/projectkudu/kudu/issues/2543 const navId = resourceId .slice(1, resourceId.length) .toLowerCase() .replace('/providers/microsoft.web', ''); this.logService.debug(LogCategories.SideNav, `Navigating to ${navId}`); this.router.navigate([navId], { relativeTo: this.route, queryParams: Url.getQueryStringObj() }); // const dashboardString = DashboardType[newDashboardType]; // setTimeout(() => this.broadcastService.broadcastEvent(BroadcastEvent[dashboardString], viewInfo), 100); this.broadcastService.broadcastEvent(BroadcastEvent.TreeNavigation, viewInfo); this._updateTitle(newSelectedNode); if (!keepChildBladesOpen) { this.portalService.closeBlades(); } return newSelectedNode.handleSelection(); } navidateToNewSub() { const navId = 'subs/new/subscription'; this.router.navigate([navId], { relativeTo: this.route, queryParams: Url.getQueryStringObj() }); } refreshSubs() { this.cacheService.getArm('/subscriptions', true).subscribe(r => { this.userService .getStartupInfo() .first() .subscribe(info => { const subs: Subscription[] = r.json().value; if (!SubUtil.subsChanged(info.subscriptions, subs)) { return; } info.subscriptions = subs; this.userService.updateStartupInfo(info); }); }); } private _logDashboardTypeChange( oldDashboard: DashboardType, newDashboard: DashboardType, oldResourceId?: string, newResourceId?: string ) { const oldDashboardType = DashboardType[oldDashboard]; const newDashboardType = DashboardType[newDashboard]; this.aiService.trackEvent('/sidenav/change-dashboard', { newResourceId, oldResourceId, source: oldDashboardType, dest: newDashboardType, }); } private _updateTitle(node: TreeNode) { const pathNames = node.getTreePathNames(); let title = ''; let subtitle = ''; for (let i = 0; i < pathNames.length; i++) { if (i % 2 === 1) { title += pathNames[i] + ' - '; } } // Remove trailing dash if (title.length > 3) { title = title.substring(0, title.length - 3); } if (!title) { title = this.translateService.instant(PortalResources.functionApps); subtitle = ''; } else { subtitle = this.translateService.instant(PortalResources.functionApps); } this.portalService.updateBladeInfo(title, subtitle); } clearView(resourceId: string) { // We only want to clear the view if the user is currently looking at something // under the tree path being deleted if (this.resourceId.startsWith(resourceId)) { this.router.navigate(['blank'], { relativeTo: this.route, queryParams: Url.getQueryStringObj() }); } } search(event: any) { if (typeof event === 'string') { this._searchTermStream.next(event); this.hasValue = !!event; } else { this.hasValue = !!event.target.value; const startPos = event.target.selectionStart; const endPos = event.target.selectionEnd; // TODO: [ehamai] - this is a hack and it's not perfect. Basically everytime we update // the searchTerm, we end up resetting the cursor. It's better than before, but // it's still not great because if the user types really fast, the cursor still moves. this._searchTermStream.next(event.target.value); if (event.target.value.length !== startPos) { setTimeout(() => { event.target.selectionStart = startPos; event.target.selectionEnd = endPos; }); } } } searchExact(term: string) { this.hasValue = !!term; this._searchTermStream.next(`"${term}"`); } clearSearch() { this.hasValue = false; this._searchTermStream.next(''); } onSubscriptionsSelect(subscriptions: Subscription[]) { let subIds: string[]; if (subscriptions.length === this.subscriptionOptions.length) { subIds = []; // Equivalent of all subs } else { subIds = subscriptions.map<string>(s => s.subscriptionId); } const storedSelectedSubIds: StoredSubscriptions = { id: LocalStorageKeys.savedSubsKey, subscriptions: subIds, }; this.localStorageService.setItem(storedSelectedSubIds.id, storedSelectedSubIds); this.selectedSubscriptions = subscriptions; this._subscriptionsStream.next(subscriptions); if (subscriptions.length === this.subscriptionOptions.length) { this._updateSubDisplayText(this.allSubscriptions); } else if (subscriptions.length > 1) { this._updateSubDisplayText(this.translateService.instant(PortalResources.sideNav_SubscriptionCount).format(subscriptions.length)); } else { this._updateSubDisplayText(`${subscriptions[0].displayName}`); } } // The multi-dropdown component has its own default display text values, // so we need to make sure we're always overwriting them. But if we simply // set the value to the same value twice, no change notification will happen. private _updateSubDisplayText(displayText: string) { setTimeout(() => { this.subscriptionsDisplayText = ''; this.subscriptionsDisplayText = displayText; }); } private _updateSubscriptions(info: StartupInfo<void>) { const savedSubs = <StoredSubscriptions>this.localStorageService.getItem(LocalStorageKeys.savedSubsKey); const savedSelectedSubscriptionIds = savedSubs ? savedSubs.subscriptions : []; let descriptor: ArmSiteDescriptor | null; if (info.resourceId) { descriptor = new ArmSiteDescriptor(info.resourceId); } let count = 0; this.subscriptionOptions = info.subscriptions .map(e => { let subSelected: boolean; if (descriptor) { subSelected = descriptor.subscription === e.subscriptionId; } else { // Multi-dropdown defaults to all of none is selected. So setting it here // helps us figure out whether we need to limit the # of initial subscriptions subSelected = savedSelectedSubscriptionIds.length === 0 || savedSelectedSubscriptionIds.findIndex(s => s === e.subscriptionId) > -1; } if (subSelected) { count++; } return { displayLabel: e.displayName, value: e, isSelected: subSelected && count <= ARM.MaxSubscriptionBatchSize, }; }) .sort((a, b) => a.displayLabel.localeCompare(b.displayLabel)); } }
the_stack
import { Yoco } from '@3yourmind/yoco' import { Instance } from '@popperjs/core/lib' import { onMounted, Ref, watchEffect } from '@vue/composition-api' import { DatePicker as ElDate } from 'element-ui' import { KottiField } from '../kotti-field/types' import { KottiFieldDate, KottiFieldDateRange, KottiFieldDateTime, KottiFieldDateTimeRange, } from './types' type Values = | KottiFieldDate.Value | KottiFieldDateRange.Value | KottiFieldDateTime.Value | KottiFieldDateTimeRange.Value type HookParameters<DATA_TYPE extends Values> = { elDateRef: Ref<ElDateWithInternalAPI | null> field: KottiField.Hook.Returns<DATA_TYPE, string | null> inputContainerRef: Ref<Element | null> popperHeight: string popperWidth: string } export type ElDateWithInternalAPI = ElDate & { blur(): void haveTrigger: boolean picker: Vue & { $el: HTMLElement leftLabel: string rightLabel: string width: number } popperJS: Instance pickerVisible: boolean referenceElm: Element showClose: boolean } const getDateComponent = <DATA_TYPE extends Values>({ elDateRef, }: Pick<HookParameters<DATA_TYPE>, 'elDateRef'>) => { const dateComponent = elDateRef.value if (dateComponent === null) throw new Error('el-date not available') return dateComponent } /** * `picker` (the popper component) is (un)set with `(un)mountPicker`. * dependency tracking is done through `pickerVisible`, an internally computed prop, * because the `picker` gets a new reference on each call of `mountPicker()`. * so using any property on the picker to trigger the `watchEffect` won’t work. * * if a field is disabled, clicking on it, will set dateComponent.pickerVisible to true * instaneously but won't open the picker (dateComponent.picker will remain null) * and `pickerVisible` will reset itself * therefore, isPickerVisible() has to guard that picker exists * * NOTE: The order inside if-condition in any `watchEffect` hook matters * so pickerVisible needs to be accessed first */ const isPickerVisible = (dateComponent: ElDateWithInternalAPI) => dateComponent.pickerVisible && dateComponent.picker const useInputDecoration = <DATA_TYPE extends Values>({ elDateRef, }: Pick<HookParameters<DATA_TYPE>, 'elDateRef'>) => { // eslint-disable-next-line sonarjs/cognitive-complexity onMounted(() => { const dateComponent = getDateComponent({ elDateRef }) // replace el-input affix icons with yoco icons for (const icon of dateComponent.$el.querySelectorAll('.el-input__icon')) icon.classList.add('yoco') const prefixIcon = dateComponent.$el.querySelector( '.el-input__icon.el-icon-time, .el-input__icon.el-icon-date', ) // DO NOT misuse `append` in a hook that will retriger multiple times in the same lifecycle; // make sure the node you're adding is not already there (see other usage here) OR use `innerHTML` prefixIcon?.append( prefixIcon.classList.contains('el-icon-time') ? Yoco.Icon.CALENDAR_CLOCK : Yoco.Icon.CALENDAR, ) let suffixIcon: Element | null = null watchEffect(() => { const dateComponent = getDateComponent({ elDateRef }) // don't refactor out of hooks // if `haveTrigger` is false, the suffixIcon is not rendered; `v-if` condition on the suffixIcon of el-ui dates if (dateComponent.haveTrigger) { // these are the default classes added to suffixIcon // there are more classes added when the clearIcon is hidden/shown // selecting with default selectors guarantees we get a suffixIcon even if it's hidden as long // as it's rendered. The other hook will handle the show/hide effect, while this should handle the existence of suffixIcon suffixIcon = dateComponent.$el.querySelector( '.el-input__icon.el-range__close-icon, .el-input__icon:not(.el-icon-date):not(.el-icon-time)', ) } }) watchEffect(() => { const dateComponent = getDateComponent({ elDateRef }) /** * true onMouseEnter (when value is not Empty & field is clearable) * false onMouseLeave or when value is Empty or when the field is not clearable */ const showClear = dateComponent.showClose if (suffixIcon) { if (!suffixIcon.classList.contains('yoco')) suffixIcon.classList.add('yoco') if (showClear) { if (!suffixIcon.hasChildNodes()) suffixIcon.append('close') } else { if (suffixIcon.hasChildNodes() && suffixIcon.lastChild) suffixIcon.removeChild(suffixIcon.lastChild) } } }) }) } /** * Allow Inputs to Shrink * @see {@link https://stackoverflow.com/a/29990524/2857873} */ const useInputSizeFix = <DATA_TYPE extends Values>({ elDateRef, }: Pick<HookParameters<DATA_TYPE>, 'elDateRef'>) => { onMounted(() => { const dateComponent = getDateComponent({ elDateRef }) const elInputs = dateComponent.$el.querySelectorAll( '.el-input__inner, .el-range-input', ) Array.from(elInputs).forEach((element) => element.setAttribute('size', '1')) }) } const usePickerDimensionsFix = <DATA_TYPE extends Values>({ elDateRef, popperWidth, popperHeight, }: Pick< HookParameters<DATA_TYPE>, 'elDateRef' | 'popperHeight' | 'popperWidth' >) => { onMounted(() => { watchEffect(() => { const dateComponent = getDateComponent({ elDateRef }) if (isPickerVisible(dateComponent)) { dateComponent.picker.$el.style.width = popperWidth dateComponent.picker.$el.style.height = popperHeight /** * HACK: to force re-compute the boundaries of the popper element (through the `update` prototype function), * thus properly position it. * * When we open the date-picker we trigger `showPicker` * https://github.com/ElemeFE/element/blob/649670c55a45c7343eb7148565e2d873bc3d52dd/packages/date-picker/src/picker.vue#L806 * which calls `updatePopper` from the mixin vue-popper, which, in turn, either * creates a new PopperJs instance or updates the already-exisiting instance's props * https://github.com/ElemeFE/element/blob/649670c55a45c7343eb7148565e2d873bc3d52dd/src/utils/vue-popper.js#L120 * In the latter case, it calls the prototype-defined function `update` from popper.js * https://github.com/ElemeFE/element/blob/3ceec7aa6a7ab46e61dbafa4c68b77ba09384b40/src/utils/popper.js#L224 * to compute the boundaries of the popper, and thus its placement, among other things. * * On the first trigger of `showPopper`, a popperJs instance is created with the height and width defined by element-ui. * After creation, we mutate the popper width and height to fit our kotti styles and needs. * This mutation changes the boundaries of the popper without triggering a position adjustment. So, we force it. */ dateComponent.popperJS.update() } }) }) } const usePickerInnerInputsFix = <DATA_TYPE extends Values>({ elDateRef, }: Pick<HookParameters<DATA_TYPE>, 'elDateRef'>) => { onMounted(() => { watchEffect(() => { const dateComponent = getDateComponent({ elDateRef }) if (isPickerVisible(dateComponent)) { const innerInputsWrapper: Array<Element> = Array.from( dateComponent.picker.$el.querySelectorAll( '.el-date-picker__editor-wrap, .el-date-range-picker__time-picker-wrap', ), ) innerInputsWrapper.forEach((input) => input.classList.add( 'kt-field__wrapper', 'kt-field__wrapper--is-small', 'kt-field__wrapper--is-validation-empty', ), ) const innerInputs: Array<Element> = Array.from( dateComponent.picker.$el.querySelectorAll('.el-input__inner'), ) innerInputs.forEach((input) => { input.classList.add('kt-field__input-container') input.setAttribute('size', '1') }) } }) }) } /** * If the field is loading, we want to unfocus in case the popper is open * so that when isLoading changes, the popper isn't misplaced */ const usePickerMisplacementFix = <DATA_TYPE extends Values>({ elDateRef, field, }: Pick<HookParameters<DATA_TYPE>, 'elDateRef' | 'field'>) => { onMounted(() => { watchEffect(() => { const dateComponent = getDateComponent({ elDateRef }) if (field.isLoading || field.isDisabled) return dateComponent.blur() }) }) } /** * add yoco class to header icons to enable yoco icons */ const usePickerNavigationIcons = <DATA_TYPE extends Values>({ elDateRef, }: Pick<HookParameters<DATA_TYPE>, 'elDateRef'>) => { onMounted(() => { watchEffect(() => { const dateComponent = getDateComponent({ elDateRef }) if (isPickerVisible(dateComponent)) { const insertYocoIcon = (icon: Yoco.Icon) => `<i class="yoco">${icon}</i>` const pickerHeaderIcons: Array<HTMLElement> = Array.from( dateComponent.picker.$el.querySelectorAll( '.el-picker-panel__icon-btn', ), ) const headerYocoIcons = [ insertYocoIcon(Yoco.Icon.CHEVRON_LEFT_DOUBLE), insertYocoIcon(Yoco.Icon.CHEVRON_LEFT), insertYocoIcon(Yoco.Icon.CHEVRON_RIGHT_DOUBLE), insertYocoIcon(Yoco.Icon.CHEVRON_RIGHT), ] pickerHeaderIcons.forEach((icon, index) => { icon.innerHTML = headerYocoIcons[index] }) } }) }) } /** * placement fix * same hack as the one used in the selects but for the datepickers, the popper component.data * are merged with the DateComponent’s own data, therefore allowing access to properties on popper component * directly through dateComponent */ const usePickerPlacementFix = <DATA_TYPE extends Values>({ elDateRef, inputContainerRef, }: Pick<HookParameters<DATA_TYPE>, 'elDateRef' | 'inputContainerRef'>) => { onMounted(() => { const dateComponent = getDateComponent({ elDateRef }) const ktFieldDateInputContainer = inputContainerRef.value if (ktFieldDateInputContainer === null) throw new Error('kt-field-date__input-container not available') dateComponent.referenceElm = ktFieldDateInputContainer }) } const useRangePickerHeaderFix = <DATA_TYPE extends Values>({ elDateRef, }: Pick<HookParameters<DATA_TYPE>, 'elDateRef'>) => { onMounted(() => { watchEffect(() => { const dateComponent = getDateComponent({ elDateRef }) if (isPickerVisible(dateComponent)) { // change when any of the navigation buttons in the range-pickers are clicked const dates = [ dateComponent.picker.leftLabel?.split(/\s+/) ?? ['', ''], dateComponent.picker.rightLabel?.split(/\s+/) ?? ['', ''], ] const headers = dateComponent.picker.$el.querySelectorAll( '.el-date-range-picker__header', ) headers.forEach((header, index) => { const fullDate = header.querySelector('div') if (fullDate) { fullDate.innerHTML = dates[index][0] // leftMonth or rightMonth if (header.lastChild?.nodeType === Node.TEXT_NODE) { // we add a text node each call with the new year value, thus need to remove the old first header.removeChild(header.lastChild) } header.append(dates[index][1]) } }) } }) }) } export const usePicker = <DATA_TYPE extends Values>({ elDateRef, field, inputContainerRef, popperHeight, popperWidth, }: HookParameters<DATA_TYPE>) => { useInputDecoration({ elDateRef }) useInputSizeFix({ elDateRef }) usePickerDimensionsFix({ elDateRef, popperHeight, popperWidth, }) usePickerInnerInputsFix({ elDateRef }) usePickerMisplacementFix({ elDateRef, field }) usePickerNavigationIcons({ elDateRef }) usePickerPlacementFix({ elDateRef, inputContainerRef }) useRangePickerHeaderFix({ elDateRef }) }
the_stack
import { ILabelArrayAndMap } from "../../label_structure/ILabelArrayAndMap"; import { PredictionStructureWithPluralEvaluationLabelObject } from "../../label_structure/PredictionStructureWithPluralEvaluationLabelObject"; import { PredictionStructureWithPluralEvaluationLabelString } from "../../label_structure/PredictionStructureWithPluralEvaluationLabelString"; import { IConfusionMatrixBaseMicroAverageMetrics } from "./IConfusionMatrixBaseMicroAverageMetrics"; import { IConfusionMatrixMeanDerivedMetrics } from "./IConfusionMatrixMeanDerivedMetrics"; import { IConfusionMatrixMeanMetrics } from "./IConfusionMatrixMeanMetrics"; import { IConfusionMatrixQuantileMetrics } from "./IConfusionMatrixQuantileMetrics"; import { IConfusionMatrixSummationMetrics } from "./IConfusionMatrixSummationMetrics"; import { BinaryConfusionMatrix } from "./BinaryConfusionMatrix"; import { ConfusionMatrix } from "./ConfusionMatrix"; import { PerInstanceMultiLabelConfusionMatrix } from "./PerInstanceMultiLabelConfusionMatrix"; import { PerInstanceMultiLabelObjectConfusionMatrix } from "./PerInstanceMultiLabelObjectConfusionMatrix"; import { MultiLabelConfusionMatrix } from "./MultiLabelConfusionMatrix"; import { MultiLabelObjectConfusionMatrix } from "./MultiLabelObjectConfusionMatrix"; import { MultiLabelObjectConfusionMatrixExact } from "./MultiLabelObjectConfusionMatrixExact"; import { MultiLabelObjectConfusionMatrixSubset } from "./MultiLabelObjectConfusionMatrixSubset"; import { IMultiLabelObjectConfusionMatrixEvaluationStructure } from "./IMultiLabelObjectConfusionMatrixEvaluationStructure"; import { IMultiLabelObjectConfusionMatrixExactEvaluationStructure } from "./IMultiLabelObjectConfusionMatrixExactEvaluationStructure"; import { IMultiLabelObjectConfusionMatrixSubsetEvaluationStructure } from "./IMultiLabelObjectConfusionMatrixSubsetEvaluationStructure"; import { Utility } from "../../utility/Utility"; export class UtilityConfusionMatrix { public static readonly ColumnNamePerLabel: string = "Per-Label"; public static readonly ColumnNamePerInstance: string = "Per-Instance"; public static readonly ColumnNameMicroAverageRaw: string = "Micro-Average"; public static readonly ColumnNameMicroAverage: string = Utility.getBolded(UtilityConfusionMatrix.ColumnNameMicroAverageRaw); public static readonly DescriptionMicroAverage: string = ` This metric follows the micro-average metric defined in <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html">Scikit-Learn Classification Report</a>. The computing process iterates through an array of per-label/per-instance binary confusion matrices and calculates the sums of per-label/per-instance "#TruePositives" and per-label/per-instance "Support", respectively. The "Support" sum is stored in this row's "Total" field and "#TruePositives" sum in the "#TruePositives" field. This metric is then the ratio of the "#TruePositives" sum over "Total." `; public static readonly ColumnNameMicroFirstQuartile: string = Utility.getBolded("Micro-First-Quartile"); public static readonly DescriptionMicroFirstQuartile: string = ` Average (or mean) is not a <a href="https://en.wikipedia.org/wiki/Robust_statistics">robust statistics</a> that average can be easily influenced by outliers. Therefore, we also compute robust quantile-based metrics in this report. For every metric in this row, e.g., precision, the computing process collects the per-label/per-instance precision metrics from an array of per-label/per-instance binary confusion matrices, sorts them, and then replicates each per-label/per-instance precision by the per-label support. It then finds the first quartile of the metric from the expanded metric series. These first-quartiles are the metrics' lower bound for the top 75% expanded binary confusion matrix entries. `; public static readonly ColumnNameMicroMedian: string = Utility.getBolded("Micro-Median"); public static readonly DescriptionMicroMedian: string = ` Similar to the previous row, but metrics in this row are the medians, another robust statistic. These medians are the metrics' lower bound for the top 50% expanded binary confusion matrix entries. `; public static readonly ColumnNameMicroThirdQuartile: string = "Micro-Third-Quartile"; public static readonly DescriptionMicroThirdQuartile: string = ` Similar to the previous rows, but metrics in this row are the third quartiles. These third-quartiles are the metrics' lower bound for the top 25% expanded binary confusion matrix entries. `; public static readonly ColumnNameMacroFirstQuartile: string = Utility.getBolded("Macro-First-Quartile"); public static readonly DescriptionMacroFirstQuartile: string = ` Above three quantile metrics are micro, i.e., they are calcuated on a metric series expanded by supports. Macro quantile metrics are calculated on the un-expanded series of metrics. The first quartiles are the metrics' lower bound for the top 75% binary confusion matrix entries. `; public static readonly ColumnNameMacroMedian: string = Utility.getBolded("Macro-Median"); public static readonly DescriptionMacroMedian: string = ` Similar to the previous row, but metrics in this row focuses on median. These medians are the metrics' lower bound for the top 50% expanded binary confusion matrix entries. `; public static readonly ColumnNameMacroThirdQuartile: string = "Macro-Third-Quartile"; public static readonly DescriptionMacroThirdQuartile: string = ` Similar to the previous row, but metrics in this row focuses on the third quartile. These third-quartiles are the metrics' lower bound for the top 25% expanded binary confusion matrix entries. `; public static readonly ColumnNameSummationMicroAverageRaw: string = `Summation ${UtilityConfusionMatrix.ColumnNameMicroAverageRaw}`; public static readonly ColumnNameSummationMicroAverage: string = Utility.getBolded(UtilityConfusionMatrix.ColumnNameSummationMicroAverageRaw); public static readonly DescriptionSummationMicroAverage: string = ` The metrics in this row are a little bit different from those of ${UtilityConfusionMatrix.ColumnNameMicroAverage}. The computng process first sums up per-label/per-instance "#TruePositives", "#FalsePositives", "#TrueNegatives", and "#FalseNegatives" metrics, respectively, uses them to directly construct a binary confusion matrix, and calculates the other metrics, such as Precision, Recall, F1, Accuracy, etc. `; public static readonly ColumnNameMacroAverageRaw: string = "Macro-Average"; public static readonly ColumnNameMacroAverage: string = Utility.getBolded(UtilityConfusionMatrix.ColumnNameMacroAverageRaw); public static readonly DescriptionMacroAverage: string = ` This metric follows the macro-average metric defined in <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html">Scikit-Learn Classification Report</a>. The computing process calcuates simple arithmetic means of the per-label/per-instance Precision, Recall, F1, and Accuracy metrics, repectively, from a series of binary confusion matrices. `; public static readonly ColumnNameSummationMacroAverage: string = `Summation ${UtilityConfusionMatrix.ColumnNameMacroAverageRaw}`; public static readonly DescriptionSummationMacroAverage: string = ` The calculating process for the metrics in this row is a little bit different from ${UtilityConfusionMatrix.ColumnNameMacroAverage}. It first calculates the averages of per-label/per-instance "#TruePositives", "#FalsePositives", "#TrueNegatives", and "#FalseNegatives" metrics, respectively, uses them to directly construct a binary confusion matrix, and calculates the other metrics, such as Precision, Recall, F1, Accuracy, etc. `; public static readonly ColumnNamePositiveSupportMacroAverage: string = `Positive-Support ${UtilityConfusionMatrix.ColumnNameMacroAverageRaw}`; public static readonly DescriptionPositiveSupportMacroAverage: string = ` The metrics in this row are similar to those of ${UtilityConfusionMatrix.ColumnNameMacroAverage}. However, instead of averaging over all train-set labels, metrics in this rows are the averages of test-set labels, i.e., labels with a positive support in the test set. Even though one might expect every label (in the train-set) should have some test instances, but sometimes a test-set might just not have test instances for some train-set labels. "Positive-support" metrics put an focus on test-set labels. A test set might even contain instances whose labels are not in the train set. Those labels are renamed UNKNOWN for evaluation purpose. `; public static readonly ColumnNamePositiveSupportSummationMacroAverage: string = `Positive-Support ${UtilityConfusionMatrix.ColumnNameSummationMacroAverage}`; public static readonly DescriptionPositiveSupportSummationMacroAverage: string = ` The metrics in this row are similar to those of ${UtilityConfusionMatrix.ColumnNameSummationMacroAverage}, but forcus on labels with test instances. `; public static readonly ColumnNameWeightedMacroAverage: string = `Weighted ${UtilityConfusionMatrix.ColumnNameMacroAverageRaw}`; public static readonly DescriptionWeightedMacroAverage: string = ` This metric follows the weighted-average metric defined in <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html">Scikit-Learn Classification Report</a>. The computing process calcuates support/prevalency-weighted means of the per-label/per-instance Precision, Recall, F1, and Accuracy metrics, repectively. `; public static readonly ColumnNameWeightedSummationMacroAverage: string = `Weighted ${UtilityConfusionMatrix.ColumnNameSummationMacroAverage}`; public static readonly DescriptionWeightedSummationMacroAverage: string = ` The calculating process for the metrics in this row is a little bit different from ${UtilityConfusionMatrix.DescriptionWeightedMacroAverage}. It first calculates the weighted averages of per-label/per-instance "#TruePositives", "#FalsePositives", "#TrueNegatives", and "#FalseNegatives" metrics, respectively, then constructs a binary confusion matrix, and calculates the other metrics, such as Precision, Recall, F1, Accuracy, etc. `; public static readonly ColumnNameMultiLabelExactAggregate: string = Utility.getBolded("Multi-Label Exact Aggregate"); public static readonly DescriptionMultiLabelExactAggregate: string = ` This evaluation package also supports multi-label instances and predictions. In another word, a test instance can be labeled and predicted with more than one labels. The above metrics so far are calculated "per label," i.e., an instance can contribute to multiple positive predictions on different labels, thus the above metrics can encourage a model to predict more than one labels per test instances that may achieve better evaluation results. To counter such a behavior, metrics in this row are "per instance," i.e., an instance can only contribute to one positive prediction. The calcuating process does not rely on the per-label binary confusion matrices, but build just one binary confusion matrix in which a true positive prediction is an exact match between the prediction and the ground-truth label sets, otherwise it's a false positive. By the way, there is no negative prediction, so false-nagative and true-negative are both 0. `; public static readonly ColumnNameMultiLabelSubsetAggregate: string = Utility.getBolded("Multi-Label Subset Aggregate"); public static readonly DescriptionMultiLabelSubsetAggregate: string = ` Similar to the previous row, but the metric computing process is less strict. A prediction can be a true positive as long as the predicted label set is a subset of the ground-truth set. This subset rule makes sense as an action taking on a prediction can respond to one of the correctly predicted labels and the action is still proper. Of course, this subset rule can discourage a model from predicting more than one labels (one is the safest strategy), even though a test instance might be labeled with a large ground-truth label set. `; public static generateAssessmentLabelObjectConfusionMatrixMetricsAndHtmlTable( predictionStructures: PredictionStructureWithPluralEvaluationLabelObject[], labelArrayAndMap: ILabelArrayAndMap, toIncludeTrueNegatives: boolean = false, toObfuscate: boolean = false, // ---- NOTE: most likely applicable to entity evaluation, where TF is not used. quantileConfiguration: number = 4): { multiLabelObjectConfusionMatrix: MultiLabelObjectConfusionMatrix; multiLabelObjectConfusionMatrixEvaluation: IMultiLabelObjectConfusionMatrixEvaluationStructure; multiLabelObjectConfusionMatrixExactEvaluation: IMultiLabelObjectConfusionMatrixExactEvaluationStructure; multiLabelObjectConfusionMatrixSubsetEvaluation: IMultiLabelObjectConfusionMatrixSubsetEvaluationStructure; perInstanceMultiLabelObjectConfusionMatrix: PerInstanceMultiLabelObjectConfusionMatrix; perInstanceMultiLabelObjectConfusionMatrixEvaluation: IMultiLabelObjectConfusionMatrixEvaluationStructure; } { const numberInstances: number = predictionStructures.length; const multiLabelObjectConfusionMatrix: MultiLabelObjectConfusionMatrix = new MultiLabelObjectConfusionMatrix( labelArrayAndMap.stringArray, labelArrayAndMap.stringMap, toIncludeTrueNegatives); const multiLabelObjectConfusionMatrixExact: MultiLabelObjectConfusionMatrixExact = new MultiLabelObjectConfusionMatrixExact( labelArrayAndMap.stringArray, labelArrayAndMap.stringMap, toIncludeTrueNegatives); const multiLabelObjectConfusionMatrixSubset: MultiLabelObjectConfusionMatrixSubset = new MultiLabelObjectConfusionMatrixSubset( labelArrayAndMap.stringArray, labelArrayAndMap.stringMap, toIncludeTrueNegatives); const perInstanceMultiLabelObjectConfusionMatrix: PerInstanceMultiLabelObjectConfusionMatrix = new PerInstanceMultiLabelObjectConfusionMatrix( numberInstances, labelArrayAndMap.stringArray, labelArrayAndMap.stringMap, toIncludeTrueNegatives); for (let i = 0; i < numberInstances; i++) { multiLabelObjectConfusionMatrix.addInstanceByLabelObjects( predictionStructures[i].labels, predictionStructures[i].labelsPredicted); multiLabelObjectConfusionMatrixExact.addInstanceByLabelObjects( predictionStructures[i].labels, predictionStructures[i].labelsPredicted); multiLabelObjectConfusionMatrixSubset.addInstanceByLabelObjects( predictionStructures[i].labels, predictionStructures[i].labelsPredicted); perInstanceMultiLabelObjectConfusionMatrix.addInstanceByLabelObjects( i, predictionStructures[i].labels, predictionStructures[i].labelsPredicted); } const multiLabelObjectConfusionMatrixEvaluation: IMultiLabelObjectConfusionMatrixEvaluationStructure = UtilityConfusionMatrix.aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs( multiLabelObjectConfusionMatrix.getBinaryConfusionMatrices(), labelArrayAndMap, [], [], [], UtilityConfusionMatrix.ColumnNamePerLabel + " ", toObfuscate, quantileConfiguration); const multiLabelObjectConfusionMatrixExactEvaluation: IMultiLabelObjectConfusionMatrixExactEvaluationStructure = UtilityConfusionMatrix.aggregateMultiLabelObjectConfusionMatrixExactIntoEvaluationOutputs( multiLabelObjectConfusionMatrixExact, labelArrayAndMap, [], []); const multiLabelObjectConfusionMatrixSubsetEvaluation: IMultiLabelObjectConfusionMatrixSubsetEvaluationStructure = UtilityConfusionMatrix.aggregateMultiLabelObjectConfusionMatrixSubsetIntoEvaluationOutputs( multiLabelObjectConfusionMatrixSubset, labelArrayAndMap, [], []); const perInstanceMultiLabelObjectConfusionMatrixEvaluation: IMultiLabelObjectConfusionMatrixEvaluationStructure = UtilityConfusionMatrix.aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs( perInstanceMultiLabelObjectConfusionMatrix.getBinaryConfusionMatrices(), labelArrayAndMap, [], [], [], UtilityConfusionMatrix.ColumnNamePerInstance + " ", toObfuscate, quantileConfiguration); return { multiLabelObjectConfusionMatrix, multiLabelObjectConfusionMatrixEvaluation, multiLabelObjectConfusionMatrixExactEvaluation, multiLabelObjectConfusionMatrixSubsetEvaluation, perInstanceMultiLabelObjectConfusionMatrix, perInstanceMultiLabelObjectConfusionMatrixEvaluation, }; } public static generateAssessmentLabelStringConfusionMatrixMetricsAndHtmlTable( predictionStructures: PredictionStructureWithPluralEvaluationLabelString[], labelArrayAndMap: ILabelArrayAndMap, toIncludeTrueNegatives: boolean = true, toObfuscate: boolean = false, quantileConfiguration: number = 4): { multiLabelConfusionMatrix: MultiLabelConfusionMatrix; multiLabelConfusionMatrixEvaluation: IMultiLabelObjectConfusionMatrixEvaluationStructure; multiLabelObjectConfusionMatrixExactEvaluation: IMultiLabelObjectConfusionMatrixExactEvaluationStructure; multiLabelObjectConfusionMatrixSubsetEvaluation: IMultiLabelObjectConfusionMatrixSubsetEvaluationStructure; perInstanceMultiLabelConfusionMatrix: PerInstanceMultiLabelConfusionMatrix; perInstanceMultiLabelConfusionMatrixEvaluation: IMultiLabelObjectConfusionMatrixEvaluationStructure; } { const numberInstances: number = predictionStructures.length; const multiLabelConfusionMatrix: MultiLabelConfusionMatrix = new MultiLabelConfusionMatrix( labelArrayAndMap.stringArray, labelArrayAndMap.stringMap, toIncludeTrueNegatives); const multiLabelObjectConfusionMatrixExact: MultiLabelObjectConfusionMatrixExact = new MultiLabelObjectConfusionMatrixExact( labelArrayAndMap.stringArray, labelArrayAndMap.stringMap, toIncludeTrueNegatives); const multiLabelObjectConfusionMatrixSubset: MultiLabelObjectConfusionMatrixSubset = new MultiLabelObjectConfusionMatrixSubset( labelArrayAndMap.stringArray, labelArrayAndMap.stringMap, toIncludeTrueNegatives); const perInstanceMultiLabelConfusionMatrix: PerInstanceMultiLabelConfusionMatrix = new PerInstanceMultiLabelConfusionMatrix( numberInstances, labelArrayAndMap.stringArray, labelArrayAndMap.stringMap, toIncludeTrueNegatives); for (let i = 0; i < numberInstances; i++) { multiLabelConfusionMatrix.addInstanceByLabelIndexes( predictionStructures[i].labelsIndexes, predictionStructures[i].labelsPredictedIndexes); multiLabelObjectConfusionMatrixExact.addInstanceByLabelIndexes( predictionStructures[i].labelsIndexes, predictionStructures[i].labelsPredictedIndexes); multiLabelObjectConfusionMatrixSubset.addInstanceByLabelIndexes( predictionStructures[i].labelsIndexes, predictionStructures[i].labelsPredictedIndexes); perInstanceMultiLabelConfusionMatrix.addInstanceByLabelIndexes( i, predictionStructures[i].labelsIndexes, predictionStructures[i].labelsPredictedIndexes); } const multiLabelConfusionMatrixEvaluation: IMultiLabelObjectConfusionMatrixEvaluationStructure = UtilityConfusionMatrix.aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs( multiLabelConfusionMatrix.getBinaryConfusionMatrices(), labelArrayAndMap, [], [], [], UtilityConfusionMatrix.ColumnNamePerLabel + " ", toObfuscate, quantileConfiguration); const multiLabelObjectConfusionMatrixExactEvaluation: IMultiLabelObjectConfusionMatrixExactEvaluationStructure = UtilityConfusionMatrix.aggregateMultiLabelObjectConfusionMatrixExactIntoEvaluationOutputs( multiLabelObjectConfusionMatrixExact, labelArrayAndMap, [], []); const multiLabelObjectConfusionMatrixSubsetEvaluation: IMultiLabelObjectConfusionMatrixSubsetEvaluationStructure = UtilityConfusionMatrix.aggregateMultiLabelObjectConfusionMatrixSubsetIntoEvaluationOutputs( multiLabelObjectConfusionMatrixSubset, labelArrayAndMap, [], []); const perInstanceMultiLabelConfusionMatrixEvaluation: IMultiLabelObjectConfusionMatrixEvaluationStructure = UtilityConfusionMatrix.aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs( perInstanceMultiLabelConfusionMatrix.getBinaryConfusionMatrices(), labelArrayAndMap, [], [], [], UtilityConfusionMatrix.ColumnNamePerInstance + " ", toObfuscate, quantileConfiguration); return { multiLabelConfusionMatrix, multiLabelConfusionMatrixEvaluation, multiLabelObjectConfusionMatrixExactEvaluation, multiLabelObjectConfusionMatrixSubsetEvaluation, perInstanceMultiLabelConfusionMatrix, perInstanceMultiLabelConfusionMatrixEvaluation, }; } public static aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs( binaryConfusionMatrices: BinaryConfusionMatrix[], labelArrayAndMap: ILabelArrayAndMap, confusionMatrixOutputLines: string[][], confusionMatrixAverageOutputLines: string[][], confusionMatrixAverageDescriptionOutputLines: string[][], columnNamePreffix: string, toObfuscate: boolean = false, quantileConfiguration: number = 4): IMultiLabelObjectConfusionMatrixEvaluationStructure { // ----------------------------------------------------------------------- const confusionMatrix: ConfusionMatrix = new ConfusionMatrix(labelArrayAndMap.stringArray, labelArrayAndMap.stringMap); // ----------------------------------------------------------------------- if (Utility.isEmptyArray(confusionMatrixOutputLines)) { confusionMatrixOutputLines = []; } if (Utility.isEmptyArray(confusionMatrixAverageOutputLines)) { confusionMatrixAverageOutputLines = []; } if (Utility.isEmptyArray(confusionMatrixAverageDescriptionOutputLines)) { confusionMatrixAverageDescriptionOutputLines = []; } // ----------------------------------------------------------------------- Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), binaryConfusionMatrices.length=${binaryConfusionMatrices.length}`); for (let i: number = 0; i < binaryConfusionMatrices.length; i++) { const label: string = Utility.carefullyAccessStringArray(labelArrayAndMap.stringArray, i); const precision: number = Utility.round(binaryConfusionMatrices[i].getPrecision()); const recall: number = Utility.round(binaryConfusionMatrices[i].getRecall()); const f1: number = Utility.round(binaryConfusionMatrices[i].getF1Measure()); const accuracy: number = Utility.round(binaryConfusionMatrices[i].getAccuracy()); const truePositives: number = binaryConfusionMatrices[i].getTruePositives(); const falsePositives: number = binaryConfusionMatrices[i].getFalsePositives(); const trueNegatives: number = binaryConfusionMatrices[i].getTrueNegatives(); const falseNegatives: number = binaryConfusionMatrices[i].getFalseNegatives(); const support: number = binaryConfusionMatrices[i].getSupport(); const total: number = binaryConfusionMatrices[i].getTotal(); const confusionMatrixOutputLine: any[] = [ Utility.outputString(label, toObfuscate), precision, recall, f1, accuracy, truePositives, falsePositives, trueNegatives, falseNegatives, support, total, ]; confusionMatrixOutputLines.push(confusionMatrixOutputLine); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), binaryConfusionMatrices[${i}].getTotal() =${binaryConfusionMatrices[i].getTotal()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), binaryConfusionMatrices[${i}].getTruePositives() =${binaryConfusionMatrices[i].getTruePositives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), binaryConfusionMatrices[${i}].getFalsePositives()=${binaryConfusionMatrices[i].getFalsePositives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), binaryConfusionMatrices[${i}].getTrueNegatives() =${binaryConfusionMatrices[i].getTrueNegatives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), binaryConfusionMatrices[${i}].getFalseNegatives()=${binaryConfusionMatrices[i].getFalseNegatives()}`); } const confusionMatrixMetricsHtml: string = Utility.convertDataArraysToIndexedHtmlTable( "Confusion matrix metrics", confusionMatrixOutputLines, ["Label", "Precision", "Recall", "F1", "Accuracy", "#TruePositives", "#FalsePositives", "#TrueNegatives", "#FalseNegatives", "Support", "Total"]); // ----------------------------------------------------------------------- const microAverageMetrics: IConfusionMatrixBaseMicroAverageMetrics = confusionMatrix.getMicroAverageMetrics(binaryConfusionMatrices); const confusionMatrixOutputLineMicroAverage: any[] = [ UtilityConfusionMatrix.ColumnNameMicroAverage, "N/A", // ---- Utility.round(microAverageMetrics.averagePrecisionRecallF1Accuracy), // ---- NOTE ---- in multi-class, there is no negative, so calculation of precision is equal to that of recall. "N/A", // ---- Utility.round(microAverageMetrics.averagePrecisionRecallF1Accuracy), // ---- NOTE ---- in multi-class, there is no negative, so calculation of precision is equal to that of recall. // tslint:disable-next-line: max-line-length "N/A", // ---- Utility.round(microAverageMetrics.averagePrecisionRecallF1Accuracy), // ---- NOTE ---- in multi-class, there is no negative, so calculation of precision is equal to that of recall. // tslint:disable-next-line: max-line-length Utility.getBolded(Utility.round(microAverageMetrics.averagePrecisionRecallF1Accuracy)), // ---- NOTE ---- in multi-class, there is no negative, so calculation of precision is equal to that of recall. microAverageMetrics.truePositives, "N/A", // ---- NOTE ---- in multi-class, there is no negative, so calculation of precision is equal to that of recall. "N/A", microAverageMetrics.falseNegatives, "N/A", microAverageMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineMicroAverage); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameMicroAverage, UtilityConfusionMatrix.DescriptionMicroAverage, ]); // ----------------------------------------------------------------------- const microQuantileMetrics: IConfusionMatrixQuantileMetrics = confusionMatrix.getMicroQuantileMetrics(binaryConfusionMatrices, quantileConfiguration); const confusionMatrixOutputLineMicroQuantile1: any[] = [ UtilityConfusionMatrix.ColumnNameMicroFirstQuartile, Utility.canAccessNumberArray(microQuantileMetrics.quantilesPrecisions, 1) ? Utility.round(microQuantileMetrics.quantilesPrecisions[1]) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesRecalls, 1) ? Utility.round(microQuantileMetrics.quantilesRecalls[1]) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesF1Scores, 1) ? Utility.getBolded(Utility.round(microQuantileMetrics.quantilesF1Scores[1])) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesAccuracies, 1) ? Utility.getBolded(Utility.round(microQuantileMetrics.quantilesAccuracies[1])) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesTruePositives, 1) ? microQuantileMetrics.quantilesTruePositives[1] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesFalsePositives, 1) ? microQuantileMetrics.quantilesFalsePositives[1] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesTrueNegatives, 1) ? microQuantileMetrics.quantilesTrueNegatives[1] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesFalseNegatives, 1) ? microQuantileMetrics.quantilesFalseNegatives[1] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesSupports, 1) ? microQuantileMetrics.quantilesSupports[1] : "N/A", microQuantileMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineMicroQuantile1); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameMicroFirstQuartile, UtilityConfusionMatrix.DescriptionMicroFirstQuartile, ]); const confusionMatrixOutputLineMicroQuantile2: any[] = [ UtilityConfusionMatrix.ColumnNameMicroMedian, Utility.canAccessNumberArray(microQuantileMetrics.quantilesPrecisions, 2) ? Utility.round(microQuantileMetrics.quantilesPrecisions[2]) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesRecalls, 2) ? Utility.round(microQuantileMetrics.quantilesRecalls[2]) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesF1Scores, 2) ? Utility.getBolded(Utility.round(microQuantileMetrics.quantilesF1Scores[2])) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesAccuracies, 2) ? Utility.getBolded(Utility.round(microQuantileMetrics.quantilesAccuracies[2])) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesTruePositives, 2) ? microQuantileMetrics.quantilesTruePositives[2] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesFalsePositives, 2) ? microQuantileMetrics.quantilesFalsePositives[2] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesTrueNegatives, 2) ? microQuantileMetrics.quantilesTrueNegatives[2] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesFalseNegatives, 2) ? microQuantileMetrics.quantilesFalseNegatives[2] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesSupports, 2) ? microQuantileMetrics.quantilesSupports[2] : "N/A", microQuantileMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineMicroQuantile2); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameMicroMedian, UtilityConfusionMatrix.DescriptionMicroMedian, ]); const confusionMatrixOutputLineMicroQuantile3: any[] = [ UtilityConfusionMatrix.ColumnNameMicroThirdQuartile, Utility.canAccessNumberArray(microQuantileMetrics.quantilesPrecisions, 3) ? Utility.round(microQuantileMetrics.quantilesPrecisions[3]) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesRecalls, 3) ? Utility.round(microQuantileMetrics.quantilesRecalls[3]) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesF1Scores, 3) ? Utility.round(microQuantileMetrics.quantilesF1Scores[3]) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesAccuracies, 3) ? Utility.round(microQuantileMetrics.quantilesAccuracies[3]) : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesTruePositives, 3) ? microQuantileMetrics.quantilesTruePositives[3] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesFalsePositives, 3) ? microQuantileMetrics.quantilesFalsePositives[3] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesTrueNegatives, 3) ? microQuantileMetrics.quantilesTrueNegatives[3] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesFalseNegatives, 3) ? microQuantileMetrics.quantilesFalseNegatives[3] : "N/A", Utility.canAccessNumberArray(microQuantileMetrics.quantilesSupports, 3) ? microQuantileMetrics.quantilesSupports[3] : "N/A", microQuantileMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineMicroQuantile3); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameMicroThirdQuartile, UtilityConfusionMatrix.DescriptionMicroThirdQuartile, ]); // ----------------------------------------------------------------------- const macroQuantileMetrics: IConfusionMatrixQuantileMetrics = confusionMatrix.getMacroQuantileMetrics(binaryConfusionMatrices, quantileConfiguration); const confusionMatrixOutputLineMacroQuantile1: any[] = [ UtilityConfusionMatrix.ColumnNameMacroFirstQuartile, Utility.canAccessNumberArray(macroQuantileMetrics.quantilesPrecisions, 1) ? Utility.round(macroQuantileMetrics.quantilesPrecisions[1]) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesRecalls, 1) ? Utility.round(macroQuantileMetrics.quantilesRecalls[1]) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesF1Scores, 1) ? Utility.getBolded(Utility.round(macroQuantileMetrics.quantilesF1Scores[1])) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesAccuracies, 1) ? Utility.getBolded(Utility.round(macroQuantileMetrics.quantilesAccuracies[1])) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesTruePositives, 1) ? macroQuantileMetrics.quantilesTruePositives[1] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesFalsePositives, 1) ? macroQuantileMetrics.quantilesFalsePositives[1] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesTrueNegatives, 1) ? macroQuantileMetrics.quantilesTrueNegatives[1] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesFalseNegatives, 1) ? macroQuantileMetrics.quantilesFalseNegatives[1] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesSupports, 1) ? macroQuantileMetrics.quantilesSupports[1] : "N/A", macroQuantileMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineMacroQuantile1); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameMacroFirstQuartile, UtilityConfusionMatrix.DescriptionMacroFirstQuartile, ]); const confusionMatrixOutputLineMacroQuantile2: any[] = [ UtilityConfusionMatrix.ColumnNameMacroMedian, Utility.canAccessNumberArray(macroQuantileMetrics.quantilesPrecisions, 2) ? Utility.round(macroQuantileMetrics.quantilesPrecisions[2]) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesRecalls, 2) ? Utility.round(macroQuantileMetrics.quantilesRecalls[2]) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesF1Scores, 2) ? Utility.getBolded(Utility.round(macroQuantileMetrics.quantilesF1Scores[2])) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesAccuracies, 2) ? Utility.getBolded(Utility.round(macroQuantileMetrics.quantilesAccuracies[2])) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesTruePositives, 2) ? macroQuantileMetrics.quantilesTruePositives[2] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesFalsePositives, 2) ? macroQuantileMetrics.quantilesFalsePositives[2] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesTrueNegatives, 2) ? macroQuantileMetrics.quantilesTrueNegatives[2] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesFalseNegatives, 2) ? macroQuantileMetrics.quantilesFalseNegatives[2] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesSupports, 2) ? macroQuantileMetrics.quantilesSupports[2] : "N/A", macroQuantileMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineMacroQuantile2); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameMacroMedian, UtilityConfusionMatrix.DescriptionMacroMedian, ]); const confusionMatrixOutputLineMacroQuantile3: any[] = [ UtilityConfusionMatrix.ColumnNameMacroThirdQuartile, Utility.canAccessNumberArray(macroQuantileMetrics.quantilesPrecisions, 3) ? Utility.round(macroQuantileMetrics.quantilesPrecisions[3]) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesRecalls, 3) ? Utility.round(macroQuantileMetrics.quantilesRecalls[3]) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesF1Scores, 3) ? Utility.round(macroQuantileMetrics.quantilesF1Scores[3]) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesAccuracies, 3) ? Utility.round(macroQuantileMetrics.quantilesAccuracies[3]) : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesTruePositives, 3) ? macroQuantileMetrics.quantilesTruePositives[3] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesFalsePositives, 3) ? macroQuantileMetrics.quantilesFalsePositives[3] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesTrueNegatives, 3) ? macroQuantileMetrics.quantilesTrueNegatives[3] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesFalseNegatives, 3) ? macroQuantileMetrics.quantilesFalseNegatives[3] : "N/A", Utility.canAccessNumberArray(macroQuantileMetrics.quantilesSupports, 3) ? macroQuantileMetrics.quantilesSupports[3] : "N/A", macroQuantileMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineMacroQuantile3); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameMacroThirdQuartile, UtilityConfusionMatrix.DescriptionMacroThirdQuartile, ]); // ----------------------------------------------------------------------- const summationMicroAverageMetrics: IConfusionMatrixSummationMetrics = confusionMatrix.getSummationMicroAverageMetrics(binaryConfusionMatrices); const confusionMatrixOutputLineSummationMicroAverage: any[] = [ UtilityConfusionMatrix.ColumnNameSummationMicroAverage, Utility.round(summationMicroAverageMetrics.summationPrecision), Utility.round(summationMicroAverageMetrics.summationRecall), Utility.getBolded(Utility.round(summationMicroAverageMetrics.summationF1Score)), Utility.getBolded(Utility.round(summationMicroAverageMetrics.summationAccuracy)), Utility.round(summationMicroAverageMetrics.summationTruePositives), Utility.round(summationMicroAverageMetrics.summationFalsePositives), Utility.round(summationMicroAverageMetrics.summationTrueNegatives), Utility.round(summationMicroAverageMetrics.summationFalseNegatives), Utility.round(summationMicroAverageMetrics.summationSupport), "N/A", // ---- summationMicroAverageMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineSummationMicroAverage); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameSummationMicroAverage, UtilityConfusionMatrix.DescriptionSummationMicroAverage, ]); // ----------------------------------------------------------------------- const macroAverageMetrics: IConfusionMatrixMeanMetrics = confusionMatrix.getMacroAverageMetrics(binaryConfusionMatrices); const confusionMatrixOutputLineMacroAverage: any[] = [ UtilityConfusionMatrix.ColumnNameMacroAverage, Utility.round(macroAverageMetrics.averagePrecision), Utility.round(macroAverageMetrics.averageRecall), Utility.getBolded(Utility.round(macroAverageMetrics.averageF1Score)), Utility.getBolded(Utility.round(macroAverageMetrics.averageAccuracy)), "N/A", // ---- Utility.round(macroAverageMetrics.averageTruePositives), "N/A", // ---- Utility.round(macroAverageMetrics.averageFalsePositives), "N/A", // ---- Utility.round(macroAverageMetrics.averageTrueNegatives), "N/A", // ---- Utility.round(macroAverageMetrics.averageFalseNegatives), "N/A", // ---- Utility.round(macroAverageMetrics.averageSupport), "N/A", // ---- macroAverageMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineMacroAverage); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameMacroAverage, UtilityConfusionMatrix.DescriptionMacroAverage, ]); // ----------------------------------------------------------------------- const summationMacroAverageMetrics: IConfusionMatrixMeanMetrics = confusionMatrix.getSummationMacroAverageMetrics(binaryConfusionMatrices); const confusionMatrixOutputLineSummationMacroAverage: any[] = [ UtilityConfusionMatrix.ColumnNameSummationMacroAverage, Utility.round(summationMacroAverageMetrics.averagePrecision), Utility.round(summationMacroAverageMetrics.averageRecall), Utility.round(summationMacroAverageMetrics.averageF1Score), Utility.round(summationMacroAverageMetrics.averageAccuracy), Utility.round(summationMacroAverageMetrics.averageTruePositives), Utility.round(summationMacroAverageMetrics.averageFalsePositives), Utility.round(summationMacroAverageMetrics.averageTrueNegatives), Utility.round(summationMacroAverageMetrics.averageFalseNegatives), Utility.round(summationMacroAverageMetrics.averageSupport), "N/A", // ---- summationMacroAverageMetrics.total, ]; confusionMatrixAverageOutputLines.push(confusionMatrixOutputLineSummationMacroAverage); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameSummationMacroAverage, UtilityConfusionMatrix.DescriptionSummationMacroAverage, ]); // ----------------------------------------------------------------------- const positiveSupportLabelMacroAverageMetrics: IConfusionMatrixMeanMetrics = confusionMatrix.getPositiveSupportLabelMacroAverageMetrics(binaryConfusionMatrices); const confusionMatrixOutputLinePositiveSupportLabelMacroAverage: any[] = [ UtilityConfusionMatrix.ColumnNamePositiveSupportMacroAverage, Utility.round(positiveSupportLabelMacroAverageMetrics.averagePrecision), Utility.round(positiveSupportLabelMacroAverageMetrics.averageRecall), Utility.round(positiveSupportLabelMacroAverageMetrics.averageF1Score), Utility.round(positiveSupportLabelMacroAverageMetrics.averageAccuracy), "N/A", // ---- Utility.round(positiveSupportLabelMacroAverageMetrics.averageTruePositives), "N/A", // ---- Utility.round(positiveSupportLabelMacroAverageMetrics.averageFalsePositives), "N/A", // ---- Utility.round(positiveSupportLabelMacroAverageMetrics.averageTrueNegatives), "N/A", // ---- Utility.round(positiveSupportLabelMacroAverageMetrics.averageFalseNegatives), "N/A", // ---- Utility.round(positiveSupportLabelMacroAverageMetrics.averageSupport), "N/A", // ---- positiveSupportLabelMacroAverageMetrics.total, ]; confusionMatrixAverageOutputLines.push( confusionMatrixOutputLinePositiveSupportLabelMacroAverage); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNamePositiveSupportMacroAverage, UtilityConfusionMatrix.DescriptionPositiveSupportMacroAverage, ]); // ----------------------------------------------------------------------- const positiveSupportLabelSummationMacroAverageMetrics: IConfusionMatrixMeanMetrics = confusionMatrix.getPositiveSupportLabelSummationMacroAverageMetrics(binaryConfusionMatrices); const confusionMatrixOutputLinePositiveSupportLabelSummationMacroAverage: any[] = [ UtilityConfusionMatrix.ColumnNamePositiveSupportSummationMacroAverage, Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averagePrecision), Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averageRecall), Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averageF1Score), Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averageAccuracy), Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averageTruePositives), Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averageFalsePositives), Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averageTrueNegatives), Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averageFalseNegatives), Utility.round(positiveSupportLabelSummationMacroAverageMetrics.averageSupport), "N/A", // ---- positiveSupportLabelSummationMacroAverageMetrics.total, ]; confusionMatrixAverageOutputLines.push( confusionMatrixOutputLinePositiveSupportLabelSummationMacroAverage); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNamePositiveSupportSummationMacroAverage, UtilityConfusionMatrix.DescriptionPositiveSupportSummationMacroAverage, ]); // ----------------------------------------------------------------------- const weightedMacroAverageMetrics: IConfusionMatrixMeanDerivedMetrics = confusionMatrix.getWeightedMacroAverageMetrics(binaryConfusionMatrices); const confusionMatrixOutputLineWeightedMacroAverage: any[] = [ UtilityConfusionMatrix.ColumnNameWeightedMacroAverage, Utility.round(weightedMacroAverageMetrics.averagePrecision), Utility.round(weightedMacroAverageMetrics.averageRecall), Utility.round(weightedMacroAverageMetrics.averageF1Score), Utility.round(weightedMacroAverageMetrics.averageAccuracy), "N/A", "N/A", "N/A", "N/A", "N/A", "N/A", // ---- weightedMacroAverageMetrics.total, ]; confusionMatrixAverageOutputLines.push( confusionMatrixOutputLineWeightedMacroAverage); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameWeightedMacroAverage, UtilityConfusionMatrix.DescriptionWeightedMacroAverage, ]); // ----------------------------------------------------------------------- const summationWeightedMacroAverageMetrics: IConfusionMatrixMeanMetrics = confusionMatrix.getSummationWeightedMacroAverageMetrics(binaryConfusionMatrices); const confusionMatrixOutputLineSummationWeightedMacroAverage: any[] = [ UtilityConfusionMatrix.ColumnNameWeightedSummationMacroAverage, Utility.round(summationWeightedMacroAverageMetrics.averagePrecision), Utility.round(summationWeightedMacroAverageMetrics.averageRecall), Utility.round(summationWeightedMacroAverageMetrics.averageF1Score), Utility.round(summationWeightedMacroAverageMetrics.averageAccuracy), Utility.round(summationWeightedMacroAverageMetrics.averageTruePositives), Utility.round(summationWeightedMacroAverageMetrics.averageFalsePositives), Utility.round(summationWeightedMacroAverageMetrics.averageTrueNegatives), Utility.round(summationWeightedMacroAverageMetrics.averageFalseNegatives), Utility.round(summationWeightedMacroAverageMetrics.averageSupport), "N/A", // ---- summationWeightedMacroAverageMetrics.total, ]; confusionMatrixAverageOutputLines.push( confusionMatrixOutputLineSummationWeightedMacroAverage); confusionMatrixAverageDescriptionOutputLines.push([ columnNamePreffix + UtilityConfusionMatrix.ColumnNameWeightedSummationMacroAverage, UtilityConfusionMatrix.DescriptionWeightedSummationMacroAverage, ]); // ----------------------------------------------------------------------- Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), confusionMatrix.getMicroAverageMetrics()= ${Utility.jsonStringify(confusionMatrix.getMicroAverageMetrics(binaryConfusionMatrices))}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), confusionMatrix.getMacroAverageMetrics()= ${Utility.jsonStringify(confusionMatrix.getMacroAverageMetrics(binaryConfusionMatrices))}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), confusionMatrix.getWeightedMacroAverageMetrics()=${Utility.jsonStringify(confusionMatrix.getWeightedMacroAverageMetrics(binaryConfusionMatrices))}`); // ----------------------------------------------------------------------- const confusionMatrixAverageMetricsHtml: string = Utility.convertDataArraysToIndexedHtmlTable( "Average confusion matrix metrics", confusionMatrixAverageOutputLines, ["Type", "Precision", "Recall", "F1", "Accuracy", "#TruePositives", "#FalsePositives", "#TrueNegatives", "#FalseNegatives", "Support", "Total"]); const confusionMatrixAverageDescriptionMetricsHtml: string = Utility.convertDataArraysToIndexedHtmlTable( "Average confusion matrix metric descriptions", confusionMatrixAverageDescriptionOutputLines, ["Type", "Description"]); // ----------------------------------------------------------------------- return { binaryConfusionMatrices, confusionMatrixOutputLines, confusionMatrixMetricsHtml, confusionMatrixAverageOutputLines, confusionMatrixAverageMetricsHtml, confusionMatrixAverageDescriptionOutputLines, confusionMatrixAverageDescriptionMetricsHtml, }; // ----------------------------------------------------------------------- } /** * Aggregate an input MultiLabelObjectConfusionMatrixExact object into * a collection of evaluation output objects with the help of some * auxiliary objects. * * @param multiLabelObjectConfusionMatrixExact * @param labelArrayAndMap * @param confusionMatrixAverageOutputLines * @param confusionMatrixAverageDescriptionOutputLines */ public static aggregateMultiLabelObjectConfusionMatrixExactIntoEvaluationOutputs( multiLabelObjectConfusionMatrixExact: MultiLabelObjectConfusionMatrixExact, labelArrayAndMap: ILabelArrayAndMap, confusionMatrixAverageOutputLines: string[][], confusionMatrixAverageDescriptionOutputLines: string[][]): IMultiLabelObjectConfusionMatrixExactEvaluationStructure { // ----------------------------------------------------------------------- const confusionMatrix: ConfusionMatrix = new ConfusionMatrix(labelArrayAndMap.stringArray, labelArrayAndMap.stringMap); // ----------------------------------------------------------------------- if (Utility.isEmptyArray(confusionMatrixAverageOutputLines)) { confusionMatrixAverageOutputLines = []; } if (Utility.isEmptyArray(confusionMatrixAverageDescriptionOutputLines)) { confusionMatrixAverageDescriptionOutputLines = []; } // ----------------------------------------------------------------------- const exactMacroAggregateMetrics: IConfusionMatrixMeanMetrics = multiLabelObjectConfusionMatrixExact.getMacroAverageMetrics([]); if (exactMacroAggregateMetrics.total > 0) { const confusionMatrixOutputLineExactMacroAggregate: any[] = [ UtilityConfusionMatrix.ColumnNameMultiLabelExactAggregate, Utility.round(exactMacroAggregateMetrics.averagePrecision), Utility.round(exactMacroAggregateMetrics.averageRecall), Utility.getBolded(Utility.round(exactMacroAggregateMetrics.averageF1Score)), Utility.getBolded(Utility.round(exactMacroAggregateMetrics.averageAccuracy)), Utility.round(exactMacroAggregateMetrics.averageTruePositives), Utility.round(exactMacroAggregateMetrics.averageFalsePositives), Utility.round(exactMacroAggregateMetrics.averageTrueNegatives), Utility.round(exactMacroAggregateMetrics.averageFalseNegatives), Utility.round(exactMacroAggregateMetrics.averageSupport), exactMacroAggregateMetrics.total, ]; confusionMatrixAverageOutputLines.push( confusionMatrixOutputLineExactMacroAggregate); confusionMatrixAverageDescriptionOutputLines.push([ UtilityConfusionMatrix.ColumnNameMultiLabelExactAggregate, UtilityConfusionMatrix.DescriptionMultiLabelExactAggregate, ]); } // ----------------------------------------------------------------------- Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixExact.getMicroAverageMetrics()= ${Utility.jsonStringify(multiLabelObjectConfusionMatrixExact.getMicroAverageMetrics([]))}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixExact.getMacroAverageMetrics()= ${Utility.jsonStringify(multiLabelObjectConfusionMatrixExact.getMacroAverageMetrics([]))}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixExact.getWeightedMacroAverageMetrics()= ${Utility.jsonStringify(multiLabelObjectConfusionMatrixExact.getWeightedMacroAverageMetrics([]))}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getTotal()= ${multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getTotal()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getTruePositives() =${multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getTruePositives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getFalsePositives()=${multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getFalsePositives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getTrueNegatives() =${multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getTrueNegatives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getFalseNegatives()=${multiLabelObjectConfusionMatrixExact.getBinaryConfusionMatrix().getFalseNegatives()}`); // ----------------------------------------------------------------------- const confusionMatrixAverageMetricsHtml: string = Utility.convertDataArraysToIndexedHtmlTable( "Average confusion matrix metrics", confusionMatrixAverageOutputLines, ["Type", "Precision", "Recall", "F1", "Accuracy", "#TruePositives", "#FalsePositives", "#TrueNegatives", "#FalseNegatives", "Support", "Total"]); const confusionMatrixAverageDescriptionMetricsHtml: string = Utility.convertDataArraysToIndexedHtmlTable( "Average confusion matrix metric descriptions", confusionMatrixAverageDescriptionOutputLines, ["Type", "Description"]); // ----------------------------------------------------------------------- return { multiLabelObjectConfusionMatrixExact, confusionMatrixAverageOutputLines, confusionMatrixAverageMetricsHtml, confusionMatrixAverageDescriptionOutputLines, confusionMatrixAverageDescriptionMetricsHtml, }; // ----------------------------------------------------------------------- } /** * Aggregate an input MultiLabelObjectConfusionMatrixSubset object into * a collection of evaluation output objects with the help of some * auxiliary objects. * * @param multiLabelObjectConfusionMatrixSubset * @param labelArrayAndMap * @param confusionMatrixAverageOutputLines * @param confusionMatrixAverageDescriptionOutputLines */ public static aggregateMultiLabelObjectConfusionMatrixSubsetIntoEvaluationOutputs( multiLabelObjectConfusionMatrixSubset: MultiLabelObjectConfusionMatrixSubset, labelArrayAndMap: ILabelArrayAndMap, confusionMatrixAverageOutputLines: string[][], confusionMatrixAverageDescriptionOutputLines: string[][]): IMultiLabelObjectConfusionMatrixSubsetEvaluationStructure { // ----------------------------------------------------------------------- const confusionMatrix: ConfusionMatrix = new ConfusionMatrix(labelArrayAndMap.stringArray, labelArrayAndMap.stringMap); // ----------------------------------------------------------------------- if (Utility.isEmptyArray(confusionMatrixAverageOutputLines)) { confusionMatrixAverageOutputLines = []; } if (Utility.isEmptyArray(confusionMatrixAverageDescriptionOutputLines)) { confusionMatrixAverageDescriptionOutputLines = []; } // ----------------------------------------------------------------------- const subsetMacroAggregateMetrics: IConfusionMatrixMeanMetrics = multiLabelObjectConfusionMatrixSubset.getMacroAverageMetrics([]); if (subsetMacroAggregateMetrics.total > 0) { const confusionMatrixOutputLineSubsetMacroAggregate: any[] = [ UtilityConfusionMatrix.ColumnNameMultiLabelSubsetAggregate, Utility.round(subsetMacroAggregateMetrics.averagePrecision), Utility.round(subsetMacroAggregateMetrics.averageRecall), Utility.getBolded(Utility.round(subsetMacroAggregateMetrics.averageF1Score)), Utility.getBolded(Utility.round(subsetMacroAggregateMetrics.averageAccuracy)), Utility.round(subsetMacroAggregateMetrics.averageTruePositives), Utility.round(subsetMacroAggregateMetrics.averageFalsePositives), Utility.round(subsetMacroAggregateMetrics.averageTrueNegatives), Utility.round(subsetMacroAggregateMetrics.averageFalseNegatives), Utility.round(subsetMacroAggregateMetrics.averageSupport), subsetMacroAggregateMetrics.total, ]; confusionMatrixAverageOutputLines.push( confusionMatrixOutputLineSubsetMacroAggregate); confusionMatrixAverageDescriptionOutputLines.push([ UtilityConfusionMatrix.ColumnNameMultiLabelSubsetAggregate, UtilityConfusionMatrix.DescriptionMultiLabelSubsetAggregate, ]); } // ----------------------------------------------------------------------- Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixSubset.getMicroAverageMetrics()= ${Utility.jsonStringify(multiLabelObjectConfusionMatrixSubset.getMicroAverageMetrics([]))}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixSubset.getMacroAverageMetrics()= ${Utility.jsonStringify(multiLabelObjectConfusionMatrixSubset.getMacroAverageMetrics([]))}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixSubset.getWeightedMacroAverageMetrics()= ${Utility.jsonStringify(multiLabelObjectConfusionMatrixSubset.getWeightedMacroAverageMetrics([]))}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getTotal()= ${multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getTotal()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getTruePositives() =${multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getTruePositives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getFalsePositives()=${multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getFalsePositives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getTrueNegatives() =${multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getTrueNegatives()}`); Utility.debuggingLog(`aggregateBinaryConfusionMatrixArrayIntoEvaluationOutputs(), multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getFalseNegatives()=${multiLabelObjectConfusionMatrixSubset.getBinaryConfusionMatrix().getFalseNegatives()}`); // ----------------------------------------------------------------------- const confusionMatrixAverageMetricsHtml: string = Utility.convertDataArraysToIndexedHtmlTable( "Average confusion matrix metrics", confusionMatrixAverageOutputLines, ["Type", "Precision", "Recall", "F1", "Accuracy", "#TruePositives", "#FalsePositives", "#TrueNegatives", "#FalseNegatives", "Support", "Total"]); const confusionMatrixAverageDescriptionMetricsHtml: string = Utility.convertDataArraysToIndexedHtmlTable( "Average confusion matrix metric descriptions", confusionMatrixAverageDescriptionOutputLines, ["Type", "Description"]); // ----------------------------------------------------------------------- return { multiLabelObjectConfusionMatrixSubset, confusionMatrixAverageOutputLines, confusionMatrixAverageMetricsHtml, confusionMatrixAverageDescriptionOutputLines, confusionMatrixAverageDescriptionMetricsHtml, }; // ----------------------------------------------------------------------- } }
the_stack
import { BigNumber } from '@ethersproject/bignumber' import { Pool, RToken, RouteLeg, MultiRoute, RouteStatus } from '../types/MultiRouterTypes' import { ASSERT, calcInByOut, calcOutByIn, closeValues, calcPrice } from '../utils/MultiRouterMath' export class Edge { readonly GasConsumption = 40_000 readonly MINIMUM_LIQUIDITY = 1000 pool: Pool vert0: Vertice vert1: Vertice canBeUsed: boolean direction: boolean amountInPrevious: number // How many liquidity were passed from vert0 to vert1 amountOutPrevious: number // How many liquidity were passed from vert0 to vert1 bestEdgeIncome: number // debug data constructor(p: Pool, v0: Vertice, v1: Vertice) { this.pool = p this.vert0 = v0 this.vert1 = v1 this.amountInPrevious = 0 this.amountOutPrevious = 0 this.canBeUsed = true this.direction = true this.bestEdgeIncome = 0 } reserve(v: Vertice): BigNumber { return v === this.vert0 ? this.pool.reserve0 : this.pool.reserve1 } calcOutput(v: Vertice, amountIn: number) { const pool = this.pool let out, gas = this.amountInPrevious ? 0 : this.GasConsumption if (v === this.vert1) { if (this.direction) { if (amountIn < this.amountOutPrevious) { out = this.amountInPrevious - calcInByOut(pool, this.amountOutPrevious - amountIn, true) } else { out = calcOutByIn(pool, amountIn - this.amountOutPrevious, false) + this.amountInPrevious } if (amountIn === this.amountOutPrevious) { // TODO: accuracy? gas = -this.GasConsumption } } else { out = calcOutByIn(pool, this.amountOutPrevious + amountIn, false) - this.amountInPrevious } } else { if (this.direction) { out = calcOutByIn(pool, this.amountInPrevious + amountIn, true) - this.amountOutPrevious } else { if (amountIn === this.amountInPrevious) { // TODO: accuracy? gas = -this.GasConsumption } if (amountIn < this.amountInPrevious) { out = this.amountOutPrevious - calcInByOut(pool, this.amountInPrevious - amountIn, false) } else { out = calcOutByIn(pool, amountIn - this.amountInPrevious, true) + this.amountOutPrevious } } } // this.testApply(v, amountIn, out); return [out, gas] } checkMinimalLiquidityExceededAfterSwap(from: Vertice, amountOut: number): boolean { if (from === this.vert0) { const r1 = parseInt(this.pool.reserve1.toString()) if (this.direction) { return r1 - amountOut - this.amountOutPrevious < this.MINIMUM_LIQUIDITY } else { return r1 - amountOut + this.amountOutPrevious < this.MINIMUM_LIQUIDITY } } else { const r0 = parseInt(this.pool.reserve0.toString()) if (this.direction) { return r0 - amountOut + this.amountInPrevious < this.MINIMUM_LIQUIDITY } else { return r0 - amountOut - this.amountInPrevious < this.MINIMUM_LIQUIDITY } } } // doesn't used in production - just for testing testApply(from: Vertice, amountIn: number, amountOut: number) { console.assert(this.amountInPrevious * this.amountOutPrevious >= 0) const inPrev = this.direction ? this.amountInPrevious : -this.amountInPrevious const outPrev = this.direction ? this.amountOutPrevious : -this.amountOutPrevious const to = from.getNeibour(this) let directionNew, amountInNew = 0, amountOutNew = 0 if (to) { const inInc = from === this.vert0 ? amountIn : -amountOut const outInc = from === this.vert0 ? amountOut : -amountIn const inNew = inPrev + inInc const outNew = outPrev + outInc if (inNew * outNew < 0) console.log('333') console.assert(inNew * outNew >= 0) if (inNew >= 0) { directionNew = true amountInNew = inNew amountOutNew = outNew } else { directionNew = false amountInNew = -inNew amountOutNew = -outNew } } else console.error('Error 221') if (directionNew) { const calc = calcOutByIn(this.pool, amountInNew, directionNew) const res = closeValues(amountOutNew, calc, 1e-6) if (!res) console.log('Err 225-1 !!', amountOutNew, calc, Math.abs(calc / amountOutNew - 1)) return res } else { const calc = calcOutByIn(this.pool, amountOutNew, directionNew) const res = closeValues(amountInNew, calc, 1e-6) if (!res) console.log('Err 225-2!!', amountInNew, calc, Math.abs(calc / amountInNew - 1)) return res } } applySwap(from: Vertice) { console.assert(this.amountInPrevious * this.amountOutPrevious >= 0) const inPrev = this.direction ? this.amountInPrevious : -this.amountInPrevious const outPrev = this.direction ? this.amountOutPrevious : -this.amountOutPrevious const to = from.getNeibour(this) if (to) { const inInc = from === this.vert0 ? from.bestIncome : -to.bestIncome const outInc = from === this.vert0 ? to.bestIncome : -from.bestIncome const inNew = inPrev + inInc const outNew = outPrev + outInc console.assert(inNew * outNew >= 0) if (inNew >= 0) { this.direction = true this.amountInPrevious = inNew this.amountOutPrevious = outNew } else { this.direction = false this.amountInPrevious = -inNew this.amountOutPrevious = -outNew } } else console.error('Error 221') ASSERT(() => { if (this.direction) return closeValues(this.amountOutPrevious, calcOutByIn(this.pool, this.amountInPrevious, this.direction), 1e-6) else { return closeValues(this.amountInPrevious, calcOutByIn(this.pool, this.amountOutPrevious, this.direction), 1e-6) } }, `Error 225`) } } export class Vertice { token: RToken edges: Edge[] price: number gasPrice: number bestIncome: number // temp data used for findBestPath algorithm gasSpent: number // temp data used for findBestPath algorithm bestTotal: number // temp data used for findBestPath algorithm bestSource?: Edge // temp data used for findBestPath algorithm checkLine: number // debug data constructor(t: RToken) { this.token = t this.edges = [] this.price = 0 this.gasPrice = 0 this.bestIncome = 0 this.gasSpent = 0 this.bestTotal = 0 this.bestSource = undefined this.checkLine = -1 } getNeibour(e?: Edge) { if (!e) return return e.vert0 === this ? e.vert1 : e.vert0 } } export class Graph { vertices: Vertice[] edges: Edge[] tokens: Map<RToken, Vertice> constructor(pools: Pool[], baseToken: RToken, gasPrice: number) { this.vertices = [] this.edges = [] this.tokens = new Map() pools.forEach(p => { const v0 = this.getOrCreateVertice(p.token0) const v1 = this.getOrCreateVertice(p.token1) const edge = new Edge(p, v0, v1) v0.edges.push(edge) v1.edges.push(edge) this.edges.push(edge) }) const baseVert = this.tokens.get(baseToken) if (baseVert) { this.setPrices(baseVert, 1, gasPrice) } } setPrices(from: Vertice, price: number, gasPrice: number) { if (from.price !== 0) return from.price = price from.gasPrice = gasPrice const edges = from.edges .map((e): [Edge, number] => [e, parseInt(e.reserve(from).toString())]) .sort(([_1, r1], [_2, r2]) => r2 - r1) edges.forEach(([e, _]) => { const v = e.vert0 === from ? e.vert1 : e.vert0 if (v.price !== 0) return let p = calcPrice(e.pool, 0, false) if (from === e.vert0) p = 1 / p this.setPrices(v, price * p, gasPrice / p) }) } getOrCreateVertice(token: RToken) { let vert = this.tokens.get(token) if (vert) return vert vert = new Vertice(token) this.vertices.push(vert) this.tokens.set(token, vert) return vert } // Function just for testing - but very usefull !!! /*exportPath(from: RToken, to: RToken) { //}, _route: MultiRoute) { // const allPools = new Map<string, Pool>(); // this.edges.forEach(p => allPools.set(p.address, p)); // const usedPools = new Map<string, boolean>(); // route.legs.forEach(l => usedPools.set(l.address, l.token === allPools.get(l.address)?.token0)) const fromVert = this.tokens.get(from) as Vertice const toVert = this.tokens.get(to) as Vertice const initValue = (fromVert.bestIncome * fromVert.price) / toVert.price const route = new Set<Edge>() for (let v = toVert; v !== fromVert; v = v.getNeibour(v.bestSource) as Vertice) { if (v.bestSource) route.add(v.bestSource) } function edgeStyle(e: Edge) { const finish = e.vert1.bestSource === e const start = e.vert0.bestSource === e let label if (e.bestEdgeIncome === -1) label = 'label: "low_liq"' if (e.bestEdgeIncome !== 0) label = `label: "${print((e.bestEdgeIncome / initValue - 1) * 100, 3)}%"` const edgeValue = route.has(e) ? 'value: 2' : undefined let arrow if (finish && start) arrow = 'arrows: "from,to"' if (finish) arrow = 'arrows: "to"' if (start) arrow = 'arrows: "from"' return ['', label, edgeValue, arrow].filter(a => a !== undefined).join(', ') } function print(n: number, digits: number) { let out if (n === 0) out = '0' else { const n0 = n > 0 ? n : -n const shift = digits - Math.ceil(Math.log(n0) / Math.LN10) if (shift <= 0) out = `${Math.round(n0)}` else { const mult = Math.pow(10, shift) out = `${Math.round(n0 * mult) / mult}` } if (n < 0) out = -out } return out } function nodeLabel(v: Vertice) { const value = (v.bestIncome * v.price) / toVert.price const income = `${print(value, 3)}` const total = `${print(v.bestTotal, 3)}` // const income = `${print((value/initValue-1)*100, 3)}%` // const total = `${print((v.bestTotal/initValue-1)*100, 3)}%` const checkLine = v.checkLine === -1 ? undefined : `${v.checkLine}` return [checkLine, income, total].filter(a => a !== undefined).join(':') } const nodes = `var nodes = new vis.DataSet([ ${this.vertices.map(t => `{ id: ${t.token.name}, label: "${nodeLabel(t)}"}`).join(',\n\t\t')} ]);\n` const edges = `var edges = new vis.DataSet([ ${this.edges.map(p => `{ from: ${p.vert0.token.name}, to: ${p.vert1.token.name}${edgeStyle(p)}}`).join(',\n\t\t')} ]);\n` const data = `var data = { nodes: nodes, edges: edges, };\n` const fs = require('fs') fs.writeFileSync('D:/Info/Notes/GraphVisualization/data.js', nodes + edges + data) }*/ findBestPath( from: RToken, to: RToken, amountIn: number ): | { path: Edge[] output: number gasSpent: number totalOutput: number } | undefined { const start = this.tokens.get(from) const finish = this.tokens.get(to) if (!start || !finish) return this.edges.forEach(e => (e.bestEdgeIncome = 0)) this.vertices.forEach(v => { v.bestIncome = 0 v.gasSpent = 0 v.bestTotal = 0 v.bestSource = undefined v.checkLine = -1 }) start.bestIncome = amountIn start.bestTotal = amountIn const processedVert = new Set<Vertice>() const nextVertList = [start] // TODO: Use sorted Set! let checkLine = 0 for (;;) { let closestVert: Vertice | undefined let closestTotal = -1 let closestPosition = 0 nextVertList.forEach((v, i) => { if (v.bestTotal > closestTotal) { closestTotal = v.bestTotal closestVert = v closestPosition = i } }) if (!closestVert) return closestVert.checkLine = checkLine++ if (closestVert === finish) { const bestPath = [] for (let v: Vertice | undefined = finish; v?.bestSource; v = v.getNeibour(v.bestSource)) { bestPath.unshift(v.bestSource) } return { path: bestPath, output: finish.bestIncome, gasSpent: finish.gasSpent, totalOutput: finish.bestTotal } } nextVertList.splice(closestPosition, 1) closestVert.edges.forEach(e => { const v2 = closestVert === e.vert0 ? e.vert1 : e.vert0 if (processedVert.has(v2)) return let newIncome, gas try { ;[newIncome, gas] = e.calcOutput(closestVert as Vertice, (closestVert as Vertice).bestIncome) } catch (e) { // Any arithmetic error or out-of-liquidity return } if (e.checkMinimalLiquidityExceededAfterSwap(closestVert as Vertice, newIncome)) { e.bestEdgeIncome = -1 return } const newGasSpent = (closestVert as Vertice).gasSpent + gas const price = v2.price / finish.price const newTotal = newIncome * price - newGasSpent * finish.gasPrice console.assert(e.bestEdgeIncome === 0, 'Error 373') e.bestEdgeIncome = newIncome * price if (!v2.bestSource) nextVertList.push(v2) if (!v2.bestSource || newTotal > v2.bestTotal) { v2.bestIncome = newIncome v2.gasSpent = newGasSpent v2.bestTotal = newTotal v2.bestSource = e } }) processedVert.add(closestVert) } } addPath(from: Vertice | undefined, to: Vertice | undefined, path: Edge[]) { let _from = from path.forEach(e => { if (_from) { e.applySwap(_from) _from = _from.getNeibour(e) } else { console.error('Unexpected 315') } }) ASSERT(() => { const res = this.vertices.every(v => { let total = 0 let totalModule = 0 v.edges.forEach(e => { if (e.vert0 === v) { if (e.direction) { total -= e.amountInPrevious } else { total += e.amountInPrevious } totalModule += e.amountInPrevious } else { if (e.direction) { total += e.amountOutPrevious } else { total -= e.amountOutPrevious } totalModule += e.amountOutPrevious } }) if (v === from) return total <= 0 if (v === to) return total >= 0 if (totalModule === 0) return total === 0 return Math.abs(total / totalModule) < 1e10 }) return res }, 'Error 290') } findBestRoute(from: RToken, to: RToken, amountIn: number, mode: number | number[]): MultiRoute { let routeValues = [] if (Array.isArray(mode)) { const sum = mode.reduce((a, b) => a + b, 0) routeValues = mode.map(e => e / sum) } else { for (let i = 0; i < mode; ++i) routeValues.push(1 / mode) } this.edges.forEach(e => { e.amountInPrevious = 0 e.amountOutPrevious = 0 e.direction = true }) let output = 0 let gasSpentInit = 0 //let totalOutput = 0 let totalrouted = 0 let step for (step = 0; step < routeValues.length; ++step) { const p = this.findBestPath(from, to, amountIn * routeValues[step]) if (!p) { break } else { output += p.output gasSpentInit += p.gasSpent //totalOutput += p.totalOutput this.addPath(this.tokens.get(from), this.tokens.get(to), p.path) totalrouted += routeValues[step] } } if (step == 0) return { status: RouteStatus.NoWay, amountIn: 0, amountOut: 0, legs: [], gasSpent: 0, totalAmountOut: 0 } let status if (step < routeValues.length) status = RouteStatus.Partial else status = RouteStatus.Success const fromVert = this.tokens.get(from) as Vertice const toVert = this.tokens.get(to) as Vertice const [legs, gasSpent, topologyWasChanged] = this.getRouteLegs(fromVert, toVert) console.assert(gasSpent <= gasSpentInit, 'Internal Error 491') if (topologyWasChanged) { output = this.calcLegsAmountOut(legs, amountIn, to) } return { status, amountIn: amountIn * totalrouted, amountOut: output, legs, gasSpent, totalAmountOut: output - gasSpent * toVert.gasPrice } } getRouteLegs(from: Vertice, to: Vertice): [RouteLeg[], number, boolean] { const [nodes, topologyWasChanged] = this.cleanTopology(from, to) const legs: RouteLeg[] = [] let gasSpent = 0 nodes.forEach(n => { const outEdges = this.getOutputEdges(n).map(e => { const from = this.edgeFrom(e) return from ? [e, from[0], from[1]] : [e] }) let outAmount = outEdges.reduce((a, b) => a + (b[2] as number), 0) if (outAmount <= 0) return const total = outAmount outEdges.forEach((e, i) => { const p = e[2] as number const quantity = i + 1 === outEdges.length ? 1 : p / outAmount legs.push({ address: (e[0] as Edge).pool.address, token: n.token, swapPortion: quantity, absolutePortion: p / total }) gasSpent += (e[0] as Edge).pool.swapGasCost outAmount -= p }) console.assert(outAmount / total < 1e-12, 'Error 281') }) return [legs, gasSpent, topologyWasChanged] } edgeFrom(e: Edge): [Vertice, number] | undefined { if (e.amountInPrevious === 0) return undefined return e.direction ? [e.vert0, e.amountInPrevious] : [e.vert1, e.amountOutPrevious] } getOutputEdges(v: Vertice): Edge[] { return v.edges.filter(e => { if (!e.canBeUsed) return false if (e.amountInPrevious === 0) return false if (e.direction !== (e.vert0 === v)) return false return true }) } getInputEdges(v: Vertice): Edge[] { return v.edges.filter(e => { if (!e.canBeUsed) return false if (e.amountInPrevious === 0) return false if (e.direction === (e.vert0 === v)) return false return true }) } calcLegsAmountOut(legs: RouteLeg[], amountIn: number, to: RToken) { const amounts = new Map<RToken, number>() amounts.set(legs[0].token, amountIn) legs.forEach(l => { const vert = this.tokens.get(l.token) console.assert(vert !== undefined, 'Internal Error 570') const edge = (vert as Vertice).edges.find(e => e.pool.address === l.address) console.assert(edge !== undefined, 'Internel Error 569') const pool = (edge as Edge).pool const direction = vert === (edge as Edge).vert0 const inputTotal = amounts.get(l.token) console.assert(inputTotal !== undefined, 'Internal Error 564') const input = (inputTotal as number) * l.swapPortion amounts.set(l.token, (inputTotal as number) - input) const output = calcOutByIn(pool, input, direction) const vertNext = (vert as Vertice).getNeibour(edge) as Vertice const prevAmount = amounts.get(vertNext.token) amounts.set(vertNext.token, (prevAmount || 0) + output) }) return amounts.get(to) || 0 } // removes all cycles if there are any, then removes all dead end could appear after cycle removing // Returns clean result topologically sorted cleanTopology(from: Vertice, to: Vertice): [Vertice[], boolean] { let topologyWasChanged = false let result = this.topologySort(from, to) if (result[0] !== 2) { topologyWasChanged = true console.assert(result[0] === 0, 'Internal Error 554') while (result[0] === 0) { this.removeWeakestEdge(result[1]) result = this.topologySort(from, to) } if (result[0] === 3) { this.removeDeadEnds(result[1]) result = this.topologySort(from, to) } console.assert(result[0] === 2, 'Internal Error 563') if (result[0] !== 2) return [[], topologyWasChanged] } return [result[1], topologyWasChanged] } removeDeadEnds(verts: Vertice[]) { verts.forEach(v => { this.getInputEdges(v).forEach(e => { e.canBeUsed = false }) }) } removeWeakestEdge(verts: Vertice[]) { let minVert: Vertice, minVertNext: Vertice let minOutput = Number.MAX_VALUE verts.forEach((v1, i) => { const v2 = i === 0 ? verts[verts.length - 1] : verts[i - 1] let out = 0 this.getOutputEdges(v1).forEach(e => { if (v1.getNeibour(e) !== v2) return out += e.direction ? e.amountOutPrevious : e.amountInPrevious }) if (out < minOutput) { minVert = v1 minVertNext = v2 minOutput = out } }) // @ts-ignore this.getOutputEdges(minVert).forEach(e => { if (minVert.getNeibour(e) !== minVertNext) return e.canBeUsed = false }) } // topological sort // if there is a cycle - returns [0, <List of envolved vertices in the cycle>] // if there are no cycles but deadends- returns [3, <List of all envolved deadend vertices>] // if there are no cycles or deadends- returns [2, <List of all envolved vertices topologically sorted>] topologySort(from: Vertice, to: Vertice): [number, Vertice[]] { // undefined or 0 - not processed, 1 - in process, 2 - finished, 3 - dedend const vertState = new Map<Vertice, number>() const vertsFinished: Vertice[] = [] const foundCycle: Vertice[] = [] const foundDeadEndVerts: Vertice[] = [] const that = this // 0 - cycle was found and created, return // 1 - during cycle creating // 2 - vertex is processed ok // 3 - dead end vertex function topSortRecursive(current: Vertice): number { const state = vertState.get(current) if (state === 2 || state === 3) return state if (state === 1) { console.assert(foundCycle.length == 0, 'Internal Error 566') foundCycle.push(current) return 1 } vertState.set(current, 1) let successors2Exist = false const outEdges = that.getOutputEdges(current) for (let i = 0; i < outEdges.length; ++i) { const e = outEdges[i] const res = topSortRecursive(current.getNeibour(e) as Vertice) if (res === 0) return 0 if (res === 1) { if (foundCycle[0] === current) return 0 else { foundCycle.push(current) return 1 } } if (res === 2) successors2Exist = true // Ok successors } if (successors2Exist) { console.assert(current !== to, 'Internal Error 589') vertsFinished.push(current) vertState.set(current, 2) return 2 } else { if (current !== to) { foundDeadEndVerts.push(current) vertState.set(current, 3) return 3 } vertsFinished.push(current) vertState.set(current, 2) return 2 } } const res = topSortRecursive(from) if (res === 0) return [0, foundCycle] if (foundDeadEndVerts.length) return [3, foundDeadEndVerts] ASSERT(() => { if (vertsFinished[0] !== to) return false if (vertsFinished[vertsFinished.length - 1] !== from) return false return true }, 'Internal Error 614') if (res === 2) return [2, vertsFinished.reverse()] console.assert(true, 'Internal Error 612') return [1, []] } } export function findMultiRouting( from: RToken, to: RToken, amountIn: number, pools: Pool[], baseToken: RToken, gasPrice: number, steps: number | number[] = 12 ): MultiRoute { const g = new Graph(pools, baseToken, gasPrice) const fromV = g.tokens.get(from) if (fromV?.price === 0) { g.setPrices(fromV, 1, 0) } const out = g.findBestRoute(from, to, amountIn, steps) return out }
the_stack
* @fileoverview Implements the elementary MathML3 support (experimental) * using David Carlisle's XLST transform. * * @author dpvc@mathjax.org (Davide Cervone) */ import {MathItem} from '../../../core/MathItem.js'; import {MathDocument} from '../../../core/MathDocument.js'; import {Handler} from '../../../core/Handler.js'; import {OptionList} from '../../../util/Options.js'; import {createTransform} from './mml3-node.js'; import {MathML} from '../../mathml.js'; /** * The data for a MathML prefilter. * * @template N The HTMLElement node class * @template T The Text node class * @template D The Document class */ export type FILTERDATA<N, T, D> = {math: MathItem<N, T, D>, document: MathDocument<N, T, D>, data: N}; /** * Class that handles XSLT transform for MathML3 elementary math tags. */ export class Mml3<N, T, D> { /** * The XSLT transform as a string; */ public static XSLT: string; // added below (it is huge) /** * The function to convert serialized MathML using the XSLT. * (Different for browser and node environments.) */ protected transform: (node: N, doc: MathDocument<N, T, D>) => N; /** * @param {MathDocument} document The MathDocument for the transformation * @constructor */ constructor(document: MathDocument<N, T, D>) { if (typeof XSLTProcessor === 'undefined') { // // For Node, get the trasnform from the external module // this.transform = createTransform(); } else { // // For in-browser use, use the browser's XSLTProcessor // const processor = new XSLTProcessor(); const parsed = document.adaptor.parse(Mml3.XSLT, 'text/xml') as any as Node; processor.importStylesheet(parsed); this.transform = (node: N) => { const adaptor = document.adaptor; const div = adaptor.node('div', {}, [adaptor.clone(node)]); const mml = processor.transformToDocument(div as any as Node) as any as N; return adaptor.tags(mml, 'math')[0]; }; } } /** * The mathml filter for the MathML input jax * * @param {FILTERDATA} args The data from the pre-filter chain. */ public mmlFilter(args: FILTERDATA<N, T, D>) { if (args.document.options.enableMml3) { args.data = this.transform(args.data, args.document); } } } /** * Add Mml3 support into the handler. */ export function Mml3Handler<N, T, D>(handler: Handler<N, T, D>): Handler<N, T, D> { handler.documentClass = class extends handler.documentClass { /** * @override */ public static OPTIONS: OptionList = { ...handler.documentClass.OPTIONS, enableMml3: true, }; /** * Add a prefilter to the MathML input jax, if there is one. * * @override * @constructor */ constructor(...args: any[]) { super(...args); for (const jax of this.inputJax || []) { if (jax.name === 'MathML') { if (!jax.options._mml3) { // prevent filter being added twice (e.g., when a11y tools load) const mml3 = new Mml3(this); (jax as MathML<N, T, D>).mmlFilters.add(mml3.mmlFilter.bind(mml3)); jax.options._mml3 = true; } break; } } } }; return handler; } // // The actual XSLT transform // Mml3.XSLT = ` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:m="http://www.w3.org/1998/Math/MathML" xmlns:c="http://exslt.org/common" exclude-result-prefixes="m c"> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:output indent="yes" omit-xml-declaration="yes"/> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="m:*[@dir='rtl']" priority="10"> <xsl:apply-templates mode="rtl" select="."/> </xsl:template> <xsl:template match="@*" mode="rtl"> <xsl:copy-of select="."/> <xsl:attribute name="dir">ltr</xsl:attribute> </xsl:template> <xsl:template match="*" mode="rtl"> <xsl:copy> <xsl:apply-templates select="@*" mode="rtl"/> <xsl:for-each select="node()"> <xsl:sort data-type="number" order="descending" select="position()"/> <xsl:text> </xsl:text> <xsl:apply-templates mode="rtl" select="."/> </xsl:for-each> </xsl:copy> </xsl:template> <xsl:template match="@open" mode="rtl"> <xsl:attribute name="close"><xsl:value-of select="."/></xsl:attribute> </xsl:template> <xsl:template match="@open[.='(']" mode="rtl"> <xsl:attribute name="close">)</xsl:attribute> </xsl:template> <xsl:template match="@open[.=')']" mode="rtl"> <xsl:attribute name="close">(</xsl:attribute> </xsl:template> <xsl:template match="@open[.='[']" mode="rtl"> <xsl:attribute name="close">]</xsl:attribute> </xsl:template> <xsl:template match="@open[.=']']" mode="rtl"> <xsl:attribute name="close">[</xsl:attribute> </xsl:template> <xsl:template match="@open[.='{']" mode="rtl"> <xsl:attribute name="close">}</xsl:attribute> </xsl:template> <xsl:template match="@open[.='}']" mode="rtl"> <xsl:attribute name="close">{</xsl:attribute> </xsl:template> <xsl:template match="@close" mode="rtl"> <xsl:attribute name="open"><xsl:value-of select="."/></xsl:attribute> </xsl:template> <xsl:template match="@close[.='(']" mode="rtl"> <xsl:attribute name="open">)</xsl:attribute> </xsl:template> <xsl:template match="@close[.=')']" mode="rtl"> <xsl:attribute name="open">(</xsl:attribute> </xsl:template> <xsl:template match="@close[.='[']" mode="rtl"> <xsl:attribute name="open">]</xsl:attribute> </xsl:template> <xsl:template match="@close[.=']']" mode="rtl"> <xsl:attribute name="open">[</xsl:attribute> </xsl:template> <xsl:template match="@close[.='{']" mode="rtl"> <xsl:attribute name="open">}</xsl:attribute> </xsl:template> <xsl:template match="@close[.='}']" mode="rtl"> <xsl:attribute name="open">{</xsl:attribute> </xsl:template> <xsl:template match="m:mfrac[@bevelled='true']" mode="rtl"> <m:mrow> <m:msub><m:mi></m:mi><xsl:apply-templates select="*[2]" mode="rtl"/></m:msub> <m:mo>&#x5c;</m:mo> <m:msup><m:mi></m:mi><xsl:apply-templates select="*[1]" mode="rtl"/></m:msup> </m:mrow> </xsl:template> <xsl:template match="m:mfrac" mode="rtl"> <xsl:copy> <xsl:apply-templates mode="rtl" select="@*|*"/> </xsl:copy> </xsl:template> <xsl:template match="m:mroot" mode="rtl"> <m:msup> <m:menclose notation="top right"> <xsl:apply-templates mode="rtl" select="@*|*[1]"/> </m:menclose> <xsl:apply-templates mode="rtl" select="*[2]"/> </m:msup> </xsl:template> <xsl:template match="m:msqrt" mode="rtl"> <m:menclose notation="top right"> <xsl:apply-templates mode="rtl" select="@*|*[1]"/> </m:menclose> </xsl:template> <xsl:template match="m:mtable|m:munder|m:mover|m:munderover" mode="rtl" priority="2"> <xsl:copy> <xsl:apply-templates select="@*" mode="rtl"/> <xsl:apply-templates mode="rtl"> </xsl:apply-templates> </xsl:copy> </xsl:template> <xsl:template match="m:msup" mode="rtl" priority="2"> <m:mmultiscripts> <xsl:apply-templates select="*[1]" mode="rtl"/> <m:mprescripts/> <m:none/> <xsl:apply-templates select="*[2]" mode="rtl"/> </m:mmultiscripts> </xsl:template> <xsl:template match="m:msub" mode="rtl" priority="2"> <m:mmultiscripts> <xsl:apply-templates select="*[1]" mode="rtl"/> <m:mprescripts/> <xsl:apply-templates select="*[2]" mode="rtl"/> <m:none/> </m:mmultiscripts> </xsl:template> <xsl:template match="m:msubsup" mode="rtl" priority="2"> <m:mmultiscripts> <xsl:apply-templates select="*[1]" mode="rtl"/> <m:mprescripts/> <xsl:apply-templates select="*[2]" mode="rtl"/> <xsl:apply-templates select="*[3]" mode="rtl"/> </m:mmultiscripts> </xsl:template> <xsl:template match="m:mmultiscripts" mode="rtl" priority="2"> <m:mmultiscripts> <xsl:apply-templates select="*[1]" mode="rtl"/> <xsl:for-each select="m:mprescripts/following-sibling::*[position() mod 2 = 1]"> <xsl:sort data-type="number" order="descending" select="position()"/> <xsl:apply-templates select="." mode="rtl"/> <xsl:apply-templates select="following-sibling::*[1]" mode="rtl"/> </xsl:for-each> <m:mprescripts/> <xsl:for-each select="m:mprescripts/preceding-sibling::*[position()!=last()][position() mod 2 = 0]"> <xsl:sort data-type="number" order="descending" select="position()"/> <xsl:apply-templates select="." mode="rtl"/> <xsl:apply-templates select="following-sibling::*[1]" mode="rtl"/> </xsl:for-each> </m:mmultiscripts> </xsl:template> <xsl:template match="m:mmultiscripts[not(m:mprescripts)]" mode="rtl" priority="3"> <m:mmultiscripts> <xsl:apply-templates select="*[1]" mode="rtl"/> <m:mprescripts/> <xsl:for-each select="*[position() mod 2 = 0]"> <xsl:sort data-type="number" order="descending" select="position()"/> <xsl:apply-templates select="." mode="rtl"/> <xsl:apply-templates select="following-sibling::*[1]" mode="rtl"/> </xsl:for-each> </m:mmultiscripts> </xsl:template> <xsl:template match="text()[.='(']" mode="rtl">)</xsl:template> <xsl:template match="text()[.=')']" mode="rtl">(</xsl:template> <xsl:template match="text()[.='{']" mode="rtl">}</xsl:template> <xsl:template match="text()[.='}']" mode="rtl">{</xsl:template> <xsl:template match="text()[.='&lt;']" mode="rtl">&gt;</xsl:template> <xsl:template match="text()[.='&gt;']" mode="rtl">&lt;</xsl:template> <xsl:template match="text()[.='&#x2208;']" mode="rtl">&#x220b;</xsl:template> <xsl:template match="text()[.='&#x220b;']" mode="rtl">&#x2208;</xsl:template> <xsl:template match="@notation[.='radical']" mode="rtl"> <xsl:attribute name="notation">top right</xsl:attribute> </xsl:template> <xsl:template match="m:mlongdiv|m:mstack" mode="rtl"> <m:mrow dir="ltr"> <xsl:apply-templates select="."/> </m:mrow> </xsl:template> <xsl:template match="m:mstack" priority="11"> <xsl:variable name="m"> <m:mtable columnspacing="0em" rowspacing="0em"> <xsl:copy-of select="@align"/> <xsl:variable name="t"> <xsl:apply-templates select="*" mode="mstack1"> <xsl:with-param name="p" select="0"/> </xsl:apply-templates> </xsl:variable> <xsl:variable name="maxl"> <xsl:for-each select="c:node-set($t)/*/@l"> <xsl:sort data-type="number" order="descending"/> <xsl:if test="position()=1"> <xsl:value-of select="."/> </xsl:if> </xsl:for-each> </xsl:variable> <xsl:for-each select="c:node-set($t)/*[not(@class='mscarries') or following-sibling::*[1]/@class='mscarries']"> <xsl:variable name="c" select="preceding-sibling::*[1][@class='mscarries']"/> <xsl:text>&#10;</xsl:text> <m:mtr> <xsl:copy-of select="@class[.='msline']"/> <xsl:variable name="offset" select="$maxl - @l"/> <xsl:choose> <xsl:when test="@class='msline' and @l='*'"> <xsl:variable name="msl" select="*[1]"/> <xsl:for-each select="(//node())[position()&lt;=$maxl]"> <xsl:copy-of select="$msl"/> </xsl:for-each> </xsl:when> <xsl:when test="$c"> <xsl:variable name="ldiff" select="$c/@l - @l"/> <xsl:variable name="loffset" select="$maxl - $c/@l"/> <xsl:for-each select="(//*)[position()&lt;= $offset]"> <xsl:variable name="pn" select="position()"/> <xsl:variable name="cy" select="$c/*[position()=$pn - $loffset]"/> <m:mtd> <xsl:if test="$cy/*"> <m:mover><m:mphantom><m:mn>0</m:mn></m:mphantom><m:mpadded width="0em" lspace="-0.5width"> <xsl:copy-of select="$cy/*"/></m:mpadded></m:mover> </xsl:if> </m:mtd> </xsl:for-each> <xsl:for-each select="*"> <xsl:variable name="pn" select="position()"/> <xsl:variable name="cy" select="$c/*[position()=$pn + $ldiff]"/> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:variable name="b"> <xsl:choose> <xsl:when test="not(string($cy/@crossout) or $cy/@crossout='none')"><xsl:copy-of select="*"/></xsl:when> <xsl:otherwise> <m:menclose notation="{$cy/@crossout}"><xsl:copy-of select="*"/></m:menclose> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:choose> <xsl:when test="$cy/m:none or not($cy/*)"><xsl:copy-of select="$b"/></xsl:when> <xsl:when test="not(string($cy/@location)) or $cy/@location='n'"> <m:mover> <xsl:copy-of select="$b"/><m:mpadded width="0em" lspace="-0.5width"> <xsl:copy-of select="$cy/*"/> </m:mpadded> </m:mover> </xsl:when> <xsl:when test="$cy/@location='nw'"> <m:mmultiscripts><xsl:copy-of select="$b"/><m:mprescripts/><m:none/><m:mpadded lspace="-1width" width="0em"><xsl:copy-of select="$cy/*"/></m:mpadded></m:mmultiscripts> </xsl:when> <xsl:when test="$cy/@location='s'"> <m:munder><xsl:copy-of select="$b"/><m:mpadded width="0em" lspace="-0.5width"><xsl:copy-of select="$cy/*"/></m:mpadded></m:munder> </xsl:when> <xsl:when test="$cy/@location='sw'"> <m:mmultiscripts><xsl:copy-of select="$b"/><m:mprescripts/><m:mpadded lspace="-1width" width="0em"><xsl:copy-of select="$cy/*"/></m:mpadded><m:none/></m:mmultiscripts> </xsl:when> <xsl:when test="$cy/@location='ne'"> <m:msup><xsl:copy-of select="$b"/><m:mpadded width="0em"><xsl:copy-of select="$cy/*"/></m:mpadded></m:msup> </xsl:when> <xsl:when test="$cy/@location='se'"> <m:msub><xsl:copy-of select="$b"/><m:mpadded width="0em"><xsl:copy-of select="$cy/*"/></m:mpadded></m:msub> </xsl:when> <xsl:when test="$cy/@location='w'"> <m:msup><m:mrow/><m:mpadded lspace="-1width" width="0em"><xsl:copy-of select="$cy/*"/></m:mpadded></m:msup> <xsl:copy-of select="$b"/> </xsl:when> <xsl:when test="$cy/@location='e'"> <xsl:copy-of select="$b"/> <m:msup><m:mrow/><m:mpadded width="0em"><xsl:copy-of select="$cy/*"/></m:mpadded></m:msup> </xsl:when> <xsl:otherwise> <xsl:copy-of select="$b"/> </xsl:otherwise> </xsl:choose> </xsl:copy> </xsl:for-each> </xsl:when> <xsl:otherwise> <xsl:for-each select="(//*)[position()&lt;= $offset]"><m:mtd/></xsl:for-each> <xsl:copy-of select="*"/> </xsl:otherwise> </xsl:choose> </m:mtr> </xsl:for-each> </m:mtable> </xsl:variable> <xsl:apply-templates mode="ml" select="c:node-set($m)"/> </xsl:template> <xsl:template match="m:none" mode="ml"> <m:mrow/> </xsl:template> <xsl:template match="*" mode="ml"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:apply-templates mode="ml"/> </xsl:copy> </xsl:template> <xsl:template mode="ml" match="m:mtr[following-sibling::*[1][@class='msline']]"> <m:mtr> <xsl:copy-of select="@*"/> <xsl:variable name="m" select="following-sibling::*[1]/m:mtd"/> <xsl:for-each select="m:mtd"> <xsl:variable name="p" select="position()"/> <m:mtd> <xsl:copy-of select="@*"/> <xsl:choose> <xsl:when test="$m[$p]/m:mpadded"> <m:mpadded depth="+.2em"> <m:menclose notation="bottom"> <m:mpadded depth=".1em" height=".8em" width=".8em"> <m:mspace width=".15em"/> <xsl:copy-of select="*"/> </m:mpadded> </m:menclose> </m:mpadded> </xsl:when> <xsl:otherwise> <xsl:copy-of select="*"/> </xsl:otherwise> </xsl:choose> </m:mtd> </xsl:for-each> </m:mtr> </xsl:template> <xsl:template mode="ml" match="m:mtr[not(preceding-sibling::*)][@class='msline']" priority="3"> <m:mtr> <xsl:copy-of select="@*"/> <xsl:for-each select="m:mtd"> <m:mtd> <xsl:copy-of select="@*"/> <xsl:if test="m:mpadded"> <m:menclose notation="bottom"> <m:mpadded depth=".1em" height="1em" width=".5em"> <m:mspace width=".2em"/> </m:mpadded> </m:menclose> </xsl:if> </m:mtd> </xsl:for-each> </m:mtr> </xsl:template> <xsl:template mode="ml" match="m:mtr[@class='msline']" priority="2"/> <xsl:template mode="mstack1" match="*"> <xsl:param name="p"/> <xsl:param name="maxl" select="0"/> <m:mtr l="{1 + $p}"> <xsl:if test="ancestor::mstack[1]/@stackalign='left'"> <xsl:attribute name="l"><xsl:value-of select="$p"/></xsl:attribute> </xsl:if> <m:mtd><xsl:apply-templates select="."/></m:mtd> </m:mtr> </xsl:template> <xsl:template mode="mstack1" match="m:msrow"> <xsl:param name="p"/> <xsl:param name="maxl" select="0"/> <xsl:variable name="align1" select="ancestor::m:mstack[1]/@stackalign"/> <xsl:variable name="align"> <xsl:choose> <xsl:when test="string($align1)=''">decimalpoint</xsl:when> <xsl:otherwise><xsl:value-of select="$align1"/></xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="row"> <xsl:apply-templates mode="mstack1" select="*"> <xsl:with-param name="p" select="0"/> </xsl:apply-templates> </xsl:variable> <xsl:text>&#10;</xsl:text> <xsl:variable name="l1"> <xsl:choose> <xsl:when test="$align='decimalpoint' and m:mn"> <xsl:for-each select="c:node-set($row)/m:mtr[m:mtd/m:mn][1]"> <xsl:value-of select="number(sum(@l))+count(preceding-sibling::*/@l)"/> </xsl:for-each> </xsl:when> <xsl:when test="$align='right' or $align='decimalpoint'"> <xsl:value-of select="count(c:node-set($row)/m:mtr/m:mtd)"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="0"/> </xsl:otherwise> </xsl:choose> </xsl:variable> <m:mtr class="msrow" l="{number($l1) + number(sum(@position)) +$p}"> <xsl:copy-of select="c:node-set($row)/m:mtr/*"/> </m:mtr> </xsl:template> <xsl:template mode="mstack1" match="m:mn"> <xsl:param name="p"/> <xsl:variable name="align1" select="ancestor::m:mstack[1]/@stackalign"/> <xsl:variable name="dp1" select="ancestor::*[@decimalpoint][1]/@decimalpoint"/> <xsl:variable name="align"> <xsl:choose> <xsl:when test="string($align1)=''">decimalpoint</xsl:when> <xsl:otherwise><xsl:value-of select="$align1"/></xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="dp"> <xsl:choose> <xsl:when test="string($dp1)=''">.</xsl:when> <xsl:otherwise><xsl:value-of select="$dp1"/></xsl:otherwise> </xsl:choose> </xsl:variable> <m:mtr l="$p"> <xsl:variable name="mn" select="normalize-space(.)"/> <xsl:variable name="len" select="string-length($mn)"/> <xsl:choose> <xsl:when test="$align='right' or ($align='decimalpoint' and not(contains($mn,$dp)))"> <xsl:attribute name="l"><xsl:value-of select="$p + $len"/></xsl:attribute> </xsl:when> <xsl:when test="$align='center'"> <xsl:attribute name="l"><xsl:value-of select="round(($p + $len) div 2)"/></xsl:attribute> </xsl:when> <xsl:when test="$align='decimalpoint'"> <xsl:attribute name="l"><xsl:value-of select="$p + string-length(substring-before($mn,$dp))"/></xsl:attribute> </xsl:when> </xsl:choose> <xsl:for-each select="(//node())[position() &lt;=$len]"> <xsl:variable name="pos" select="position()"/> <xsl:variable name="digit" select="substring($mn,$pos,1)"/> <m:mtd> <xsl:if test="$digit='.' or $digit=','"> <m:mspace width=".15em"/> </xsl:if> <m:mn><xsl:value-of select="$digit"/></m:mn> </m:mtd> </xsl:for-each> </m:mtr> </xsl:template> <xsl:template match="m:msgroup" mode="mstack1"> <xsl:param name="p"/> <xsl:variable name="s" select="number(sum(@shift))"/> <xsl:variable name="thisp" select="number(sum(@position))"/> <xsl:for-each select="*"> <xsl:apply-templates mode="mstack1" select="."> <xsl:with-param name="p" select="number($p)+$thisp+(position()-1)*$s"/> </xsl:apply-templates> </xsl:for-each> </xsl:template> <xsl:template match="m:msline" mode="mstack1"> <xsl:param name="p"/> <xsl:variable name="align1" select="ancestor::m:mstack[1]/@stackalign"/> <xsl:variable name="align"> <xsl:choose> <xsl:when test="string($align1)=''">decimalpoint</xsl:when> <xsl:otherwise><xsl:value-of select="$align1"/></xsl:otherwise> </xsl:choose> </xsl:variable> <m:mtr class="msline"> <xsl:attribute name="l"> <xsl:choose> <xsl:when test="not(string(@length)) or @length=0">*</xsl:when> <xsl:when test="string($align)='right' or string($align)='decimalpoint' "><xsl:value-of select="$p+ @length"/></xsl:when> <xsl:otherwise><xsl:value-of select="$p"/></xsl:otherwise> </xsl:choose> </xsl:attribute> <xsl:variable name="w"> <xsl:choose> <xsl:when test="@mslinethickness='thin'">0.1em</xsl:when> <xsl:when test="@mslinethickness='medium'">0.15em</xsl:when> <xsl:when test="@mslinethickness='thick'">0.2em</xsl:when> <xsl:when test="@mslinethickness"><xsl:value-of select="@mslinethickness"/></xsl:when> <xsl:otherwise>0.15em</xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:choose> <xsl:when test="not(string(@length)) or @length=0"> <m:mtd class="mslinemax"> <m:mpadded lspace="-0.2em" width="0em" height="0em"> <m:mfrac linethickness="{$w}"> <m:mspace width=".5em"/> <m:mrow/> </m:mfrac> </m:mpadded> </m:mtd> </xsl:when> <xsl:otherwise> <xsl:variable name="l" select="@length"/> <xsl:for-each select="(//node())[position()&lt;=$l]"> <m:mtd class="msline"> <m:mpadded lspace="-0.2em" width="0em" height="0em"> <m:mfrac linethickness="{$w}"> <m:mspace width=".5em"/> <m:mrow/> </m:mfrac> </m:mpadded> </m:mtd> </xsl:for-each> </xsl:otherwise> </xsl:choose> </m:mtr> </xsl:template> <xsl:template match="m:mscarries" mode="mstack1"> <xsl:param name="p"/> <xsl:variable name="align1" select="ancestor::m:mstack[1]/@stackalign"/> <xsl:variable name="l1"> <xsl:choose> <xsl:when test="string($align1)='left'">0</xsl:when> <xsl:otherwise><xsl:value-of select="count(*)"/></xsl:otherwise> </xsl:choose> </xsl:variable> <m:mtr class="mscarries" l="{$p + $l1 + sum(@position)}"> <xsl:apply-templates select="*" mode="msc"/> </m:mtr> </xsl:template> <xsl:template match="*" mode="msc"> <m:mtd> <xsl:copy-of select="../@location|../@crossout"/> <xsl:choose> <xsl:when test="../@scriptsizemultiplier"> <m:mstyle mathsize="{round(../@scriptsizemultiplier div .007)}%"> <xsl:apply-templates select="."/> </m:mstyle> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="."/> </xsl:otherwise> </xsl:choose> </m:mtd> </xsl:template> <xsl:template match="m:mscarry" mode="msc"> <m:mtd> <xsl:copy-of select="@location|@crossout"/> <xsl:choose> <xsl:when test="../@scriptsizemultiplier"> <m:mstyle mathsize="{round(../@scriptsizemultiplier div .007)}%"> <xsl:apply-templates/> </m:mstyle> </xsl:when> <xsl:otherwise> <xsl:apply-templates/> </xsl:otherwise> </xsl:choose> </m:mtd> </xsl:template> <xsl:template match="m:mlongdiv" priority="11"> <xsl:variable name="ms"> <m:mstack> <xsl:copy-of select="(ancestor-or-self::*/@decimalpoint)[last()]"/> <xsl:choose> <xsl:when test="@longdivstyle='left)(right'"> <m:msrow> <m:mrow><xsl:copy-of select="*[1]"/></m:mrow> <m:mo>)</m:mo> <xsl:copy-of select="*[3]"/> <m:mo>(</m:mo> <xsl:copy-of select="*[2]"/> </m:msrow> </xsl:when> <xsl:when test="@longdivstyle='left/\right'"> <m:msrow> <m:mrow><xsl:copy-of select="*[1]"/></m:mrow> <m:mo>/</m:mo> <xsl:copy-of select="*[3]"/> <m:mo>\</m:mo> <xsl:copy-of select="*[2]"/> </m:msrow> </xsl:when> <xsl:when test="@longdivstyle=':right=right'"> <m:msrow> <xsl:copy-of select="*[3]"/> <m:mo>:</m:mo> <xsl:copy-of select="*[1]"/> <m:mo>=</m:mo> <xsl:copy-of select="*[2]"/> </m:msrow> </xsl:when> <xsl:when test="@longdivstyle='stackedrightright' or @longdivstyle='mediumstackedrightright' or @longdivstyle='shortstackedrightright' or @longdivstyle='stackedleftleft' "> <xsl:attribute name="align">top</xsl:attribute> <xsl:copy-of select="*[3]"/> </xsl:when> <xsl:when test="@longdivstyle='stackedleftlinetop'"> <xsl:copy-of select="*[2]"/> <m:msline length="{string-length(*[3])}"/> <m:msrow> <m:mrow> <m:menclose notation="bottom right"> <xsl:copy-of select="*[1]"/> </m:menclose> </m:mrow> <xsl:copy-of select="*[3]"/> </m:msrow> </xsl:when> <xsl:when test="@longdivstyle='righttop'"> <xsl:copy-of select="*[2]"/> <m:msline length="{string-length(*[3])}"/> <m:msrow> <xsl:copy-of select="*[3]"/> <m:menclose notation="top left bottom"> <xsl:copy-of select="*[1]"/></m:menclose> </m:msrow> </xsl:when> <xsl:otherwise> <xsl:copy-of select="*[2]"/> <m:msline length="{string-length(*[3])+1}"/> <m:msrow> <m:mrow><xsl:copy-of select="*[1]"/><m:mspace width=".2em"/></m:mrow> <m:mpadded voffset=".1em" lspace="-.15em" depth="-.2em" height="-.2em"> <m:mo minsize="1.2em">)</m:mo> </m:mpadded> <xsl:copy-of select="*[3]"/> </m:msrow> </xsl:otherwise> </xsl:choose> <xsl:copy-of select="*[position()&gt;3]"/> </m:mstack> </xsl:variable> <xsl:choose> <xsl:when test="@longdivstyle='stackedrightright'"> <m:menclose notation="right"> <xsl:apply-templates select="c:node-set($ms)"/> </m:menclose> <m:mtable align="top"> <m:mtr> <m:menclose notation="bottom"> <xsl:copy-of select="*[1]"/> </m:menclose> </m:mtr> <m:mtr> <mtd><xsl:copy-of select="*[2]"/></mtd> </m:mtr> </m:mtable> </xsl:when> <xsl:when test="@longdivstyle='mediumstackedrightright'"> <xsl:apply-templates select="c:node-set($ms)"/> <m:menclose notation="left"> <m:mtable align="top"> <m:mtr> <m:menclose notation="bottom"> <xsl:copy-of select="*[1]"/> </m:menclose> </m:mtr> <m:mtr> <mtd><xsl:copy-of select="*[2]"/></mtd> </m:mtr> </m:mtable> </m:menclose> </xsl:when> <xsl:when test="@longdivstyle='shortstackedrightright'"> <xsl:apply-templates select="c:node-set($ms)"/> <m:mtable align="top"> <m:mtr> <m:menclose notation="left bottom"> <xsl:copy-of select="*[1]"/> </m:menclose> </m:mtr> <m:mtr> <mtd><xsl:copy-of select="*[2]"/></mtd> </m:mtr> </m:mtable> </xsl:when> <xsl:when test="@longdivstyle='stackedleftleft'"> <m:mtable align="top"> <m:mtr> <m:menclose notation="bottom"> <xsl:copy-of select="*[1]"/> </m:menclose> </m:mtr> <m:mtr> <mtd><xsl:copy-of select="*[2]"/></mtd> </m:mtr> </m:mtable> <m:menclose notation="left"> <xsl:apply-templates select="c:node-set($ms)"/> </m:menclose> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="c:node-set($ms)"/> </xsl:otherwise> </xsl:choose> </xsl:template> <xsl:template match="m:menclose[@notation='madruwb']" mode="rtl"> <m:menclose notation="bottom right"> <xsl:apply-templates mode="rtl"/> </m:menclose> </xsl:template> </xsl:stylesheet> `;
the_stack
module android.graphics { import Log = android.util.Log; import System = java.lang.System; import StringBuilder = java.lang.StringBuilder; import Point = android.graphics.Point; import Rect = android.graphics.Rect; import RectF = android.graphics.RectF; /** * The Matrix class holds a 3x3 matrix for transforming coordinates. * FIXME recycle Array or share Array: new Array<number>(9) */ export class Matrix { //!< use with getValues/setValues static MSCALE_X:number = 0; //!< use with getValues/setValues static MSKEW_X:number = 1; //!< use with getValues/setValues static MTRANS_X:number = 2; //!< use with getValues/setValues static MSKEW_Y:number = 3; //!< use with getValues/setValues static MSCALE_Y:number = 4; //!< use with getValues/setValues static MTRANS_Y:number = 5; //!< use with getValues/setValues static MPERSP_0:number = 6; //!< use with getValues/setValues static MPERSP_1:number = 7; //!< use with getValues/setValues static MPERSP_2:number = 8; private static MATRIX_SIZE:number = 9; private mValues = androidui.util.ArrayCreator.newNumberArray(Matrix.MATRIX_SIZE); /** @hide */ static IDENTITY_MATRIX:Matrix = (()=>{ class _Inner extends Matrix { oops():void { throw Error(`new IllegalStateException("Matrix can not be modified")`); } set(src:Matrix):void { this.oops(); } reset():void { this.oops(); } setTranslate(dx:number, dy:number):void { this.oops(); } setScale(sx:number, sy:number, px?:number, py?:number):void { this.oops(); } setRotate(degrees:number, px?:number, py?:number):void { this.oops(); } setSinCos(sinValue:number, cosValue:number, px?:number, py?:number):void { this.oops(); } setSkew(kx:number, ky:number, px?:number, py?:number):void { this.oops(); } setConcat(a:Matrix, b:Matrix):boolean { this.oops(); return false; } preTranslate(dx:number, dy:number):boolean { this.oops(); return false; } preScale(sx:number, sy:number, px?:number, py?:number):boolean { this.oops(); return false; } preRotate(degrees:number, px?:number, py?:number):boolean { this.oops(); return false; } preSkew(kx:number, ky:number, px?:number, py?:number):boolean { this.oops(); return false; } preConcat(other:Matrix):boolean { this.oops(); return false; } postTranslate(dx:number, dy:number):boolean { this.oops(); return false; } postScale(sx:number, sy:number, px?:number, py?:number):boolean { this.oops(); return false; } postRotate(degrees:number, px?:number, py?:number):boolean { this.oops(); return false; } postSkew(kx:number, ky:number, px?:number, py?:number):boolean { this.oops(); return false; } postConcat(other:Matrix):boolean { this.oops(); return false; } setRectToRect(src:RectF, dst:RectF, stf:Matrix.ScaleToFit):boolean { this.oops(); return false; } setPolyToPoly(src:number[], srcIndex:number, dst:number[], dstIndex:number, pointCount:number):boolean { this.oops(); return false; } setValues(values:number[]):void { this.oops(); } } return new _Inner(); })(); /** * Create an identity matrix */ constructor(); /** * Create a matrix that is a (deep) copy of src * @param src The matrix to copy into this matrix */ constructor(src:Matrix); /** * Create a matrix that is a (deep) copy of src * @param values The matrix values to copy into this matrix */ constructor(values:number[]); constructor(values?:Matrix|number[]) { if(values instanceof Matrix) this.set(values); else if(values instanceof Array){ System.arraycopy(values, 0, this.mValues, 0, Matrix.MATRIX_SIZE); }else{ Matrix.reset(this.mValues); } } /** * Returns true if the matrix is identity. * This maybe faster than testing if (getType() == 0) */ isIdentity():boolean { for (let i:number = 0, k:number = 0; i < 3; i++) { for (let j:number = 0; j < 3; j++, k++) { if (this.mValues[k] != ((i == j) ? 1 : 0)) { return false; } } } return true; } hasPerspective():boolean { return (this.mValues[6] != 0 || this.mValues[7] != 0 || this.mValues[8] != 1); } /** * Returns true if will map a rectangle to another rectangle. This can be * true if the matrix is identity, scale-only, or rotates a multiple of 90 * degrees. */ rectStaysRect():boolean { return (this.computeTypeMask() & Matrix.kRectStaysRect_Mask) != 0; } /** * (deep) copy the src matrix into this matrix. If src is null, reset this * matrix to the identity matrix. */ set(src:Matrix):void { if (src == null) { this.reset(); } else { System.arraycopy(src.mValues, 0, this.mValues, 0, Matrix.MATRIX_SIZE); } } /** Returns true iff obj is a Matrix and its values equal our values. */ equals(obj:any):boolean { //if (obj == this) return true; -- NaN value would mean matrix != itself if (!(obj instanceof Matrix)) return false; let another:Matrix = <Matrix> obj; for (let i:number = 0; i < Matrix.MATRIX_SIZE; i++) { if (this.mValues[i] != another.mValues[i]) { return false; } } return true; } hashCode():number { // really using this at the moment, so we take the easy way out. return 44; } /** Set the matrix to identity */ reset():void { Matrix.reset(this.mValues); } /** Set the matrix to translate by (dx, dy). */ setTranslate(dx:number, dy:number):void { Matrix.setTranslate(this.mValues, dx, dy); } /** * Set the matrix to scale by sx and sy, with a pivot point at (px, py). * The pivot point is the coordinate that should remain unchanged by the * specified transformation. */ setScale(sx:number, sy:number, px?:number, py?:number):void { if(px==null || py==null){ this.mValues[0] = sx; this.mValues[1] = 0; this.mValues[2] = 0; this.mValues[3] = 0; this.mValues[4] = sy; this.mValues[5] = 0; this.mValues[6] = 0; this.mValues[7] = 0; this.mValues[8] = 1; }else{ this.mValues = Matrix.getScale(sx, sy, px, py); } } /** * Set the matrix to rotate by the specified number of degrees, with a pivot * point at (px, py). The pivot point is the coordinate that should remain * unchanged by the specified transformation. */ setRotate(degrees:number, px?:number, py?:number):void { if(px==null || py==null){ Matrix.setRotate_1(this.mValues, degrees); }else{ this.mValues = Matrix.getRotate_3(degrees, px, py); } } /** * Set the matrix to rotate by the specified sine and cosine values, with a * pivot point at (px, py). The pivot point is the coordinate that should * remain unchanged by the specified transformation. */ setSinCos(sinValue:number, cosValue:number, px?:number, py?:number):void { if(px==null || py==null){ Matrix.setRotate_2(this.mValues, sinValue, cosValue); }else { // translate so that the pivot is in 0,0 Matrix.setTranslate(this.mValues, -px, -py); // scale this.postTransform(Matrix.getRotate_2(sinValue, cosValue)); // translate back the pivot this.postTransform(Matrix.getTranslate(px, py)); } } /** * Set the matrix to skew by sx and sy, with a pivot point at (px, py). * The pivot point is the coordinate that should remain unchanged by the * specified transformation. */ setSkew(kx:number, ky:number, px?:number, py?:number):void { if(px==null || py==null){ this.mValues[0] = 1; this.mValues[1] = kx; this.mValues[2] = -0; this.mValues[3] = ky; this.mValues[4] = 1; this.mValues[5] = 0; this.mValues[6] = 0; this.mValues[7] = 0; this.mValues[8] = 1; }else{ this.mValues = Matrix.getSkew(kx, ky, px, py); } } /** * Set the matrix to the concatenation of the two specified matrices, * returning true if the the result can be represented. Either of the two * matrices may also be the target matrix. this = a * b */ setConcat(a:Matrix, b:Matrix):boolean { Matrix.multiply(this.mValues, a.mValues, b.mValues); return true; } /** * Preconcats the matrix with the specified translation. * M' = M * T(dx, dy) */ preTranslate(dx:number, dy:number):boolean { this.preTransform(Matrix.getTranslate(dx, dy)); return true; } /** * Preconcats the matrix with the specified scale. * M' = M * S(sx, sy, px, py) */ preScale(sx:number, sy:number, px?:number, py?:number):boolean { this.preTransform(Matrix.getScale(sx, sy, px, py)); return true; } /** * Preconcats the matrix with the specified rotation. * M' = M * R(degrees) * M' = M * R(degrees, px, py) */ preRotate(degrees:number, px?:number, py?:number):boolean { if(px==null || py==null){ let rad:number = Math_toRadians(degrees); let sin:number = <number> Math.sin(rad); let cos:number = <number> Math.cos(rad); this.preTransform(Matrix.getRotate_2(sin, cos)); return true; } this.preTransform(Matrix.getRotate_3(degrees, px, py)); return true; } /** * Preconcats the matrix with the specified skew. * M' = M * K(kx, ky) * M' = M * K(kx, ky, px, py) */ preSkew(kx:number, ky:number, px?:number, py?:number):boolean { this.preTransform(Matrix.getSkew(kx, ky, px, py)); return true; } /** * Preconcats the matrix with the specified matrix. * M' = M * other */ preConcat(other:Matrix):boolean { this.preTransform(other.mValues); return true; } /** * Postconcats the matrix with the specified translation. * M' = T(dx, dy) * M */ postTranslate(dx:number, dy:number):boolean { this.postTransform(Matrix.getTranslate(dx, dy)); return true; } /** * Postconcats the matrix with the specified scale. * M' = S(sx, sy) * M * M' = S(sx, sy, px, py) * M */ postScale(sx:number, sy:number, px?:number, py?:number):boolean { this.postTransform(Matrix.getScale(sx, sy, px, py)); return true; } /** * Postconcats the matrix with the specified rotation. * M' = R(degrees) * M * M' = R(degrees, px, py) * M */ postRotate(degrees:number, px?:number, py?:number):boolean { this.postTransform(Matrix.getRotate_3(degrees, px, py)); return true; } /** * Postconcats the matrix with the specified skew. * M' = K(kx, ky) * M * M' = K(kx, ky, px, py) * M */ postSkew(kx:number, ky:number, px?:number, py?:number):boolean { this.postTransform(Matrix.getSkew(kx, ky, px, py)); return true; } /** * Postconcats the matrix with the specified matrix. * M' = other * M */ postConcat(other:Matrix):boolean { this.postTransform(other.mValues); return true; } /** * Set the matrix to the scale and translate values that map the source * rectangle to the destination rectangle, returning true if the the result * can be represented. * * @param src the source rectangle to map from. * @param dst the destination rectangle to map to. * @param stf the ScaleToFit option * @return true if the matrix can be represented by the rectangle mapping. */ setRectToRect(src:RectF, dst:RectF, stf:Matrix.ScaleToFit):boolean { if (dst == null || src == null) { throw Error(`new NullPointerException()`); } let d:Matrix = this; if (src.isEmpty()) { Matrix.reset(d.mValues); return false; } if (dst.isEmpty()) { d.mValues[0] = d.mValues[1] = d.mValues[2] = d.mValues[3] = d.mValues[4] = d.mValues[5] = d.mValues[6] = d.mValues[7] = 0; d.mValues[8] = 1; } else { let tx:number, sx:number = dst.width() / src.width(); let ty:number, sy:number = dst.height() / src.height(); let xLarger:boolean = false; if (stf != Matrix.ScaleToFit.FILL) { if (sx > sy) { xLarger = true; sx = sy; } else { sy = sx; } } tx = dst.left - src.left * sx; ty = dst.top - src.top * sy; if (stf == Matrix.ScaleToFit.CENTER || stf == Matrix.ScaleToFit.END) { let diff:number; if (xLarger) { diff = dst.width() - src.width() * sy; } else { diff = dst.height() - src.height() * sy; } if (stf == Matrix.ScaleToFit.CENTER) { diff = diff / 2; } if (xLarger) { tx += diff; } else { ty += diff; } } d.mValues[0] = sx; d.mValues[4] = sy; d.mValues[2] = tx; d.mValues[5] = ty; d.mValues[1] = d.mValues[3] = d.mValues[6] = d.mValues[7] = 0; } // shared cleanup d.mValues[8] = 1; return true; } // private helper to perform range checks on arrays of "points" private static checkPointArrays(src:number[], srcIndex:number, dst:number[], dstIndex:number, pointCount:number):void { // check for too-small and too-big indices let srcStop:number = srcIndex + (pointCount << 1); let dstStop:number = dstIndex + (pointCount << 1); if ((pointCount | srcIndex | dstIndex | srcStop | dstStop) < 0 || srcStop > src.length || dstStop > dst.length) { throw Error(`new ArrayIndexOutOfBoundsException()`); } } ///** // * Set the matrix such that the specified src points would map to the // * specified dst points. The "points" are represented as an array of floats, // * order [x0, y0, x1, y1, ...], where each "point" is 2 float values. // * // * @param src The array of src [x,y] pairs (points) // * @param srcIndex Index of the first pair of src values // * @param dst The array of dst [x,y] pairs (points) // * @param dstIndex Index of the first pair of dst values // * @param pointCount The number of pairs/points to be used. Must be [0..4] // * @return true if the matrix was set to the specified transformation // */ //setPolyToPoly(src:number[], srcIndex:number, dst:number[], dstIndex:number, pointCount:number):boolean { // Log.e('Matrix', "Matrix.setPolyToPoly is not supported"); // return false; //} ///** // * If this matrix can be inverted, return true and if inverse is not null, // * set inverse to be the inverse of this matrix. If this matrix cannot be // * inverted, ignore inverse and return false. // */ //invert(inverse:Matrix):boolean { // try { // let matrixInverter:MatrixInverter = this.getAffineTransform(); // let inverseTransform:MatrixInverter = matrixInverter.createInverse(); // inverse.mValues[0] = <number> inverseTransform.getScaleX(); // inverse.mValues[1] = <number> inverseTransform.getShearX(); // inverse.mValues[2] = <number> inverseTransform.getTranslateX(); // inverse.mValues[3] = <number> inverseTransform.getScaleX(); // inverse.mValues[4] = <number> inverseTransform.getShearY(); // inverse.mValues[5] = <number> inverseTransform.getTranslateY(); // return true; // } catch (e){ // return false; // } //} /** * Apply this matrix to the array of 2D points specified by src, and write * the transformed points into the array of points specified by dst. The * two arrays represent their "points" as pairs of floats [x, y]. * * @param dst The array of dst points (x,y pairs) * @param dstIndex The index of the first [x,y] pair of dst floats * @param src The array of src points (x,y pairs) * @param srcIndex The index of the first [x,y] pair of src floats * @param pointCount The number of points (x,y pairs) to transform */ mapPoints(dst:number[], dstIndex=0, src=dst, srcIndex=0, pointCount=dst.length >> 1):void { Matrix.checkPointArrays(src, srcIndex, dst, dstIndex, pointCount); const count:number = pointCount * 2; let tmpDest:number[] = dst; let inPlace:boolean = dst == src; if (inPlace) { tmpDest = androidui.util.ArrayCreator.newNumberArray(dstIndex + count); } for (let i:number = 0; i < count; i += 2) { // just in case we are doing in place, we better put this in temp vars let x:number = this.mValues[0] * src[i + srcIndex] + this.mValues[1] * src[i + srcIndex + 1] + this.mValues[2]; let y:number = this.mValues[3] * src[i + srcIndex] + this.mValues[4] * src[i + srcIndex + 1] + this.mValues[5]; tmpDest[i + dstIndex] = x; tmpDest[i + dstIndex + 1] = y; } if (inPlace) { System.arraycopy(tmpDest, dstIndex, dst, dstIndex, count); } } /** * Apply this matrix to the array of 2D vectors specified by src, and write * the transformed vectors into the array of vectors specified by dst. The * two arrays represent their "vectors" as pairs of floats [x, y]. * * Note: this method does not apply the translation associated with the matrix. Use * {@link Matrix#mapPoints(float[], int, float[], int, int)} if you want the translation * to be applied. * * @param dst The array of dst vectors (x,y pairs) * @param dstIndex The index of the first [x,y] pair of dst floats * @param src The array of src vectors (x,y pairs) * @param srcIndex The index of the first [x,y] pair of src floats * @param ptCount The number of vectors (x,y pairs) to transform */ mapVectors(dst:number[], dstIndex=0, src=dst, srcIndex=0, ptCount=dst.length >> 1):void { Matrix.checkPointArrays(src, srcIndex, dst, dstIndex, ptCount); if (this.hasPerspective()) { // transform the (0,0) point let origin:number[] = [ 0., 0. ]; this.mapPoints(origin); // translate the vector data as points this.mapPoints(dst, dstIndex, src, srcIndex, ptCount); // then substract the transformed origin. const count:number = ptCount * 2; for (let i:number = 0; i < count; i += 2) { dst[dstIndex + i] = dst[dstIndex + i] - origin[0]; dst[dstIndex + i + 1] = dst[dstIndex + i + 1] - origin[1]; } } else { // make a copy of the matrix let copy:Matrix = new Matrix(this.mValues); // remove the translation Matrix.setTranslate(copy.mValues, 0, 0); // map the content as points. copy.mapPoints(dst, dstIndex, src, srcIndex, ptCount); } } /** * Apply this matrix to the src rectangle, and write the transformed * rectangle into dst. This is accomplished by transforming the 4 corners of * src, and then setting dst to the bounds of those points. * * @param dst Where the transformed rectangle is written. * @param src The original rectangle to be transformed. * @return the result of calling rectStaysRect() */ mapRect(dst:RectF, src=dst):boolean { if (dst == null || src == null) { throw Error(`new NullPointerException()`); } // array with 4 corners let corners:number[] = [ src.left, src.top, src.right, src.top, src.right, src.bottom, src.left, src.bottom ]; // apply the transform to them. this.mapPoints(corners); // now put the result in the rect. We take the min/max of Xs and min/max of Ys dst.left = Math.min(Math.min(corners[0], corners[2]), Math.min(corners[4], corners[6])); dst.right = Math.max(Math.max(corners[0], corners[2]), Math.max(corners[4], corners[6])); dst.top = Math.min(Math.min(corners[1], corners[3]), Math.min(corners[5], corners[7])); dst.bottom = Math.max(Math.max(corners[1], corners[3]), Math.max(corners[5], corners[7])); return (this.computeTypeMask() & Matrix.kRectStaysRect_Mask) != 0; } /** * Return the mean radius of a circle after it has been mapped by * this matrix. NOTE: in perspective this value assumes the circle * has its center at the origin. */ mapRadius(radius:number):number { let src:number[] = [ radius, 0., 0., radius ]; this.mapVectors(src, 0, src, 0, 2); let l1:number = Matrix.getPointLength(src, 0); let l2:number = Matrix.getPointLength(src, 2); return <number> Math.sqrt(l1 * l2); } /** Copy 9 values from the matrix into the array. */ getValues(values:number[]):void { if (values.length < 9) { throw Error(`new ArrayIndexOutOfBoundsException()`); } System.arraycopy(this.mValues, 0, values, 0, Matrix.MATRIX_SIZE); } /** Copy 9 values from the array into the matrix. Depending on the implementation of Matrix, these may be transformed into 16.16 integers in the Matrix, such that a subsequent call to getValues() will not yield exactly the same values. */ setValues(values:number[]):void { if (values.length < 9) { throw Error(`new ArrayIndexOutOfBoundsException()`); } System.arraycopy(values, 0, this.mValues, 0, Matrix.MATRIX_SIZE); } toString():string { let sb:StringBuilder = new StringBuilder(64); sb.append("Matrix{"); this.toShortString(sb); sb.append('}'); return sb.toString(); } /** * @hide */ toShortString(sb:StringBuilder):void { let values:number[] = androidui.util.ArrayCreator.newNumberArray(9); this.getValues(values); sb.append('['); sb.append(values[0]); sb.append(", "); sb.append(values[1]); sb.append(", "); sb.append(values[2]); sb.append("]["); sb.append(values[3]); sb.append(", "); sb.append(values[4]); sb.append(", "); sb.append(values[5]); sb.append("]["); sb.append(values[6]); sb.append(", "); sb.append(values[7]); sb.append(", "); sb.append(values[8]); sb.append(']'); } /** * Adds the given transformation to the current Matrix * <p/>This in effect does this = this*matrix * @param matrix */ private postTransform(matrix:number[]):void { let tmp:number[] = androidui.util.ArrayCreator.newNumberArray(9); Matrix.multiply(tmp, this.mValues, matrix); this.mValues = tmp; } /** * Adds the given transformation to the current Matrix * <p/>This in effect does this = matrix*this * @param matrix */ private preTransform(matrix:number[]):void { let tmp:number[] = androidui.util.ArrayCreator.newNumberArray(9); Matrix.multiply(tmp, matrix, this.mValues); this.mValues = tmp; } private static getPointLength(src:number[], index:number):number { return <number> Math.sqrt(src[index] * src[index] + src[index + 1] * src[index + 1]); } /** * multiply two matrices and store them in a 3rd. * <p/>This in effect does dest = a*b * dest cannot be the same as a or b. */ /*package*/ static multiply(dest:number[], a:number[], b:number[]):void { // first row dest[0] = b[0] * a[0] + b[1] * a[3] + b[2] * a[6]; dest[1] = b[0] * a[1] + b[1] * a[4] + b[2] * a[7]; dest[2] = b[0] * a[2] + b[1] * a[5] + b[2] * a[8]; // 2nd row dest[3] = b[3] * a[0] + b[4] * a[3] + b[5] * a[6]; dest[4] = b[3] * a[1] + b[4] * a[4] + b[5] * a[7]; dest[5] = b[3] * a[2] + b[4] * a[5] + b[5] * a[8]; // 3rd row dest[6] = b[6] * a[0] + b[7] * a[3] + b[8] * a[6]; dest[7] = b[6] * a[1] + b[7] * a[4] + b[8] * a[7]; dest[8] = b[6] * a[2] + b[7] * a[5] + b[8] * a[8]; } /** * Returns a matrix that represents a given translate * @param dx * @param dy * @return */ /*package*/ static getTranslate(dx:number, dy:number):number[] { return this.setTranslate(androidui.util.ArrayCreator.newNumberArray(9), dx, dy); } /*package*/ static setTranslate(dest:number[], dx:number, dy:number):number[] { dest[0] = 1; dest[1] = 0; dest[2] = dx; dest[3] = 0; dest[4] = 1; dest[5] = dy; dest[6] = 0; dest[7] = 0; dest[8] = 1; return dest; } /** * Returns a matrix that represents the given scale info. * @param sx * @param sy * @param px * @param py */ /*package*/ static getScale(sx:number, sy:number, px?:number, py?:number):number[] { if(px==null || py==null){ return [ sx, 0, 0, 0, sy, 0, 0, 0, 1 ]; } let tmp:number[] = androidui.util.ArrayCreator.newNumberArray(9); let tmp2:number[] = androidui.util.ArrayCreator.newNumberArray(9); // TODO: do it in one pass // translate tmp so that the pivot is in 0,0 this.setTranslate(tmp, -px, -py); // scale into tmp2 Matrix.multiply(tmp2, tmp, Matrix.getScale(sx, sy)); // translate back the pivot back into tmp Matrix.multiply(tmp, tmp2, Matrix.getTranslate(px, py)); return tmp; } /*package*/ static getRotate_1(degrees:number):number[] { let rad:number = Math_toRadians(degrees); let sin:number = Math.sin(rad); let cos:number = Math.cos(rad); return Matrix.getRotate_2(sin, cos); } /*package*/ static getRotate_2(sin:number, cos:number):number[] { return this.setRotate_2(androidui.util.ArrayCreator.newNumberArray(9), sin, cos); } /*package*/ static setRotate_1(dest:number[], degrees:number):number[] { let rad:number = Math_toRadians(degrees); let sin:number = <number> Math.sin(rad); let cos:number = <number> Math.cos(rad); return Matrix.setRotate_2(dest, sin, cos); } /*package*/ static setRotate_2(dest:number[], sin:number, cos:number):number[] { dest[0] = cos; dest[1] = -sin; dest[2] = 0; dest[3] = sin; dest[4] = cos; dest[5] = 0; dest[6] = 0; dest[7] = 0; dest[8] = 1; return dest; } /*package*/ static getRotate_3(degrees:number, px:number, py:number):number[] { let tmp:number[] = androidui.util.ArrayCreator.newNumberArray(9); let tmp2:number[] = androidui.util.ArrayCreator.newNumberArray(9); // TODO: do it in one pass // translate so that the pivot is in 0,0 this.setTranslate(tmp, -px, -py); // rotate into tmp2 let rad:number = Math_toRadians(degrees); let cos:number = <number> Math.cos(rad); let sin:number = <number> Math.sin(rad); Matrix.multiply(tmp2, tmp, Matrix.getRotate_2(sin, cos)); // translate back the pivot back into tmp Matrix.multiply(tmp, tmp2, Matrix.getTranslate(px, py)); return tmp; } /*package*/ static getSkew(kx:number, ky:number, px?:number, py?:number):number[] { if(px==null || py==null){ return [ 1, kx, 0, ky, 1, 0, 0, 0, 1 ]; } let tmp:number[] = androidui.util.ArrayCreator.newNumberArray(9); let tmp2:number[] = androidui.util.ArrayCreator.newNumberArray(9); // TODO: do it in one pass // translate so that the pivot is in 0,0 this.setTranslate(tmp, -px, -py); // skew into tmp2 Matrix.multiply(tmp2, tmp, [ 1, kx, 0, ky, 1, 0, 0, 0, 1 ]); // translate back the pivot back into tmp Matrix.multiply(tmp, tmp2, Matrix.getTranslate(px, py)); return tmp; } // ---- Private helper methods ---- ///** // * Returns an {@link java.awt.geom.AffineTransform} matching the matrix. // */ //getAffineTransform():MatrixInverter { // return this.getAffineTransform(this.mValues); //} // ///*package*/ //static getAffineTransform(matrix:number[]):MatrixInverter { // // the order is 0, 3, 1, 4, 2, 5... // return new MatrixInverter(matrix[0], matrix[3], matrix[1], matrix[4], matrix[2], matrix[5]); //} /** * Reset a matrix to the identity */ private static reset(mtx:number[]):void { mtx[0] = 1; mtx[1] = 0; mtx[2] = 0; mtx[3] = 0; mtx[4] = 1; mtx[5] = 0; mtx[6] = 0; mtx[7] = 0; mtx[8] = 1; } private static kIdentity_Mask:number = 0; //!< set if the matrix has translation private static kTranslate_Mask:number = 0x01; //!< set if the matrix has X or Y scale private static kScale_Mask:number = 0x02; //!< set if the matrix skews or rotates private static kAffine_Mask:number = 0x04; //!< set if the matrix is in perspective private static kPerspective_Mask:number = 0x08; private static kRectStaysRect_Mask:number = 0x10; private static kUnknown_Mask:number = 0x80; private static kAllMasks:number = Matrix.kTranslate_Mask | Matrix.kScale_Mask | Matrix.kAffine_Mask | Matrix.kPerspective_Mask | Matrix.kRectStaysRect_Mask; // these guys align with the masks, so we can compute a mask from a variable 0/1 private static kTranslate_Shift:number = 0; private static kScale_Shift:number = 1; private static kAffine_Shift:number = 2; private static kPerspective_Shift:number = 3; private static kRectStaysRect_Shift:number = 4; private computeTypeMask():number { let mask:number = 0; if (this.mValues[6] != 0. || this.mValues[7] != 0. || this.mValues[8] != 1.) { mask |= Matrix.kPerspective_Mask; } if (this.mValues[2] != 0. || this.mValues[5] != 0.) { mask |= Matrix.kTranslate_Mask; } let m00:number = this.mValues[0]; let m01:number = this.mValues[1]; let m10:number = this.mValues[3]; let m11:number = this.mValues[4]; if (m01 != 0. || m10 != 0.) { mask |= Matrix.kAffine_Mask; } if (m00 != 1. || m11 != 1.) { mask |= Matrix.kScale_Mask; } if ((mask & Matrix.kPerspective_Mask) == 0) { // map non-zero to 1 let im00:number = m00 != 0 ? 1 : 0; let im01:number = m01 != 0 ? 1 : 0; let im10:number = m10 != 0 ? 1 : 0; let im11:number = m11 != 0 ? 1 : 0; // record if the (p)rimary and (s)econdary diagonals are all 0 or // all non-zero (answer is 0 or 1) // true if both are 0 let dp0:number = (im00 | im11) ^ 1; // true if both are 1 let dp1:number = im00 & im11; // true if both are 0 let ds0:number = (im01 | im10) ^ 1; // true if both are 1 let ds1:number = im01 & im10; // return 1 if primary is 1 and secondary is 0 or // primary is 0 and secondary is 1 mask |= ((dp0 & ds1) | (dp1 & ds0)) << Matrix.kRectStaysRect_Shift; } return mask; } } export module Matrix{ /** Controlls how the src rect should align into the dst rect for setRectToRect(). */ export enum ScaleToFit { /** * Scale in X and Y independently, so that src matches dst exactly. * This may change the aspect ratio of the src. */ FILL /*() { } */, /** * Compute a scale that will maintain the original src aspect ratio, * but will also ensure that src fits entirely inside dst. At least one * axis (X or Y) will fit exactly. START aligns the result to the * left and top edges of dst. */ START /*() { } */, /** * Compute a scale that will maintain the original src aspect ratio, * but will also ensure that src fits entirely inside dst. At least one * axis (X or Y) will fit exactly. The result is centered inside dst. */ CENTER /*() { } */, /** * Compute a scale that will maintain the original src aspect ratio, * but will also ensure that src fits entirely inside dst. At least one * axis (X or Y) will fit exactly. END aligns the result to the * right and bottom edges of dst. */ END /*() { } */ /*; */}} function Math_toRadians(angdeg:number):number { return angdeg / 180.0 * Math.PI; } }
the_stack
import * as path from 'path'; import * as FS from '../../tools/fs'; import * as tar from 'tar'; import * as semver from 'semver'; import * as Tools from '../../tools/index'; import ncp from 'ncp'; import Logger from '../../tools/env.logger'; import LogsService from '../../tools/env.logger.service'; import ControllerPluginPackage, { IPackageJson } from './plugin.package'; import ControllerPluginStore from './plugins.store'; import ControllerPluginRender from './plugin.controller.render'; import ControllerPluginProcess, { TConnectionFactory } from './plugin.controller.process'; import ControllerIPCPlugin from './plugin.process.ipc'; import ServicePaths from '../../services/service.paths'; import ServiceElectronService from '../../services/service.electron.state'; import ServicePackage from '../../services/service.package'; import ServiceElectron from '../../services/service.electron'; import { IPCMessages } from '../../services/service.electron'; import { CommonInterfaces } from '../../interfaces/interface.common'; import { getPluginReleaseInfoFromStr } from './plugins.validator'; export { IPackageJson, TConnectionFactory }; export type TPluginName = string; export interface IInstalledPluginInfo extends CommonInterfaces.Plugins.IPlugin { package: { render: ControllerPluginPackage | undefined; process: ControllerPluginPackage | undefined; }; controller: { render: ControllerPluginRender | undefined; process: ControllerPluginProcess | undefined; }; } const CPluginInfoFile: string = 'info.json'; const CPluginsFolders = { process: 'process', render: 'render', }; export class ErrorCompatibility extends Error { public phash: string; public expected: string; constructor(msg: string, phash: string, expected: string) { super(msg); this.expected = expected; this.phash = phash; } } export default class ControllerPluginInstalled { private _logger: Logger; private _path: string; private _name: string; private _info: CommonInterfaces.Plugins.IPlugin | undefined; private _packages: { render: ControllerPluginPackage | undefined; process: ControllerPluginPackage | undefined; } = { render: undefined, process: undefined, }; private _controllers: { render: ControllerPluginRender | undefined; process: ControllerPluginProcess | undefined; } = { render: undefined, process: undefined, }; private _store: ControllerPluginStore; private _token: string = Tools.guid(); private _id: number = Tools.sequence(); private _subscriptions: { [key: string]: Tools.Subscription } = {}; constructor(_name: string, _path: string, store: ControllerPluginStore) { this._name = _name; this._path = _path; this._store = store; this._logger = new Logger(`ControllerPluginInstalled (${this._path})`); ServiceElectron.IPC.subscribe(IPCMessages.PluginsLogsRequest, this._ipc_PluginsLogsRequest.bind(this)).then((subscription: Tools.Subscription) => { this._subscriptions.PluginsLogsRequest = subscription; }).catch((error: Error) => { this._logger.warn(`Fail to subscribe on PluginsLogsRequest due error: ${error.message}`); }); } public destroy(): Promise<void> { return new Promise((resolve) => { Object.keys(this._subscriptions).forEach((key: string) => { this._subscriptions[key].destroy(); }); if (this._controllers.process === undefined) { return resolve(); } return this._controllers.process.destroy().then(() => { this._controllers.process = undefined; }).catch((error: Error) => { this._logger.warn(`Error during destroy plugin's process: ${error.message}`); }).finally(() => { resolve(); }); }); } public shutdown(): Promise<void> { return new Promise((resolve) => { if (this._controllers.process === undefined) { return resolve(); } return this._controllers.process.destroy().then(() => { this._controllers.process = undefined; }).catch((error: Error) => { this._logger.warn(`Error during shutdown plugin's process: ${error.message}`); }).finally(() => { resolve(); }); }); } public read(): Promise<void> { return new Promise((resolve, reject) => { const filename: string = path.resolve(this._path, CPluginInfoFile); ServiceElectronService.logStateToRender(`Reading plugin data "${path.basename(this._path)}"`); FS.exist(filename).then((exist: boolean) => { if (!exist) { return reject(new Error(this._logger.warn(`Not valid plugin. Info-file "${filename}" doesn't exist`))); } FS.readTextFile(filename).then((content: string) => { const plugin: CommonInterfaces.Plugins.IPlugin | Error = getPluginReleaseInfoFromStr(content); if (plugin instanceof Error) { return reject(plugin); } if (!semver.valid(plugin.version)) { return reject(new Error(`Plugin has not valid version: "${plugin.version}"`)); } this._info = plugin; if (plugin.phash !== ServicePackage.getHash(plugin.dependencies)) { this._logger.warn(`Plugin could not be used, because hash dismatch.\n\t- plugin hash: ${plugin.phash}\n\t- expected plugin hash: ${ServicePackage.getHash(plugin.dependencies)}\n\t- chipmunk hash: ${ServicePackage.getHash()}`); return reject(new ErrorCompatibility(`Version-hash dismatch`, plugin.phash, ServicePackage.getHash(plugin.dependencies))); } ServiceElectronService.logStateToRender(`Reading plugin package "${path.basename(this._path)}"`); this._readPackages().then(() => { if (this._packages.render === undefined && this._packages.process === undefined) { this._info = undefined; return reject(new Error(this._logger.warn(`Plugin doesn't have valid [render] and [process]. Plugin will not be used.`))); } ServiceElectronService.logStateToRender(`Creating controllers for "${path.basename(this._path)}"`); this._addControllers().then(() => { this._verify(); this._logPluginState(); resolve(); }).catch((controllersErr: Error) => { reject(controllersErr); }); }).catch((packageJsonErr: Error) => { this._info = undefined; reject(new Error(this._logger.warn(`Error during reading package.json of plugin: ${packageJsonErr.message}. Plugin will not be used.`))); }); }).catch((readingErr: Error) => { this._logger.warn(`Fail read info-file due error: ${readingErr.message}`); reject(readingErr); }); }).catch((err: Error) => { this._logger.warn(`Fail check info-file due error: ${err.message}`); reject(err); }); }); } public getInfo(): CommonInterfaces.Plugins.IPlugin | undefined { if (this._info === undefined) { return undefined; } return Object.assign({}, this._info); } public getName(): string { if (this._info === undefined) { this._logger.error(`Attempt to get name of plugin, which isn't read or not valid.`); } return this._info?.name as string; } public getDisplayName(): string { if (this._info === undefined) { this._logger.error(`Attempt to get display_name of plugin, which isn't read or not valid.`); } return this._info?.display_name as string; } public getPath(): string { return this._path; } public getId(): number { return this._id; } public getToken(): string { return this._token; } public getSessionIPC(session: string): ControllerIPCPlugin | undefined { if (this._controllers.process === undefined) { return undefined; } return this._controllers.process.getSessionIPC(session); } public getRenderController(): ControllerPluginRender | undefined { if (this._controllers.render === undefined) { return undefined; } return this._controllers.render; } public remove(): Promise<void> { return new Promise((resolve, reject) => { ServiceElectronService.logStateToRender(`Removing plugin "${path.basename(this._path)}"`); FS.rmdir(this._path).then(() => { ServiceElectronService.logStateToRender(`Plugin "${path.basename(this._path)}" has been removed`); resolve(); }).catch((error: Error) => { this._logger.warn(`Fail to remove file due error: ${error.message}`); reject(error); }); }); } public update(version?: string): Promise<void> { return new Promise((resolve, reject) => { if (this._info === undefined) { return reject(new Error(this._logger.warn(`Cannot update plugin, because it isn't initialized.`))); } if (typeof version !== 'string' || !semver.valid(version)) { version = this._store.getLatestVersion(this.getName())?.version; if (version === undefined) { return reject(new Error(this._logger.warn(`Fail to find a suitable version for plugin "${this.getName()}"`))); } } const target: string = version; // Remove current version of plugin this.remove().then(() => { this._logger.debug(`Plugin is removed. New version will be downloaded`); ServiceElectronService.logStateToRender(`Updating plugin "${path.basename(this._path)}"...`); // Download updated version of plugin this._store.download(this._name, target).then((filename: string) => { this._logger.debug(`New version of plugin is downloaded: ${filename}`); ServiceElectronService.logStateToRender(`Unpacking package of plugin "${path.basename(this._path)}"`); // Unpack plugin this._unpack(filename).then(() => { this._logger.debug(`Plugin is unpacked`); ServiceElectronService.logStateToRender(`Plugin "${path.basename(this._path)}" has been unpacked`); // Read plugin info once again this.read().then(() => { this._logger.debug(`Plugin is successfully updated`); resolve(); }).catch((readErr: Error) => { reject(new Error(this._logger.warn(`Fail to updated plugin due error: ${readErr.message}`))); }); }).catch((unpackErr: Error) => { reject(new Error(this._logger.warn(`Fail to unpack plugin due error: ${unpackErr.message}`))); }); }).catch((downloadErr: Error) => { reject(new Error(`Fail to download new version of plugin due error: ${downloadErr.message}`)); }); }).catch((removeErr: Error) => { reject(new Error(this._logger.warn(`Fail to remove plugin due error: ${removeErr.message}`))); }); }); } public install(version?: string): Promise<void> { return new Promise((resolve, reject) => { const available: CommonInterfaces.Plugins.IPlugin | undefined = this._store.getInfo(this._name); if (available === undefined) { return reject(new Error(this._logger.warn(`Plugin will not be installed, because there are no such plugin in store`))); } if (typeof version !== 'string' || !semver.valid(version)) { version = this._store.getLatestVersion(this.getName())?.version; if (version === undefined) { return reject(new Error(this._logger.warn(`Fail to find a suitable version for plugin "${this.getName()}"`))); } } // Download plugin this._store.download(this._name, version).then((filename: string) => { this._logger.debug(`Plugin is downloaded: ${filename}`); ServiceElectronService.logStateToRender(`Unpacking package of plugin "${path.basename(this._path)}"`); this.remove().then(() => { // Unpack plugin this._unpack(filename).then(() => { ServiceElectronService.logStateToRender(`Plugin "${path.basename(this._path)}" has been unpacked`); this._logger.debug(`Plugin is unpacked`); // Read plugin info once again this.read().then(() => { this._logger.debug(`Plugin is successfully installed`); resolve(); }).catch((readErr: Error) => { reject(new Error(this._logger.warn(`Fail to install plugin due error: ${readErr.message}`))); }); }).catch((unpackErr: Error) => { reject(new Error(this._logger.warn(`Fail to unpack plugin due error: ${unpackErr.message}`))); }); }).catch((cleanErr: Error) => { reject(new Error(this._logger.warn(`Fail to clean plugin folder due error: ${cleanErr.message}`))); }); }).catch((downloadErr: Error) => { reject(new Error(`Fail to download plugin due error: ${downloadErr.message}`)); }); }); } public import(tgz: string): Promise<void> { return new Promise((resolve, reject) => { FS.exist(tgz).then((exist: boolean) => { if (!exist) { return reject(new Error(`File "${tgz}" doesn't exist.`)); } const dest: string = path.resolve(ServicePaths.getTmp(), Tools.guid()); FS.mkdir(dest).then(() => { this._unpack(tgz, false, dest).then((cwd: string) => { FS.readFolder(dest, FS.EReadingFolderTarget.folders).then((folders: string[]) => { if (folders.length !== 1) { return reject(new Error(this._logger.warn(`Expecting only one compressed folder, but found in "${tgz}":\n\t-${folders.join('\n\t-\t')}`))); } this._name = folders[0]; this._path = path.resolve(dest, folders[0]); this._logger.debug(`Plugin "${folders[0]}" is unpacked into: ${dest}`); resolve(); }).catch((fldReadErr: Error) => { reject(new Error(this._logger.warn(`Fail to read dest folder "${dest}" due error: ${fldReadErr.message}`))); }); }).catch((unpackErr: Error) => { reject(new Error(this._logger.warn(`Fail to unpack plugin due error: ${unpackErr.message}`))); }); }).catch((mkdirErr: Error) => { reject(new Error(this._logger.warn(`Fail to create temp-folder due error: ${mkdirErr.message}`))); }); }).catch((existErr: Error) => { reject(new Error(this._logger.warn(`Fail to find file "${tgz}" due error: ${existErr.message}`))); }); }); } public delivery(): Promise<void> { return new Promise((resolve, reject) => { const dest: string = path.resolve(ServicePaths.getPlugins(), this._name); ncp(this._path, dest, (err: Error[] | null) => { if (err !== null) { return reject(new Error(this._logger.warn(`Fail delivery plugin from "${this._path}" to "${dest}":\n\t- ${err.map(e => e.message).join('\n\t- ')}`))); } const tmp: string = path.resolve(this._path, '..'); FS.rmdir(tmp).catch((rmErr: Error) => { this._logger.warn(`Fail remove tmp plugin folder ${tmp} due error: ${rmErr.message}`); }).finally(() => { this._path = path.resolve(ServicePaths.getPlugins(), this._name); resolve(); }); }); }); } public getSuitableUpdates(): CommonInterfaces.Plugins.IHistory[] | Error { if (this._info === undefined) { return new Error(`Fail to check plugin, because it isn't loaded`); } const version: string = this._info.version; return this._store.getSuitableVersions(this.getName()).filter((record: CommonInterfaces.Plugins.IHistory) => { if (!semver.valid(record.version)) { this._logger.warn(`History of plugin "${this.getName()}" has wrong record: ${JSON.stringify(record)}. Version isn't valid`); return false; } /* compare(v1, v2): Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if v2 is greater. */ return semver.compare(record.version, version) === 1; }); } public isSingleProcess(): boolean { if (this._info === undefined) { return false; } if (this._controllers.process === undefined) { return false; } return this._controllers.process.isSingleProcess(); } public runAsSingle(): Promise<void> | Error { if (this._info === undefined) { return new Error(`Plugin isn't inited`); } if (this._controllers.process === undefined) { return new Error(`Plugin doesn't have process part`); } if (!this._controllers.process.isSingleProcess()) { return new Error(`Plugin isn't single process`); } return this._controllers.process.runAsSingle(); } public bindWithSession(session: string, connectionFactory: TConnectionFactory): Promise<Error | undefined> { return new Promise((resolve, reject) => { if (this._info === undefined) { return resolve(new Error(`Plugin isn't inited`)); } if (this._controllers.process === undefined) { return resolve(new Error(`Plugin doesn't have process part`)); } if (this._controllers.process.isSingleProcess()) { this._controllers.process.bindSinglePlugin(session, connectionFactory).then(() => { resolve(undefined); }).catch(reject); } else if (this._controllers.process.isMultipleProcess()) { this._controllers.process.bindMultiplePlugin(session, connectionFactory).then(() => { resolve(undefined); }).catch(reject); } }); } public unbindWithSession(session: string): Promise<void> { return new Promise((resolve, reject) => { if (this._info === undefined) { return reject(new Error(`Plugin isn't inited`)); } if (this._controllers.process === undefined) { return reject(new Error(`Plugin doesn't have process part`)); } if (this._controllers.process.isSingleProcess()) { this._controllers.process.unbindSingle(session).then(resolve).catch(reject); } else if (this._controllers.process.isMultipleProcess()) { this._controllers.process.unbindMuliple(session).then(resolve).catch(reject); } }); } private _verify() { if (this._info === undefined) { return; } if (typeof this._info.display_name !== 'string' || this._info.display_name.trim() === '' || this._info.display_name === this._info.name) { let displayName: string | undefined; if (this._packages.process !== undefined && this._packages.process.getDisplayName() !== undefined) { displayName = this._packages.process.getDisplayName(); } if (displayName === undefined && this._packages.render !== undefined && this._packages.render.getDisplayName() !== undefined) { displayName = this._packages.render.getDisplayName(); } if (displayName !== undefined) { this._info.display_name = displayName; } } } private _logPluginState() { let msg = `Plugin state:\n`; if (this._info === undefined) { msg += `\tNOT READY`; } else { msg += `\tpackage render:\t\t${this._packages.render !== undefined ? 'OK' : '-'}\n\tpackage process:\t${this._packages.process !== undefined ? 'OK' : '-'}\n`; msg += `\tcontroller render:\t${this._controllers.render !== undefined ? 'OK' : '-'}\n\tcontroller process:\t${this._controllers.process !== undefined ? 'OK' : '-'}`; } this._logger.env(msg); } private _unpack(tgzfile: string, removetgz: boolean = true, cwd?: string): Promise<string> { return new Promise((resolve, reject) => { const _cwd = cwd === undefined ? ServicePaths.getPlugins() : cwd; this._logger.debug(`Unpacking ${tgzfile} from ${_cwd}`); tar.x({ file: tgzfile, cwd: cwd === undefined ? ServicePaths.getPlugins() : cwd, }).then(() => { this._logger.debug(`Unpacking of ${tgzfile} is done.`); const included: boolean = ServicePaths.getIncludedPlugins().indexOf(path.dirname(tgzfile)) === 0; if (!removetgz || included) { if (included) { this._logger.debug(`Source of plugin ${tgzfile} wouldn't be removed as soon as it's included plugin.`); } resolve(_cwd); } else { FS.unlink(tgzfile).catch((removeErr: Error) => { this._logger.warn(`Fail to remove ${tgzfile} due error: ${removeErr.message}`); }).finally(() => { resolve(_cwd); }); } }).catch((err: Error) => { reject(new Error(this._logger.error(`Fail unpack ${tgzfile} from ${_cwd} due error: ${err.message}`))); }); }); } private _readPackages(): Promise<void> { return new Promise((resolve, reject) => { if (this._info === undefined) { return reject(new Error(`Basic info hadn't been read`)); } const render = new ControllerPluginPackage(path.resolve(this._path, CPluginsFolders.render), this._name); const process = new ControllerPluginPackage(path.resolve(this._path, CPluginsFolders.process), this._name); Promise.all([ render.read().then(() => { this._packages.render = render; }).catch(() => { return Promise.resolve(); }), process.read().then(() => { this._packages.process = process; }).catch(() => { return Promise.resolve(); }), ]).catch((error: Error) => { this._logger.debug(`Error reading package.json: ${error.message}`); }).finally(() => { resolve(); }); }); } private _addControllers(): Promise<void> { return new Promise((resolve, reject) => { if (this._info === undefined) { return reject(new Error(`Basic info hadn't been read`)); } if (this._packages.process === undefined && this._packages.render === undefined) { return reject(new Error(`Packages hadn't been read`)); } const tasks = []; if (this._packages.render !== undefined) { const render = new ControllerPluginRender(this._name, this._packages.render); tasks.push(render.init().then(() => { this._controllers.render = render; }).catch((error: Error) => { this._logger.warn(`Fail to init render controller due error: ${error.message}`); if (this._info === undefined) { return; } this._controllers.render = undefined; })); } if (this._packages.process !== undefined) { const process = new ControllerPluginProcess(this._name, this._token, this._id, this._packages.process); tasks.push(process.init().then(() => { this._controllers.process = process; }).catch((error: Error) => { this._logger.warn(`Fail to init process controller due error: ${error.message}`); if (this._info === undefined) { return; } this._controllers.process = undefined; })); } Promise.all(tasks).then(() => { resolve(); }).catch((initErr: Error) => { reject(initErr); }); }); } private _ipc_PluginsLogsRequest(request: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) { const msg: IPCMessages.PluginsLogsRequest = request as IPCMessages.PluginsLogsRequest; if (msg.name !== this._name) { return; } response(new IPCMessages.PluginsLogsResponse({ logs: LogsService.getStored(this._token), })).catch((error: Error) => { this._logger.warn(`Fail delivery log for plugin due error: ${error.message}`); }); } }
the_stack
import _ from "lodash"; import Stream from "mithril/stream"; import { ConfigJSON, GroupJSON, HistoryJSON, MaterialRevisionJSON, ModificationJSON, PipelineActivityJSON, StageConfigJSON, StageJSON } from "models/pipeline_activity/pipeline_activity_json"; const TimeFormatter = require("helpers/time_formatter"); function toBool(str: string | boolean) { if (typeof str === "undefined") { return false; } if (typeof str === "boolean") { return str; } return str.trim().toLowerCase() === "true"; } export class StageConfig { name: Stream<string>; isAutoApproved: Stream<boolean>; constructor(name: string, isAutoApproved: boolean) { this.name = Stream(name); this.isAutoApproved = Stream(isAutoApproved); } static fromJSON(stage: StageConfigJSON) { return new StageConfig(stage.name, toBool(stage.isAutoApproved)); } } export class StageConfigs extends Array<StageConfig> { constructor(...stageConfigs: StageConfig[]) { super(...stageConfigs); Object.setPrototypeOf(this, Object.create(StageConfigs.prototype)); } static fromJSON(stages: StageConfigJSON[]) { return new StageConfigs(...stages.map(StageConfig.fromJSON)); } isAutoApproved(name: string): boolean { return this.find((stage: StageConfig) => stage.name() === name)!.isAutoApproved(); } } export class Config { stages: Stream<StageConfigs>; constructor(stages: StageConfigs) { this.stages = Stream(stages); } static fromJSON(config: ConfigJSON) { return new Config(StageConfigs.fromJSON(config.stages)); } } export class Modification { user: Stream<string>; revision: Stream<string>; date: Stream<string>; comment: Stream<string>; modifiedFiles: Stream<string[]>; constructor(user: string, revision: string, date: string, comment: string, modifiedFiles: string[]) { this.user = Stream(user); this.revision = Stream(revision); this.date = Stream(date); this.comment = Stream(comment); this.modifiedFiles = Stream(modifiedFiles); } static fromJSON(modification: ModificationJSON) { return new Modification(modification.user, modification.revision, modification.date, modification.comment, modification.modifiedFiles); } } class Modifications extends Array<Modification> { constructor(...modifications: Modification[]) { super(...modifications); Object.setPrototypeOf(this, Object.create(Modifications.prototype)); } static fromJSON(modifications: ModificationJSON[]) { return new Modifications(...modifications.map(Modification.fromJSON)); } } export class MaterialRevision { revision: Stream<string>; revisionHref: Stream<string>; user: Stream<string>; date: Stream<string>; changed: Stream<boolean>; modifications: Stream<Modifications>; folder: Stream<string>; scmType: Stream<string>; location: Stream<string>; action: Stream<string>; constructor(revision: string, revision_href: string, user: string, date: string, changed: boolean, modifications: Modifications, folder: string, scmType: string, location: string, action: string) { this.revision = Stream(revision); this.revisionHref = Stream(revision_href); this.user = Stream(user); this.date = Stream(date); this.changed = Stream(changed); this.modifications = Stream(modifications); this.folder = Stream(folder); this.scmType = Stream(scmType); this.location = Stream(location); this.action = Stream(action); } static fromJSON(materialRevision: MaterialRevisionJSON) { return new MaterialRevision(materialRevision.revision, materialRevision.revision_href, materialRevision.user, materialRevision.date, toBool(materialRevision.changed), Modifications.fromJSON(materialRevision.modifications), materialRevision.folder, materialRevision.scmType, materialRevision.location, materialRevision.action); } } class MaterialRevisions extends Array<MaterialRevision> { constructor(...materialRevisions: MaterialRevision[]) { super(...materialRevisions); Object.setPrototypeOf(this, Object.create(MaterialRevisions.prototype)); } static fromJSON(materialRevisions: MaterialRevisionJSON[]) { return new MaterialRevisions(...materialRevisions.map(MaterialRevision.fromJSON)); } } export class Stage { stageName: Stream<string>; stageId: Stream<number>; stageStatus: Stream<string>; stageLocator: Stream<string>; getCanRun: Stream<boolean>; getCanCancel: Stream<boolean>; scheduled: Stream<boolean>; stageCounter: Stream<number>; approvedBy: Stream<string | undefined>; errorMessage: Stream<string | undefined>; constructor(stageName: string, stageId: number, stageStatus: string, stageLocator: string, getCanRun: boolean, getCanCancel: boolean, scheduled: boolean, stageCounter: number, approvedBy?: string, errorMessage?: string) { this.stageName = Stream(stageName); this.stageId = Stream(stageId); this.stageStatus = Stream(stageStatus); this.stageLocator = Stream(stageLocator); this.getCanRun = Stream(getCanRun); this.getCanCancel = Stream(getCanCancel); this.scheduled = Stream(scheduled); this.stageCounter = Stream(stageCounter); this.approvedBy = Stream(approvedBy); this.errorMessage = Stream(errorMessage); } static fromJSON(stage: StageJSON) { return new Stage(stage.stageName, stage.stageId, stage.stageStatus, stage.stageLocator, toBool(stage.getCanRun), toBool(stage.getCanCancel), toBool(stage.scheduled), stage.stageCounter, stage.approvedBy, stage.errorMessage); } pipelineName() { return this.stageLocator().split("/")[0]; } pipelineCounter() { return this.stageLocator().split("/")[1]; } isBuilding(): boolean { return this.stageStatus() === "Building"; } } export class Stages extends Array<Stage> { constructor(...stages: Stage[]) { super(...stages); Object.setPrototypeOf(this, Object.create(Stages.prototype)); } static fromJSON(stages: StageJSON[]) { return new Stages(...stages.map(Stage.fromJSON)); } } export class PipelineRunInfo { pipelineId: Stream<number>; label: Stream<string>; counterOrLabel: Stream<string>; scheduledDate: Stream<string>; scheduledTimestamp: Stream<Date>; buildCauseBy: Stream<string>; modificationDate: Stream<string>; materialRevisions: Stream<MaterialRevisions>; stages: Stream<Stages>; revision: Stream<string>; comment: Stream<string>; constructor(pipelineId: number, label: string, counterOrLabel: string, scheduled_date: string, scheduled_timestamp: Date, buildCauseBy: string, modification_date: string, materialRevisions: MaterialRevisions, stages: Stages, revision: string, comment: string | null) { this.pipelineId = Stream(pipelineId); this.label = Stream(label); this.counterOrLabel = Stream(counterOrLabel); this.scheduledDate = Stream(scheduled_date); this.scheduledTimestamp = Stream(scheduled_timestamp); this.buildCauseBy = Stream(buildCauseBy); this.modificationDate = Stream(modification_date); this.materialRevisions = Stream(materialRevisions); this.stages = Stream(stages); this.revision = Stream(revision); this.comment = Stream(comment ? comment : ""); } static fromJSON(pipelineRunInfo: HistoryJSON) { return new PipelineRunInfo(pipelineRunInfo.pipelineId, pipelineRunInfo.label, pipelineRunInfo.counterOrLabel, pipelineRunInfo.scheduled_date, parseDate(pipelineRunInfo.scheduled_timestamp), pipelineRunInfo.buildCauseBy, pipelineRunInfo.modification_date, MaterialRevisions.fromJSON(pipelineRunInfo.materialRevisions), Stages.fromJSON(pipelineRunInfo.stages), pipelineRunInfo.revision, pipelineRunInfo.comment); } } class PipelineHistory extends Array<PipelineRunInfo> { constructor(...pipelineRunInfos: PipelineRunInfo[]) { super(...pipelineRunInfos); Object.setPrototypeOf(this, Object.create(PipelineHistory.prototype)); } static fromJSON(history: HistoryJSON[]) { return new PipelineHistory(...history.map(PipelineRunInfo.fromJSON)); } } export class Group { config: Stream<Config>; history: Stream<PipelineHistory>; constructor(config: Config, history: PipelineHistory) { this.config = Stream(config); this.history = Stream(history); } static fromJSON(group: GroupJSON): Group { return new Group(Config.fromJSON(group.config), PipelineHistory.fromJSON(group.history)); } } class Groups extends Array<Group> { constructor(...groups: Group[]) { super(...groups); Object.setPrototypeOf(this, Object.create(Groups.prototype)); } static fromJSON(groups: GroupJSON[]) { return new Groups(...groups.map(Group.fromJSON)); } } export class PipelineActivity { pipelineName: Stream<string>; paused: Stream<boolean>; pauseCause: Stream<string>; pauseBy: Stream<string>; canForce: Stream<boolean>; nextLabel: Stream<string>; groups: Stream<Groups>; forcedBuild: Stream<boolean>; showForceBuildButton: Stream<boolean>; canPause: Stream<boolean>; count: Stream<number>; start: Stream<number>; perPage: Stream<number>; constructor(pipelineName: string, nextLabel: string, canPause: boolean, paused: boolean, pauseCause: string, pauseBy: string, canForce: boolean, forcedBuild: boolean, showForceBuildButton: boolean, count: number, start: number, perPage: number, groups: Groups) { this.pipelineName = Stream(pipelineName); this.paused = Stream(paused); this.pauseCause = Stream(pauseCause); this.pauseBy = Stream(pauseBy); this.canForce = Stream(canForce); this.nextLabel = Stream(nextLabel); this.groups = Stream(groups); this.forcedBuild = Stream(forcedBuild); this.showForceBuildButton = Stream(showForceBuildButton); this.canPause = Stream(canPause); this.count = Stream(count); this.start = Stream(start); this.perPage = Stream(perPage); } static fromJSON(data: PipelineActivityJSON) { return new PipelineActivity(data.pipelineName, data.nextLabel, toBool(data.canPause), toBool(data.paused), data.pauseCause, data.pauseBy, toBool(data.canForce), toBool(data.forcedBuild), toBool(data.showForceBuildButton), data.count, data.start, data.perPage, Groups.fromJSON(data.groups)); } } function parseDate(dateAsStringOrNumber: string | number | null) { if (!dateAsStringOrNumber) { return undefined; } if (_.isNumber(dateAsStringOrNumber)) { return new Date(dateAsStringOrNumber); } return TimeFormatter.toDate(dateAsStringOrNumber); }
the_stack
import { compactDecrypt } from '@inrupt/jose-legacy-modules'; import { ClientReadableStream } from 'grpc-web'; import * as pako from 'pako'; import { Observable, of, from } from 'rxjs'; import { bufferTime, catchError, concatMap, finalize, mergeMap, map, timeout, startWith, } from 'rxjs/operators'; import { ErrorDetails, ExecuteScriptRequest, HealthCheckRequest, QueryExecutionStats, Relation, RowBatchData, Status, MutationInfo, HealthCheckResponse, ExecuteScriptResponse, } from 'app/types/generated/vizierapi_pb'; import { VizierServiceClient } from 'app/types/generated/VizierapiServiceClientPb'; import { GRPCStatusCode, VizierQueryError } from './vizier'; import { VizierTable } from './vizier-table'; const noop = () => {}; declare global { interface Window { __GRPCWEB_DEVTOOLS__: (any) => void; } } function withDevTools(client) { // eslint-disable-next-line no-underscore-dangle const enableDevTools = globalThis.__GRPCWEB_DEVTOOLS__ || noop; enableDevTools([client]); } export interface ExecuteScriptOptions { enableE2EEncryption: boolean; } export interface VizierQueryResult { queryId?: string; tables: VizierTable[]; status?: Status; executionStats?: QueryExecutionStats; mutationInfo?: MutationInfo; schemaOnly?: boolean; // Whether the result only has the schema loaded so far. } export interface VizierQueryArg { name: string; value?: string; variable?: string; } export interface VizierQueryFunc { name: string; outputTablePrefix: string; args: VizierQueryArg[]; } export interface BatchDataUpdate { id: string; name: string; relation: Relation; batch: RowBatchData; } interface ExecutionStartEvent { type: 'start'; } interface ExecutionErrorEvent { type: 'error'; error: VizierQueryError; } interface ExecutionMetadataEvent { type: 'metadata'; table: VizierTable; } interface ExecutionMutationInfoEvent { type: 'mutation-info'; mutationInfo: MutationInfo; } interface ExecutionDataEvent { type: 'data'; data: BatchDataUpdate[]; } interface ExecutionCancelEvent { type: 'cancel'; } interface ExecutionStatusEvent { type: 'status'; status: Status; } interface ExecutionStatsEvent { type: 'stats'; stats: QueryExecutionStats; } export type ExecutionEvent = ExecutionStartEvent | ExecutionErrorEvent | ExecutionMetadataEvent | ExecutionMutationInfoEvent | ExecutionDataEvent | ExecutionCancelEvent | ExecutionStatusEvent | ExecutionStatsEvent; /** The latest state of an executeScript, streamed from an observable */ export interface ExecutionStateUpdate { /** The event that generated this state update */ event: ExecutionEvent; /** If `completionReason` is not set, this result can be partial */ results: VizierQueryResult; /** If set, cancels the execution. Gets unset when the query completes for any reason (including error or cancel). */ cancel?: () => void; /** If set, execution has halted for this reason */ completionReason?: 'complete' | 'cancelled' | 'error'; } function getExecutionErrors(errList: ErrorDetails[]): string[] { return errList.map((error) => { switch (error.getErrorCase()) { case ErrorDetails.ErrorCase.COMPILER_ERROR: { const ce = error.getCompilerError(); return `Compiler error on line ${ce.getLine()}, column ${ce.getColumn()}: ${ce.getMessage()}.`; } default: return `Unknown error type ${ErrorDetails.ErrorCase[error.getErrorCase()]}.`; } }); } function addFuncsToRequest(req: ExecuteScriptRequest, funcs: VizierQueryFunc[]): VizierQueryError { for (const input of funcs) { const execFuncPb = new ExecuteScriptRequest.FuncToExecute(); execFuncPb.setFuncName(input.name); execFuncPb.setOutputTablePrefix(input.outputTablePrefix); for (const arg of input.args) { const argValPb = new ExecuteScriptRequest.FuncToExecute.ArgValue(); argValPb.setName(arg.name); if (typeof arg.value === 'undefined') { return new VizierQueryError('vis', `No value provided for arg ${arg.name}.`); } if (typeof arg.value !== 'string') { return new VizierQueryError('vis', 'All args must be strings.' + ` Received '${typeof arg.value}' for arg '${arg.name}'.`); } argValPb.setValue(arg.value); execFuncPb.addArgValues(argValPb); } req.addExecFuncs(execFuncPb); } return null; } type KeyPair = { publicKeyJWK: JsonWebKey, privateKey: CryptoKey, }; async function parseKeyPair(data: string): Promise<KeyPair> { const parsed: { privateKeyJWK: JsonWebKey, publicKeyJWK: JsonWebKey } = JSON.parse(data); const privateKey = await window.crypto.subtle.importKey( 'jwk', parsed.privateKeyJWK, { name: 'RSA-OAEP', hash: 'SHA-256' }, true, // Only set decrypt as option because this is the private key. ['decrypt'], ); return { publicKeyJWK: parsed.publicKeyJWK, privateKey }; } async function serializeKeyPair(pair: KeyPair): Promise<string> { const privateKeyJWK = await window.crypto.subtle.exportKey('jwk', pair.privateKey); return JSON.stringify({ privateKeyJWK, publicKeyJWK: pair.publicKeyJWK }); } async function generateRSAKeyPair(): Promise<KeyPair> { const keyPair = await window.crypto.subtle.generateKey( { name: 'RSA-OAEP', modulusLength: 4096, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256', }, true, ['encrypt', 'decrypt'], ); const publicKeyJWK = await window.crypto.subtle.exportKey( 'jwk', keyPair.publicKey, ); return { publicKeyJWK, privateKey: keyPair.privateKey }; } async function getRSAKeyPair(): Promise<KeyPair> { // If key pair exists in our cache, then we parse it out. const keyPairCache = sessionStorage.getItem('pixie-e2e-encryption-key'); if (keyPairCache) { return parseKeyPair(keyPairCache); } // Generate if not found in keyparse. const keyPair = await generateRSAKeyPair(); sessionStorage.setItem('pixie-e2e-encryption-key', await serializeKeyPair(keyPair)); return keyPair; } async function decryptRSA(privateKey: CryptoKey, data: Uint8Array): Promise<Uint8Array> { const { plaintext } = await compactDecrypt(data, privateKey, { inflateRaw: (input) => Promise.resolve(pako.inflateRaw(input)), }); return plaintext; } const HEALTH_CHECK_TIMEOUT = 10000; // 10 seconds type ExecuteScriptResponseOrError = { resp?: ExecuteScriptResponse, error?: VizierQueryError, }; /** * Client for gRPC connections to individual Vizier clusters. * See CloudGQLClient for the GraphQL client that works with shared data. * Should not be used directly - PixieAPIClient exposes wrappers around both this and CloudGQLClient, * which smooth out bumps in things like error handling. Prefer using that if you can. */ export class VizierGRPCClient { private readonly client: VizierServiceClient; private readonly rsaKeyPromise: Promise<KeyPair>; constructor( addr: string, private token: string, readonly clusterID: string, private attachCreds: boolean, ) { this.client = new VizierServiceClient(addr, null, attachCreds ? { withCredentials: 'true' } : {}); // Generate once per client and cache it to avoid the expense of regenrating on every // request. The key pair will rotate on browser reload or on creation of a new client. this.rsaKeyPromise = getRSAKeyPair(); withDevTools(this.client); } /** * Monitors the health of both Pixie instrumentation on a cluster, and this client's connection to it. * The returned Observable watches */ health(): Observable<Status> { const headers = { ...(this.attachCreds ? {} : { Authorization: `bearer ${this.token}` }), }; const req = new HealthCheckRequest(); req.setClusterId(this.clusterID); const call = this.client.healthCheck(req, headers); return new Observable<HealthCheckResponse>((observer) => { call.on('data', observer.next.bind(observer)); call.on('error', observer.error.bind(observer)); call.on('end', observer.complete.bind(observer)); }).pipe( map((resp: HealthCheckResponse) => resp.getStatus()), finalize((() => { call.cancel(); })), timeout(HEALTH_CHECK_TIMEOUT), ); } // Use a generator to produce the VizierQueryFunc to remove the dependency on vis.tsx. // funcsGenerator should correspond to getQueryFuncs in vis.tsx. executeScript( script: string, funcs: VizierQueryFunc[], mutation: boolean, opts: ExecuteScriptOptions, ): Observable<ExecutionStateUpdate> { let call: ClientReadableStream<unknown>; const cancelCall = () => { if (call?.cancel) { call.cancel(); } }; let keyPair: KeyPair; const tablesMap = new Map<string, VizierTable>(); const results: VizierQueryResult = { tables: [] }; const rsaKeyPromise: Promise<KeyPair> = opts.enableE2EEncryption ? this.rsaKeyPromise : Promise.resolve(null); return from( rsaKeyPromise, ).pipe( mergeMap((kp: KeyPair) => { keyPair = kp; const headers = { ...(this.attachCreds ? {} : { Authorization: `bearer ${this.token}` }), }; const req = new ExecuteScriptRequest(); req.setClusterId(this.clusterID); req.setQueryStr(script); req.setMutation(mutation); if (keyPair) { const encOpts = new ExecuteScriptRequest.EncryptionOptions(); encOpts.setJwkKey(JSON.stringify(keyPair.publicKeyJWK)); encOpts.setKeyAlg('RSA-OAEP-256'); encOpts.setContentAlg('A256GCM'); encOpts.setCompressionAlg('DEF'); req.setEncryptionOptions(encOpts); } const err = addFuncsToRequest(req, funcs); if (err) { throw err; } call = this.client.executeScript(req, headers); return new Observable<ExecuteScriptResponseOrError>((observer) => { call.on('data', (data: ExecuteScriptResponse) => { observer.next({ resp: data }); }); call.on('error', (grpcError) => { let error: VizierQueryError; if (grpcError.code === GRPCStatusCode.Unavailable) { error = new VizierQueryError('unavailable', grpcError.message); } else { error = new VizierQueryError('server', grpcError.message); } // Delay throwing of errors until after the buffering step. observer.next({ error }); }); call.on('end', observer.complete.bind(observer)); }); }), finalize(cancelCall), concatMap((respOrErr: ExecuteScriptResponseOrError) => { const { resp, error } = respOrErr; if (error) { return of(respOrErr); } if (!keyPair || !resp.hasData()) { return of(respOrErr); } if (!resp.getData().getEncryptedBatch()) { if (resp.getData().hasBatch()) { // eslint-disable-next-line no-console console.warn('Expected table data to be encrypted. Please upgrade vizier.'); } return of(respOrErr); } const encrypted = resp.getData().getEncryptedBatch_asU8(); return from(decryptRSA(keyPair.privateKey, encrypted)).pipe( map((dec: Uint8Array) => { resp.getData().setBatch(RowBatchData.deserializeBinary(dec)); resp.getData().setEncryptedBatch(''); return { resp }; }), ); }), bufferTime(250), concatMap((buffer: ExecuteScriptResponseOrError[]) => { const outs: ExecutionStateUpdate[] = []; const dataBatch: BatchDataUpdate[] = []; let errored = false; for (const respOrErr of buffer) { const { resp, error } = respOrErr; if (error) { errored = true; outs.push({ event: { type: 'error', error }, completionReason: 'error', results }); break; } if (!results.queryId) { results.queryId = resp.getQueryId(); } if (resp.hasStatus()) { const status = resp.getStatus(); const errList = status.getErrorDetailsList(); if (errList.length > 0) { throw new VizierQueryError('execution', getExecutionErrors(errList), status); } const errMsg = status.getMessage(); if (errMsg) { throw new VizierQueryError('execution', errMsg, status); } results.status = status; outs.push({ event: { type: 'status', status }, results }); } if (resp.hasMetaData()) { const id = resp.getMetaData().getId(); const name = resp.getMetaData().getName(); const relation = resp.getMetaData().getRelation(); tablesMap.set(id, new VizierTable(id, name, relation)); const table = tablesMap.get(id); results.tables.push(table); results.schemaOnly = true; outs.push({ event: { type: 'metadata', table }, results }); } else if (resp.hasMutationInfo()) { results.mutationInfo = resp.getMutationInfo(); outs.push({ event: { type: 'mutation-info', mutationInfo: results.mutationInfo }, results }); } else if (resp.hasData()) { const data = resp.getData(); if (data.hasBatch()) { results.schemaOnly = false; const batch = data.getBatch(); const id = batch.getTableId(); const table = tablesMap.get(id); const { name, relation } = table; table.appendBatch(batch); dataBatch.push({ id, name, relation, batch, }); } else if (data.hasExecutionStats()) { // The query finished executing, and all the data has been received. results.executionStats = data.getExecutionStats(); outs.push({ event: { type: 'stats', stats: results.executionStats }, completionReason: 'complete', results, }); } } } if (!errored) { outs.push({ event: { type: 'data', data: dataBatch }, results }); } return outs; }), startWith({ event: { type: 'start' as const }, results, cancel: cancelCall, }), catchError((error) => { cancelCall(); return of({ event: { type: 'error' as const, error }, completionReason: 'error' as const, results, }); }), finalize(cancelCall), ); } }
the_stack
export declare abstract class SyntheticFile { /** * * @param name the file name * @param size the file size * @param type the file type * @returns */ static createFile: (name: string, size: number, type: string) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_aac: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_abw: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_freearc: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_avi: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_azw: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_octet: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_bmp: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_bz: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_bz2: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_cda: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_csh: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_css: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_csv: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_doc: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_docx: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_eot: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_epub: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_gzip: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_gif: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_htm: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_html: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_ico: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_icalendar: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_jar: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_jpeg: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_jpg: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_js: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_json: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_jsonld: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_mid: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_x_mid: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_midi: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_x_midi: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_mjs: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_mp3: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_mp4: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_mpeg: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_mpkg: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_odp: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_ods: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_odt: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_oga: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_ogv: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_ogx: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_opus: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_otf: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_png: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_pdf: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_php: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_ppt: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_pptx: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_rar: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_rtf: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_sh: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_svg: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_swf: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_tar: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_tif: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_tiff: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_ts: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_ttf: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_text: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_typescript: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_vsd: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_wav: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_weba: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_webm: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_webp: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_woff: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_woff2: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_xhtml: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_xlsx: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_xls: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_xml: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_xml_txt: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_xul: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_zip: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_3gp: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_3gp2: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_3gp_a: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_3gp_v: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_7z: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_python: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_java: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_react: (size?: number) => File; /** * * @param size the file size * @returns a syntetic File object instance */ static create_vue: (size?: number) => File; /** * Creates an array of fake (synthetic) files * @param size the file size for all synthetic files * @returns an array of all file icon preview supported files */ static createFileListMiscelanious: (size?: number) => File[]; }
the_stack
import React, {RefObject} from 'react'; import TopBar from './navbar/TopBar'; import {SettingsButton, VisualizeButton} from './navbar/Buttons'; import { AlgorithmDropDown, ClearDropDown, MazeDropDown, TilesDropDown } from './navbar/DropDowns'; import { AlgorithmSettings, HeuristicSettings, SpeedSettings, VisualSettings } from './panel/SettingPanels'; import DraggablePanel from './panel/DraggablePanel'; import PathfindingVisualizer from './grid/PathfindingVisualizer'; import PathfinderBuilder from '../pathfinding/builders/PathfinderBuilder'; import { MAZE, MAZE_HORIZONTAL_SKEW, MAZE_VERTICAL_SKEW, RANDOM_TERRAIN } from '../pathfinding/builders/TerrainGeneratorBuilder'; import Icon from '../../assets/react.png'; import AppSettings, {getDefaultSettings} from "../utils/AppSettings"; import Tutorial, {KEY_SHOW} from './tutorial/Tutorial'; import {getTutorialPages} from './tutorial/TutorialPages'; interface IProps {} interface IState { settings: AppSettings, heuristicDisabled: boolean, bidirectionalDisabled: boolean, arrowsDisabled: boolean, scoreDisabled: boolean panelShow: boolean, visualizing: boolean, paused: boolean, useIcon: boolean } class PathfindingApp extends React.Component<IProps, IState> { //expose grid to parent to connect to button siblings private visualizer: RefObject<PathfindingVisualizer> = React.createRef(); //drop down refs needed to invoke behavior between dropdowns private algDropDown: RefObject<AlgorithmDropDown> = React.createRef(); private clrDropDown: RefObject<ClearDropDown> = React.createRef(); private mazeDropDown: RefObject<MazeDropDown> = React.createRef(); private tilesDropDown: RefObject<TilesDropDown> = React.createRef(); private readonly tileWidth: number; constructor(props: IProps) { super(props); this.state = { settings: getDefaultSettings(), heuristicDisabled: false, bidirectionalDisabled: false, arrowsDisabled: false, scoreDisabled: false, panelShow: false, visualizing: false, paused: false, useIcon: this.useIcon() } const mobile = isMobile(); this.tileWidth = mobile ? 47 : Math.round(window.screen.availWidth / 57); } windowOnResize = () => { this.setState({ useIcon: this.useIcon() }); } /** * Binds window listeners. * Listener is to keep track of screen size to check if we show icon */ componentDidMount() { window.addEventListener('resize', this.windowOnResize); } componentWillUnmount() { window.removeEventListener('resize', this.windowOnResize); } useIcon() { return window.innerWidth <= 850; } /** * Called when the drop downs are clicked to prevent more * than one dropdown from being open at a time */ onClickAlgDrop() { this.clrDropDown.current!.hide(); this.mazeDropDown.current!.hide(); this.tilesDropDown.current!.hide(); } onClickClrDrop() { this.algDropDown.current!.hide(); this.mazeDropDown.current!.hide(); this.tilesDropDown.current!.hide(); } onClickMazeDrop() { this.clrDropDown.current!.hide(); this.algDropDown.current!.hide(); this.tilesDropDown.current!.hide(); } onClickTilesDrop() { this.clrDropDown.current!.hide(); this.algDropDown.current!.hide(); this.mazeDropDown.current!.hide(); } /** * Utility functions to change overall state of application * Settings, overall appearance, etc */ changeButtonActiveState(visualizing: boolean) { this.setState({ visualizing: visualizing }) } toggleSettings() { this.setState(prevState => ({ panelShow: !prevState.panelShow })); } hideSettings() { this.setState({ panelShow: false }); } doPathfinding() { this.setState({ paused: false }); this.visualizer.current!.doDelayedPathfinding(); } pausePathfinding() { this.setState({ paused: true }); this.visualizer.current!.pausePathfinding(); } resumePathfinding() { this.setState({ paused: false }); this.visualizer.current!.resumePathfinding(); } clearPath() { this.visualizer.current!.clearPath(); this.visualizer.current!.clearVisualizationChecked(); } clearTiles() { this.clearPath(); this.visualizer.current!.clearTilesChecked(); } resetBoard() { this.clearPath(); this.clearTiles(); this.visualizer.current!.resetPoints(); } createMaze() { this.visualizer.current!.createTerrain(MAZE, false); } createMazeVSkew() { this.visualizer.current!.createTerrain(MAZE_VERTICAL_SKEW, false); } createMazeHSkew() { this.visualizer.current!.createTerrain(MAZE_HORIZONTAL_SKEW, false); } createRandomTerrain() { this.visualizer.current!.createTerrain(RANDOM_TERRAIN, true); } changeTile(cost: number) { this.visualizer.current!.changeTile({ isSolid: cost === -1, pathCost: cost }); } /** * Functions to modify app's settings */ changeAlgo(algorithm: string) { this.setState(prevState => ({ heuristicDisabled: !PathfinderBuilder.usesHeuristic(algorithm), bidirectionalDisabled: !PathfinderBuilder.hasBidirectional(algorithm), scoreDisabled: !PathfinderBuilder.usesWeights(algorithm), settings: { ...prevState.settings, algorithm: algorithm } })); } changeShowArrows() { this.setState(prevState => ({ settings: { ...prevState.settings, showArrows: !prevState.settings.showArrows } })); } changeBidirectional() { this.setState(prevState => ({ settings: { ...prevState.settings, bidirectional: !prevState.settings.bidirectional } })); } changeSpeed(value: number) { this.setState(prevState => ({ settings: { ...prevState.settings, delayInc: value } })); } changeManhattan() { this.setState(prevState => ({ settings: { ...prevState.settings, heuristicKey: 'manhattan' } })); } changeEuclidean() { this.setState(prevState => ({ settings: { ...prevState.settings, heuristicKey: 'euclidean' } })); } changeChebyshev() { this.setState(prevState => ({ settings: { ...prevState.settings, heuristicKey: 'chebyshev' } })); } changeOctile() { this.setState(prevState => ({ settings: { ...prevState.settings, heuristicKey: 'octile' } })); } showTutorial() { localStorage.setItem(KEY_SHOW, 'false'); } render() { const title: string = 'Pathfinding Visualizer'; const icon = this.state.useIcon ? <img width={'100%'} height={'100%'} className='icon' alt={title} src={Icon} /> : title; return ( <div> <Tutorial> {getTutorialPages()} </Tutorial> <DraggablePanel title='Grid Settings' show={this.state.panelShow} onClickXButton={() => this.hideSettings()} width={350} height={405} > <VisualSettings defaultShowArrows={this.state.settings.showArrows} disabledTree={this.state.arrowsDisabled} disabledScore={this.state.scoreDisabled} onChangeShowArrows={() => this.changeShowArrows()} /> <SpeedSettings onChange={(value: number) => this.changeSpeed(value)} initialSpeed={this.state.settings.delayInc} /> <AlgorithmSettings defaultAlg={this.state.settings.bidirectional} disabled={this.state.bidirectionalDisabled} onChangeBidirectional={() => this.changeBidirectional()} /> <HeuristicSettings defaultHeuristic={this.state.settings.heuristicKey} disabled={this.state.heuristicDisabled} onClickManhattan={() => this.changeManhattan()} onClickEuclidean={() => this.changeEuclidean()} onClickChebyshev={() => this.changeChebyshev()} onClickOctile={() => this.changeOctile()} /> </DraggablePanel> <TopBar> <div className='title' tabIndex={0} style={{ width: this.state.useIcon ? 70 : 'auto', height: this.state.useIcon ? 52 : '100%' }} onClick={() => { this.showTutorial(); window.location.reload(); }} > {icon} </div> <AlgorithmDropDown ref={this.algDropDown} onClick={() => this.onClickAlgDrop()} onChange={(alg: string) => this.changeAlgo(alg)} /> <MazeDropDown ref={this.mazeDropDown} onClick={() => this.onClickMazeDrop()} onClickMaze={() => this.createMaze()} onClickMazeHorizontal={() => this.createMazeHSkew()} onClickMazeVertical={() => this.createMazeVSkew()} onClickRandomTerrain={() => this.createRandomTerrain()} /> <VisualizeButton active={this.state.visualizing} paused={this.state.paused} onPause={() => this.pausePathfinding()} onResume={() => this.resumePathfinding()} onStartStop={() => this.doPathfinding()} /> <ClearDropDown ref={this.clrDropDown} onClick={() => this.onClickClrDrop()} onClickTiles={() => this.clearTiles()} onClickPath={() => this.clearPath()} onClickReset={() => this.resetBoard()} /> <TilesDropDown ref={this.tilesDropDown} onClick={() => this.onClickTilesDrop()} onClickTileType={(cost: number) => this.changeTile(cost)} /> <SettingsButton onClick={() => this.toggleSettings()}/> </TopBar> <PathfindingVisualizer ref={this.visualizer} onChangeVisualizing={(viz: boolean) => this.changeButtonActiveState(viz)} settings={this.state.settings} tileWidth={this.tileWidth} /> </div> ); } } function isMobile() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); } export default PathfindingApp;
the_stack
import { deepStrictEqual, ok, strictEqual } from 'assert'; import { readFileSync, stat } from 'fs'; import { join } from 'path'; import { promisify } from 'util'; // 3p import { ApiInfo, Context, getHttpMethod, getPath, isHttpResponseBadRequest, isHttpResponseMovedPermanently, isHttpResponseNotFound, isHttpResponseOK, OpenApi, OPENAPI_SERVICE_ID, ServiceManager, streamToBuffer } from '@foal/core'; // FoalTS import { SwaggerController } from './swagger-controller'; describe('SwaggerController', () => { class ConcreteClass extends SwaggerController { options = { url: 'foobar' }; } /* Spec file(s) */ describe('has a "getOpenApiDefinition" method that', () => { it('should handle requests at GET /.', () => { strictEqual(getHttpMethod(ConcreteClass, 'getOpenApiDefinition'), 'GET'); strictEqual(getPath(ConcreteClass, 'getOpenApiDefinition'), '/openapi.json'); }); describe('given options is an object', () => { const ctx = new Context({}); it('should return an HttpResponseNotFound if the object interface is { url: string }', () => { class ConcreteClass extends SwaggerController { options = { url: 'foobar' }; } const controller = new ConcreteClass(); const response = controller.getOpenApiDefinition(ctx); if (!isHttpResponseNotFound(response)) { throw new Error('The response should be an instance of HttpResponseNotFound.'); } }); it('should return an HttpResponseOK with the controller document.', () => { const info = { title: 'Api', version: '1.0.0', }; @ApiInfo(info) class ApiController {} class ConcreteClass extends SwaggerController { options = { controllerClass: ApiController }; } const services = new ServiceManager(); const openApi = services.get(OpenApi); openApi.addDocument(ApiController, { info, openapi: '3.0.0', paths: {} }); services.set(OPENAPI_SERVICE_ID, openApi); const controller = services.get(ConcreteClass); const response = controller.getOpenApiDefinition(ctx); if (!isHttpResponseOK(response)) { throw new Error('The response should be an instance of HttpResponseOK.'); } deepStrictEqual(response.body, { info, openapi: '3.0.0', paths: {} }); }); }); describe('given options is an array', () => { it('should return an HttpResponseBadRequest if no param "name" is provided.', () => { class ConcreteClass extends SwaggerController { options = []; } const controller = new ConcreteClass(); const ctx = new Context({ query: {} }); const response = controller.getOpenApiDefinition(ctx); if (!isHttpResponseBadRequest(response)) { throw new Error('The response should be an instance of HttpResponseBadRequest.'); } strictEqual(response.body, 'Missing URL parameter "name".'); }); it('should return an HttpResponseNotFound if no controller is found with that name.', () => { class ConcreteClass extends SwaggerController { options = [ { name: 'v1', url: 'http://example.com' }, ]; } const controller = new ConcreteClass(); let ctx = new Context({ query: { name: 'v2' } }); let response = controller.getOpenApiDefinition(ctx); if (!isHttpResponseNotFound(response)) { throw new Error('The response should be an instance of HttpResponseNotFound.'); } ctx = new Context({ query: { name: 'v1' } }); response = controller.getOpenApiDefinition(ctx); if (!isHttpResponseNotFound(response)) { throw new Error('The response should be an instance of HttpResponseNotFound.'); } }); it('should return an HttpResponseOK with the controller document.', () => { const info = { title: 'Api', version: '1.0.0', }; @ApiInfo(info) class ApiController {} class ConcreteClass extends SwaggerController { options = [ { name: 'v1', url: 'http://example.com' }, { name: 'v2', controllerClass: ApiController }, ]; } const services = new ServiceManager(); const openApi = services.get(OpenApi); openApi.addDocument(ApiController, { info, openapi: '3.0.0', paths: {} }); services.set(OPENAPI_SERVICE_ID, openApi); const controller = services.get(ConcreteClass); const ctx = new Context({ query: { name: 'v2' } }); const response = controller.getOpenApiDefinition(ctx); if (!isHttpResponseOK(response)) { throw new Error('The response should be an instance of HttpResponseOK.'); } deepStrictEqual(response.body, { info, openapi: '3.0.0', paths: {} }); }); }); }); /* UI */ describe('has an "index" method that', () => { it('should handle requests at GET /.', () => { strictEqual(getHttpMethod(ConcreteClass, 'index'), 'GET'); strictEqual(getPath(ConcreteClass, 'index'), '/'); }); it('should redirect the user to xxx/ if there is no trailing slash in the URL.', async () => { // This way, the browser requests the assets at the correct path (the relative path). const controller = new ConcreteClass(); const ctx = new Context({ path: 'xxx' }); const response = await controller.index(ctx); if (!isHttpResponseMovedPermanently(response)) { throw new Error('SwaggerController.index should return an HttpResponseMovedPermanently instance.'); } strictEqual(response.path, ctx.request.path + '/'); }); it('should return the swagger HTML page.', async () => { const controller = new ConcreteClass(); const ctx = new Context({ path: 'swagger/' }); const response = await controller.index(ctx); if (!isHttpResponseOK(response)) { throw new Error('SwaggerController.index should return an HttpResponseOK instance.'); } strictEqual(response.getHeader('Content-Type'), 'text/html; charset=utf-8'); const expected = readFileSync(join(__dirname, 'index.html'), 'utf8'); strictEqual(response.body, expected); }) }); describe('has a "main" method that', () => { const ctx = new Context({ path: 'swagger/' }); it('should handle requests at GET /main.js.', () => { strictEqual(getHttpMethod(ConcreteClass, 'main'), 'GET'); strictEqual(getPath(ConcreteClass, 'main'), '/main.js'); }); it('should properly render the template given options are { url: "xxx" }.', async () => { class ConcreteClass extends SwaggerController { options = { url: 'xxx' }; } const controller = new ConcreteClass(); const response = await controller.main(ctx); if (!isHttpResponseOK(response)) { throw new Error('SwaggerController.main should return an HttpResponseOK instance.'); } strictEqual(response.getHeader('Content-Type'), 'application/javascript'); const expected = readFileSync(join(__dirname, 'specs/main.url.spec.js'), 'utf8'); strictEqual(response.body, expected); }); it('should properly render the template given options are AppController.', async () => { class ConcreteClass extends SwaggerController { options = { controllerClass: class {} }; } const controller = new ConcreteClass(); const response = await controller.main(ctx); if (!isHttpResponseOK(response)) { throw new Error('SwaggerController.main should return an HttpResponseOK instance.'); } strictEqual(response.getHeader('Content-Type'), 'application/javascript'); const expected = readFileSync(join(__dirname, 'specs/main.controller.spec.js'), 'utf8'); strictEqual(response.body, expected); }); it('should properly render the template given options are [{ url: "v1.json", name: "v1" }, ' + '{ controllerClass: AppController, name: "v2" }].', async () => { class ConcreteClass extends SwaggerController { options = [ { name: 'v1', url: 'v1.json' }, { name: 'v2', controllerClass: class {} }, ]; } const controller = new ConcreteClass(); const response = await controller.main(ctx); if (!isHttpResponseOK(response)) { throw new Error('SwaggerController.main should return an HttpResponseOK instance.'); } strictEqual(response.getHeader('Content-Type'), 'application/javascript'); const expected = readFileSync(join(__dirname, 'specs/main.no-primary.spec.js'), 'utf8'); strictEqual(response.body, expected); }); it('should properly render the template given options are [{ url: "xxx", name: "spec1" }, ' + '{ url: "yyy", name: "spec2", primary: true }].', async () => { class ConcreteClass extends SwaggerController { options = [ { name: 'spec1', url: 'xxx' }, { name: 'spec2', url: 'yyy', primary: true }, ]; } const controller = new ConcreteClass(); const response = await controller.main(ctx); if (!isHttpResponseOK(response)) { throw new Error('SwaggerController.main should return an HttpResponseOK instance.'); } strictEqual(response.getHeader('Content-Type'), 'application/javascript'); const expected = readFileSync(join(__dirname, 'specs/main.primary.spec.js'), 'utf8'); strictEqual(response.body, expected); }); it('should properly render the template given options are { url: "xxx" } and uiOptions are { docExpansion:"none" }' , async () => { class ConcreteClass extends SwaggerController { options = { url: 'xxx' }; uiOptions = { docExpansion: 'none' }; } const controller = new ConcreteClass(); const response = await controller.main(ctx); if (!isHttpResponseOK(response)) { throw new Error('SwaggerController.main should return an HttpResponseOK instance.'); } strictEqual(response.getHeader('Content-Type'), 'application/javascript'); const expected = readFileSync(join(__dirname, 'specs/main.url.ui-options.spec.js'), 'utf8'); strictEqual(response.body, expected); }); it('should properly render the template given options are [{ url: "v1.json", name: "v1" }] and uiOptions are' + '{ docExpansion:"none" }', async () => { class ConcreteClass extends SwaggerController { options = [ { name: 'v1', url: 'v1.json' }, ]; uiOptions = { docExpansion: 'none' }; } const controller = new ConcreteClass(); const response = await controller.main(ctx); if (!isHttpResponseOK(response)) { throw new Error('SwaggerController.main should return an HttpResponseOK instance.'); } strictEqual(response.getHeader('Content-Type'), 'application/javascript'); const expected = readFileSync(join(__dirname, 'specs/main.no-primary.ui-options.spec.js'), 'utf8'); strictEqual(response.body, expected); }); }); function testAsset( methodName: 'swaggerUi'|'swaggerUiBundle'|'swaggerUiStandalonePreset', filename: string, contentType: string ): void { describe(`has a "${methodName}" method that`, () => { it(`should handle requests at GET /${filename}.`, () => { strictEqual(getHttpMethod(ConcreteClass, methodName), 'GET'); strictEqual(getPath(ConcreteClass, methodName), `/${filename}`); }); it(`should return an HttpResponseOK whose content is the ${filename} asset.`, async () => { const controller = new ConcreteClass(); const response = await controller[methodName](); if (!isHttpResponseOK(response)) { throw new Error(`SwaggerController.${methodName} should return an HttpResponseOK instance.`); } strictEqual(response.getHeader('Content-Type'), contentType); strictEqual(response.stream, true); const filePath = `./node_modules/swagger-ui-dist/${filename}`; const stats = await promisify(stat)(filePath); strictEqual(response.getHeader('Content-Length'), stats.size.toString()); const content = await streamToBuffer(response.body); const expected = readFileSync(filePath); ok(expected.equals(content)); }); }); } testAsset('swaggerUi', 'swagger-ui.css', 'text/css'); testAsset('swaggerUiBundle', 'swagger-ui-bundle.js', 'application/javascript'); testAsset('swaggerUiStandalonePreset', 'swagger-ui-standalone-preset.js', 'application/javascript'); });
the_stack
declare module 'pixi-cull' { export class Simple { /** * Creates a simple cull * * @param {object} [options] * @param {boolean} [options.visible] Parameter of the object to set (usually * visible or renderable) Default is `visible` * @param {boolean} [options.calculatePIXI] Calculate pixi.js bounding box * automatically; if this is set to false then it uses * object[options.AABB] for bounding box Default is `true` * @param {string} [options.dirtyTest] Only update spatial hash for objects * with object[options.dirtyTest]=true; this has a HUGE impact on * performance Default is `true` * @param {string} [options.AABB] Object property that holds bounding box so * that object[type] = { x: number, y: number, width: number, height: * number }; not needed if options.calculatePIXI=true Default is `AABB` */ constructor(options?: { visible: boolean calculatePIXI: boolean dirtyTest: string AABB: string }) visible: string | true calculatePIXI: boolean dirtyTest: string | boolean AABB: string lists: any[][] /** * Add an array of objects to be culled * * @param {Array} array * @param {boolean} [staticObject] Set to true if the object's position/size * does not change * @returns {Array} Array */ addList(array: any[], staticObject?: boolean): any[] /** * Remove an array added by addList() * * @param {Array} array * @returns {Array} Array */ removeList(array: any[]): any[] /** * Add an object to be culled * * @param {any} object * @param {boolean} [staticObject] Set to true if the object's position/size * does not change * @returns {any} Object */ add(object: any, staticObject?: boolean): any /** * Remove an object added by add() * * @param {any} object * @returns {any} Object */ remove(object: any): any /** * Cull the items in the list by setting visible parameter * * @param {object} bounds * @param {number} bounds.x * @param {number} bounds.y * @param {number} bounds.width * @param {number} bounds.height * @param {boolean} [skipUpdate] Skip updating the AABB bounding box of all objects */ cull( bounds: { x: number y: number width: number height: number }, skipUpdate?: boolean ): void /** * Update the AABB for all objects automatically called from update() when * calculatePIXI=true and skipUpdate=false */ updateObjects(): void /** * Update the has of an object automatically called from updateObjects() * * @param {any} object */ updateObject(object: any): void /** * Returns an array of objects contained within bounding box * * @param {object} boudns Bounding box to search * @param {number} bounds.x * @param {number} bounds.y * @param {number} bounds.width * @param {number} bounds.height * @returns {object[]} Search results */ query(bounds: any): object[] /** * Iterates through objects contained within bounding box stops iterating if * the callback returns true * * @param {object} bounds Bounding box to search * @param {number} bounds.x * @param {number} bounds.y * @param {number} bounds.width * @param {number} bounds.height * @param {function} callback * @returns {boolean} True if callback returned early */ queryCallback( bounds: { x: number y: number width: number height: number }, callback: Function ): boolean /** * Get stats (only updated after update() is called) * * @returns {SimpleStats} */ stats(): SimpleStats } export type SimpleStats = { total: number visible: number culled: number } export class SpatialHash { /** * Creates a spatial-hash cull * * @param {object} [options] * @param {number} [options.size] Cell size used to create hash (xSize = ySize) * Default is `1000` * @param {number} [options.xSize] Horizontal cell size * @param {number} [options.ySize] Vertical cell size * @param {boolean} [options.calculatePIXI] Calculate bounding box * automatically; if this is set to false then it uses * object[options.AABB] for bounding box Default is `true` * @param {boolean} [options.visible] Parameter of the object to set (usually * visible or renderable) Default is `visible` * @param {boolean} [options.simpleTest] Iterate through visible buckets to * check for bounds Default is `true` * @param {string} [options.dirtyTest] Only update spatial hash for objects * with object[options.dirtyTest]=true; this has a HUGE impact on * performance Default is `true` * @param {string} [options.AABB] Object property that holds bounding box so * that object[type] = { x: number, y: number, width: number, height: * number } Default is `AABB` * @param {string} [options.spatial] Object property that holds object's hash * list Default is `spatial` * @param {string} [options.dirty] Object property for dirtyTest Default is `dirty` */ constructor(options?: { size: number xSize: number ySize: number calculatePIXI: boolean visible: boolean simpleTest: boolean dirtyTest: string AABB: string spatial: string dirty: string }) xSize: number ySize: number AABB: any spatial: string calculatePIXI: boolean visibleText: any simpleTest: boolean dirtyTest: string | boolean visible: string | true dirty: string width: number height: number hash: {} objects: any[] containers: any[] /** * Add an object to be culled side effect: adds object.spatialHashes to track * existing hashes * * @param {any} object * @param {boolean} [staticObject] Set to true if the object's position/size * does not change * @returns {any} Object */ add(object: any, staticObject?: boolean): any /** * Remove an object added by add() * * @param {any} object * @returns {any} Object */ remove(object: any): any /** * Add an array of objects to be culled * * @param {PIXI.Container} container * @param {boolean} [staticObject] Set to true if the objects in the * container's position/size do not change note: this only works with pixi * v5.0.0rc2+ because it relies on the new container events childAdded and * childRemoved */ addContainer(container: any, staticObject?: boolean): void /** * Remove an array added by addContainer() * * @param {PIXI.Container} container * @returns {PIXI.Container} Container */ removeContainer(container: any): any /** * Update the hashes and cull the items in the list * * @param {AABB} AABB * @param {boolean} [skipUpdate] Skip updating the hashes of all objects * @returns {number} Number of buckets in results */ cull(AABB: AABB, skipUpdate?: boolean): number /** Set all objects in hash to visible=false */ invisible(): void /** * Update the hashes for all objects automatically called from update() when * skipUpdate=false */ updateObjects(): void /** * Update the has of an object automatically called from updateObjects() * * @param {any} object * @param {boolean} [force] Force update for calculatePIXI */ updateObject(object: any): void /** * Returns an array of buckets with >= minimum of objects in each bucket * * @param {number} [minimum] Default is `1` * @returns {array} Array of buckets */ getBuckets(minimum?: number): any[] /** * Gets hash bounds * * @private * * @param {AABB} AABB * @returns {Bounds} */ private getBounds /** * Insert object into the spatial hash automatically called from updateObject() * * @param {any} object * @param {string} key */ insert(object: any, key: string): void /** * Removes object from the hash table should be called when removing an object * automatically called from updateObject() * * @param {object} object */ removeFromHash(object: object): void /** * Get all neighbors that share the same hash as object * * @param {any} object In the spatial hash * @returns {Array} Of objects that are in the same hash as object */ neighbors(object: any): any[] /** * Returns an array of objects contained within bounding box * * @param {AABB} AABB Bounding box to search * @param {boolean} [simpleTest] Perform a simple bounds check of all items in * the buckets Default is `true` * @returns {object[]} Search results */ query(AABB: AABB, simpleTest?: boolean): object[] lastBuckets: number /** * Iterates through objects contained within bounding box stops iterating if * the callback returns true * * @param {AABB} AABB Bounding box to search * @param {function} callback * @param {boolean} [simpleTest] Perform a simple bounds check of all items in * the buckets Default is `true` * @returns {boolean} True if callback returned early */ queryCallback(AABB: AABB, callback: Function, simpleTest?: boolean): boolean /** * Get stats * * @returns {Stats} */ stats(): Stats /** * Helper function to evaluate hash table * * @returns {number} The number of buckets in the hash table */ getNumberOfBuckets(): number /** * Helper function to evaluate hash table * * @returns {number} The average number of entries in each bucket */ getAverageSize(): number /** * Helper function to evaluate the hash table * * @returns {number} The largest sized bucket */ getLargest(): number /** * Gets quadrant bounds * * @returns {Bounds} */ getWorldBounds(): Bounds /** * Helper function to evalute the hash table * * @param {AABB} [AABB] Bounding box to search or entire world * @returns {number} Sparseness percentage (i.e., buckets with at least 1 * element divided by total possible buckets) */ getSparseness(AABB?: AABB): number } export type Stats = { total: number visible: number culled: number } export type Bounds = { xStart: number yStart: number xEnd: number } export type AABB = { x: number y: number width: number height: number } }
the_stack
namespace LogDog { /** Options that can be passed to fetch operations. */ export type FetcherOptions = { /** * The maximum number of bytes to fetch. If undefined, no maximum will be * specified, and the service will constrain the results. */ byteCount?: number; /** * The maximum number of logs to fetch. If undefined, no maximum will be * specified, and the service will constrain the results. */ logCount?: number; /** If defined and true, allow a fetch to return non-continuous entries. */ sparse?: boolean; }; /** The Fetcher's current status. */ export enum FetchStatus { // Not doing anything. IDLE, // Attempting to load log data. LOADING, // We're waiting for the log stream to emit more logs. STREAMING, // The log stream is missing. MISSING, // The log stream encountered an error. ERROR, // The operaiton has been cancelled. CANCELLED, } /** Fetch represents a single fetch operation. */ export class Fetch { readonly op: luci.Operation; private stateChangedCallbacks = new Array<(f: Fetch) => void>(); constructor( private ctx: FetchContext, readonly p: Promise<LogDog.LogEntry[]>) { this.op = this.ctx.op; // We will now get notifications if our Context's state changes. this.ctx.stateChangedCallback = this.onStateChanged.bind(this); } get lastStatus(): FetchStatus { return this.ctx.lastStatus; } get lastError(): Error|undefined { return this.ctx.lastError; } addStateChangedCallback(cb: (f: Fetch) => void) { this.stateChangedCallbacks.push(cb); } private onStateChanged() { this.stateChangedCallbacks.forEach(cb => cb(this)); } } /** * FetchContext is an internal context used to pair all of the common * parameters involved in a fetch operation. */ class FetchContext { private _lastStatus = FetchStatus.IDLE; private _lastError?: Error; stateChangedCallback: () => void; constructor(readonly op: luci.Operation) { // If our operation is cancelled, update our status to note this. op.addCancelCallback(() => { this._lastStatus = FetchStatus.CANCELLED; this._lastError = undefined; }); } get lastStatus(): FetchStatus { return this._lastStatus; } get lastError(): Error|undefined { return this._lastError; } updateStatus(st: FetchStatus, err?: Error) { if (this.op.cancelled) { // No more status updates, force cancelled. st = FetchStatus.CANCELLED; err = undefined; } if (st === this._lastStatus && err === this._lastError) { return; } this._lastStatus = st; this._lastError = err; this.notifyStateChanged(); } notifyStateChanged() { // If our Fetch has assigned our callback, notify it. if (this.stateChangedCallback) { this.stateChangedCallback(); } } } /** * Fetcher is responsible for fetching LogDog log stream entries from the * remote service via an RPC client. * * Fetcher is responsible for wrapping the raw RPC calls and their results, * and retrying calls due to: * * - Transient failures (via RPC client). * - Missing stream (assumption is that the stream is still being ingested and * registered, and therefore a repeated retry is appropriate). * - Streaming stream (log stream is not terminated, but more records are not * yet available). * * The interface that Fetcher presents to its caller is a simple Promise-based * method to retrieve log stream data. * * Fetcher offers fetching via "get", "getAll", and "getLatest". */ export class Fetcher { private debug = false; private static maxLogsPerGet = 0; private lastDesc: LogDog.LogStreamDescriptor; private lastState: LogDog.LogStreamState; private static missingRetry: luci.Retry = {delay: 5000, maxDelay: 15000}; private static streamingRetry: luci.Retry = {delay: 1000, maxDelay: 5000}; constructor( private client: LogDog.Client, readonly stream: LogDog.StreamPath) {} get desc() { return this.lastDesc; } get state() { return this.lastState; } /** * Returns the log stream's terminal index. * * If no terminal index is known (the log is still streaming) this will * return -1. */ get terminalIndex(): number { return ((this.lastState) ? this.lastState.terminalIndex : -1); } /** Archived returns true if this log stream is known to be archived. */ get archived(): boolean { return (!!(this.lastState && this.lastState.archive)); } /** * Returns a Promise that will resolve to the next block of logs in the * stream. * * @return A Fetch object configured with the fetch result. */ get(op: luci.Operation, index: number, opts: FetcherOptions): Fetch { let ctx = new FetchContext(op); return new Fetch(ctx, this.getIndex(ctx, index, opts)); } /** * Returns a Promise that will resolve to "count" log entries starting at * "startIndex". * * If multiple RPC calls are required to retrieve "count" entries, these * will be scheduled, and the Promise will block until the full set of * requested stream entries is retrieved. */ getAll(op: luci.Operation, startIndex: number, count: number): Fetch { // Request the tail walkback logs. Since our request for N logs may return // <N logs, we will repeat the request until all requested logs have been // obtained. let allLogs: LogDog.LogEntry[] = []; let ctx = new FetchContext(op); let getIter = async () => { op.assert(); if (count <= 0) { return allLogs; } // Perform Gets until we have the requested number of logs. We don't // have to constrain the "logCount" parameter b/c we automatically do // that in getIndex. let opts: FetcherOptions = { logCount: count, sparse: true, }; let logs = await this.getIndex(ctx, startIndex, opts); op.assert(); if (logs && logs.length) { allLogs.push.apply(allLogs, logs); startIndex += logs.length; count -= logs.length; } if (count > 0) { // Recurse. } return allLogs; }; return new Fetch(ctx, getIter()); } /** * Fetches the latest log entry. */ getLatest(op: luci.Operation): Fetch { let errNoLogs = new Error('no logs, streaming'); let ctx = new FetchContext(op); let streamingRetry = new luci.RetryIterator(Fetcher.streamingRetry); let retryPromise = streamingRetry.do( async () => { let logs = await this.doTail(ctx); if (!(logs && logs.length)) { throw errNoLogs; } return logs; }, (err: Error, delay: number) => { if (err !== errNoLogs) { throw err; } // No logs were returned, and we expect logs, so we're // streaming. Try again after a delay. ctx.updateStatus(FetchStatus.STREAMING); console.warn( this.stream, `: No logs returned; retrying after ${delay}ms...`); }); return new Fetch(ctx, retryPromise); } private async getIndex( ctx: FetchContext, index: number, opts: FetcherOptions) { // (Testing) Constrain our max logs, if set. if (Fetcher.maxLogsPerGet > 0) { if ((!opts.logCount) || opts.logCount > Fetcher.maxLogsPerGet) { opts.logCount = Fetcher.maxLogsPerGet; } } // We will retry continuously until we get a log (streaming). let errNoLogs = new Error('no logs, streaming'); let streamingRetry = new luci.RetryIterator(Fetcher.streamingRetry); let logs = await streamingRetry.do( async () => { // If we're asking for a log beyond our stream, don't bother. if (this.terminalIndex >= 0 && index > this.terminalIndex) { return []; } let fetchLogs = await this.doGet(ctx, index, opts); ctx.op.assert(); if (!(fetchLogs && fetchLogs.length)) { // (Retry) throw errNoLogs; } return fetchLogs; }, (err: Error, delay: number) => { ctx.op.assert(); if (err !== errNoLogs) { throw err; } // No logs were returned, and we expect logs, so we're streaming. // Try again after a delay. ctx.updateStatus(FetchStatus.STREAMING); console.warn( this.stream, `: No logs returned; retrying after ${delay}ms...`); }); ctx.op.assert(); // Since we allow non-contiguous Get, we may get back more logs than // we actually expected. Prune any such additional. if (opts.sparse && opts.logCount && opts.logCount > 0) { let maxStreamIndex = index + opts.logCount - 1; logs = logs.filter(le => le.streamIndex <= maxStreamIndex); } return logs; } private async doGet( ctx: FetchContext, index: number, opts: FetcherOptions) { let request: LogDog.GetRequest = { project: this.stream.project, path: this.stream.path, state: (this.terminalIndex < 0), index: index, }; if (opts.sparse || this.archived) { // This log stream is archived. We will relax the contiguous requirement // so we can render sparse log streams. request.nonContiguous = true; } if (opts.byteCount && opts.byteCount > 0) { request.byteCount = opts.byteCount; } if (opts.logCount && opts.logCount > 0) { request.logCount = opts.logCount; } if (this.debug) { console.log('logdog.Logs.Get:', request); } // Perform our Get, waiting until the stream actually exists. let missingRetry = new luci.RetryIterator(Fetcher.missingRetry); let resp = await missingRetry.do(() => { ctx.updateStatus(FetchStatus.LOADING); return this.client.get(ctx.op, request); }, this.doRetryIfMissing(ctx)); let fr = FetchResult.make(resp, this.lastDesc); return this.afterProcessResult(ctx, fr); } private async doTail(ctx: FetchContext) { let missingRetry = new luci.RetryIterator(Fetcher.missingRetry); let resp = await missingRetry.do(() => { ctx.updateStatus(FetchStatus.LOADING); let needsState = (this.terminalIndex < 0); return this.client.tail(ctx.op, this.stream, needsState); }, this.doRetryIfMissing(ctx)); let fr = FetchResult.make(resp, this.lastDesc); return this.afterProcessResult(ctx, fr); } private afterProcessResult(ctx: FetchContext, fr: FetchResult): LogDog.LogEntry[] { if (this.debug) { if (fr.logs.length) { console.log( 'Request returned:', fr.logs[0].streamIndex, '..', fr.logs[fr.logs.length - 1].streamIndex, fr.desc, fr.state); } else { console.log('Request returned no logs:', fr.desc, fr.state); } } ctx.updateStatus(FetchStatus.IDLE); if (fr.desc) { this.lastDesc = fr.desc; } if (fr.state) { this.lastState = fr.state; } return fr.logs; } private doRetryIfMissing(ctx: FetchContext) { return (err: Error, delay: number) => { ctx.op.assert(); // Is this a gRPC Error? let grpc = luci.GrpcError.convert(err); if (grpc && grpc.code === luci.Code.NOT_FOUND) { ctx.updateStatus(FetchStatus.MISSING); console.warn( this.stream, ': Is not found:', err, `; retrying after ${delay}ms...`); return; } ctx.updateStatus(FetchStatus.ERROR, err); throw err; }; } } /** * The result of a log stream fetch, for internal usage. * * It will include zero or more log entries, and optionally (if requested) * the log stream's descriptor and state. */ class FetchResult { constructor( readonly logs: LogDog.LogEntry[], readonly desc?: LogDog.LogStreamDescriptor, readonly state?: LogDog.LogStreamState) {} static make(resp: GetResponse, desc: LogDog.LogStreamDescriptor): FetchResult { let loadDesc: LogDog.LogStreamDescriptor|undefined; if (resp.desc) { desc = loadDesc = LogDog.LogStreamDescriptor.make(resp.desc); } let loadState: LogDog.LogStreamState|undefined; if (resp.state) { loadState = LogDog.LogStreamState.make(resp.state); } let logs = (resp.logs || []).map(le => LogDog.LogEntry.make(le, desc)); return new FetchResult(logs, loadDesc, loadState); } } }
the_stack
import expect from "expect"; import invariant from "invariant"; import now from "performance-now"; import sample from "lodash/sample"; import { throwError, of, Observable } from "rxjs"; import { first, filter, map, reduce, tap, mergeMap, timeoutWith, } from "rxjs/operators"; import { log } from "@ledgerhq/logs"; import type { TransactionStatus, Transaction, Account, Operation, SignOperationEvent, CryptoCurrency, } from "../types"; import { getCurrencyBridge, getAccountBridge } from "../bridge"; import { promiseAllBatched } from "../promise"; import { isAccountEmpty, formatAccount } from "../account"; import { getOperationConfirmationNumber } from "../operation"; import { getEnv } from "../env"; import { delay } from "../promise"; import { listAppCandidates, createSpeculosDevice, releaseSpeculosDevice, findAppCandidate, } from "../load/speculos"; import deviceActions from "../generated/speculos-deviceActions"; import type { AppCandidate } from "../load/speculos"; import { formatReportForConsole, formatTime, formatAppCandidate, } from "./formatters"; import type { AppSpec, MutationSpec, SpecReport, MutationReport, DeviceAction, TransactionTestInput, TransactionArg, TransactionRes, } from "./types"; import { makeBridgeCacheSystem } from "../bridge/cache"; let appCandidates; const localCache = {}; const cache = makeBridgeCacheSystem({ saveData(c, d) { localCache[c.id] = d; return Promise.resolve(); }, getData(c) { return Promise.resolve(localCache[c.id]); }, }); export async function runWithAppSpec<T extends Transaction>( spec: AppSpec<T>, reportLog: (arg0: string) => void ): Promise<SpecReport<T>> { log("engine", `spec ${spec.name}`); const seed = getEnv("SEED"); invariant(seed, "SEED is not set"); const coinapps = getEnv("COINAPPS"); invariant(coinapps, "COINAPPS is not set"); if (!appCandidates) { appCandidates = await listAppCandidates(coinapps); } const mutationReports: MutationReport<T>[] = []; const { appQuery, currency, dependency } = spec; const appCandidate = findAppCandidate(appCandidates, appQuery); invariant( appCandidate, "%s: no app found. Are you sure your COINAPPS is up to date?", spec.name, coinapps ); log( "engine", `spec ${spec.name} will use ${formatAppCandidate( appCandidate as AppCandidate )}` ); const deviceParams = { ...(appCandidate as AppCandidate), appName: spec.currency.managerAppName, seed, dependency, coinapps, }; let device; const appReport: SpecReport<T> = { spec, }; try { device = await createSpeculosDevice(deviceParams); const bridge = getCurrencyBridge(currency); const syncConfig = { paginationConfig: {}, }; let t = now(); const preloadedData = await cache.prepareCurrency(currency); const preloadTime = now() - t; // Scan all existing accounts t = now(); let scanTime = 0; const firstSyncDurations = {}; let accounts = await bridge .scanAccounts({ currency, deviceId: device.id, syncConfig, }) .pipe( filter((e) => e.type === "discovered"), map((e) => e.account), tap((account) => { const dt = now() - t; firstSyncDurations[account.id] = dt; t = now(); scanTime += dt; }), reduce<Account, Account[]>((all, a) => all.concat(a), []), timeoutWith( getEnv("BOT_TIMEOUT_SCAN_ACCOUNTS"), throwError( new Error("scan accounts timeout for currency " + currency.name) ) ) ) .toPromise(); appReport.scanTime = scanTime; appReport.accountsBefore = accounts; invariant( accounts.length > 0, "unexpected empty accounts for " + currency.name ); const preloadStats = preloadTime > 10 ? ` (preload: ${formatTime(preloadTime)})` : ""; reportLog( `Spec ${spec.name} found ${accounts.length} ${ currency.name } accounts${preloadStats}. Will use ${formatAppCandidate( appCandidate as AppCandidate )}\n${accounts .map( (a) => "(" + formatTime(firstSyncDurations[a.id] || 0) + ") " + formatAccount(a, "head") ) .join("\n")}\n` ); if (accounts.every(isAccountEmpty)) { reportLog( `This SEED does not have ${ currency.name }. Please send funds to ${accounts .map((a) => a.freshAddress) .join(" or ")}\n` ); appReport.accountsAfter = accounts; return appReport; } let mutationsCount = {}; // we sequentially iterate on the initial account set to perform mutations const length = accounts.length; const totalTries = spec.multipleRuns || 1; for (let j = 0; j < totalTries; j++) { for (let i = 0; i < length; i++) { log( "engine", `spec ${spec.name} sync all accounts (try ${j} run ${i})` ); // resync all accounts (necessary between mutations) t = now(); accounts = await promiseAllBatched( getEnv("SYNC_MAX_CONCURRENT"), accounts, syncAccount ); appReport.accountsAfter = accounts; const syncAllAccountsTime = now() - t; const account = accounts[i]; const report = await runOnAccount({ appCandidate, spec, device, account, accounts, mutationsCount, syncAllAccountsTime, preloadedData, }); // eslint-disable-next-line no-console console.log(formatReportForConsole(report)); mutationReports.push(report); appReport.mutations = mutationReports; if ( report.error || (report.latestSignOperationEvent && report.latestSignOperationEvent.type === "device-signature-requested") ) { log( "engine", `spec ${spec.name} is recreating the device because deviceAction didn't finished` ); await releaseSpeculosDevice(device.id); device = await createSpeculosDevice(deviceParams); } } mutationsCount = {}; } accounts = await promiseAllBatched( getEnv("SYNC_MAX_CONCURRENT"), accounts, syncAccount ); appReport.mutations = mutationReports; appReport.accountsAfter = accounts; } catch (e: any) { console.error(e); appReport.fatalError = e; log("engine", `spec ${spec.name} failed with ${String(e)}`); } finally { log("engine", `spec ${spec.name} finished`); if (device) await releaseSpeculosDevice(device.id); } return appReport; } export async function runOnAccount<T extends Transaction>({ appCandidate, spec, device, account, accounts, mutationsCount, syncAllAccountsTime, preloadedData, }: { appCandidate: any; spec: AppSpec<T>; device: any; account: any; accounts: any; mutationsCount: Record<string, number>; syncAllAccountsTime: number; preloadedData: any; }): Promise<MutationReport<T>> { const { mutations } = spec; let latestSignOperationEvent; const report: MutationReport<T> = { spec, appCandidate, syncAllAccountsTime, }; try { const accountBridge = getAccountBridge(account); const accountBeforeTransaction = account; report.account = account; log("engine", `spec ${spec.name}/${account.name}`); const maxSpendable = await accountBridge.estimateMaxSpendable({ account, }); report.maxSpendable = maxSpendable; log( "engine", `spec ${spec.name}/${ account.name } maxSpendable=${maxSpendable.toString()}` ); const candidates: Array<{ mutation: MutationSpec<T>; tx: T; updates: Array<Partial<T> | null | undefined>; }> = []; const unavailableMutationReasons: Array<{ mutation: MutationSpec<T>; error: Error; }> = []; for (const mutation of mutations) { try { const count = mutationsCount[mutation.name] || 0; invariant( count < (mutation.maxRun || Infinity), "maximum mutation run reached (%s)", count ); const arg: TransactionArg<T> = { appCandidate, account, bridge: accountBridge, siblings: accounts.filter((a) => a !== account), maxSpendable, preloadedData, }; if (spec.transactionCheck) spec.transactionCheck(arg); const r: TransactionRes<T> = mutation.transaction(arg); candidates.push({ mutation, tx: r.transaction, // $FlowFixMe what the hell updates: r.updates, }); } catch (error: any) { console.error(error); unavailableMutationReasons.push({ mutation, error, }); } } const candidate = sample(candidates); if (!candidate) { // no mutation were suitable report.unavailableMutationReasons = unavailableMutationReasons; return report; } // a mutation was chosen const { tx, mutation, updates } = candidate; report.mutation = mutation; report.mutationTime = now(); // prepare the transaction and ensure it's valid let status; let errors = []; let transaction: T = await accountBridge.prepareTransaction(account, tx); for (const patch of updates) { if (patch) { await accountBridge.getTransactionStatus(account, transaction); // result is unused but that would happen in normal flow report.transaction = transaction; transaction = await accountBridge.updateTransaction(transaction, patch); report.transaction = transaction; transaction = await accountBridge.prepareTransaction( account, transaction ); } } report.transaction = transaction; report.destination = accounts.find( (a) => a.freshAddress === transaction.recipient ); status = await accountBridge.getTransactionStatus(account, transaction); report.status = status; report.statusTime = now(); errors = Object.values(status.errors); const warnings = Object.values(status.warnings); if (mutation.recoverBadTransactionStatus) { if (errors.length || warnings.length) { // there is something to recover from const recovered = mutation.recoverBadTransactionStatus({ transaction, status, account, bridge: accountBridge, }); if (recovered && recovered !== transaction) { report.recoveredFromTransactionStatus = { transaction, status, }; report.transaction = transaction = recovered; status = await accountBridge.getTransactionStatus( account, transaction ); report.status = status; report.statusTime = now(); } } } // without recovering mecanism, we simply assume an error is a failure if (errors.length) { throw errors[0]; } mutationsCount[mutation.name] = (mutationsCount[mutation.name] || 0) + 1; // sign the transaction with speculos log("engine", `spec ${spec.name}/${account.name} signing`); const signedOperation = await accountBridge .signOperation({ account, transaction, deviceId: device.id, }) .pipe( tap((e) => { latestSignOperationEvent = e; log("engine", `spec ${spec.name}/${account.name}: ${e.type}`); }), autoSignTransaction({ transport: device.transport, deviceAction: mutation.deviceAction || getImplicitDeviceAction(account.currency), appCandidate, account, transaction, status, }), first((e: any) => e.type === "signed"), map( (e) => ( invariant(e.type === "signed", "signed operation"), e.signedOperation ) ) ) .toPromise(); report.signedOperation = signedOperation; report.signedTime = now(); // broadcast the transaction const optimisticOperation = getEnv("DISABLE_TRANSACTION_BROADCAST") ? signedOperation.operation : await accountBridge.broadcast({ account, signedOperation, }); report.optimisticOperation = optimisticOperation; report.broadcastedTime = now(); log( "engine", `spec ${spec.name}/${account.name}/${optimisticOperation.hash} broadcasted` ); // wait the condition are good (operation confirmed) const testBefore = now(); const step = (account) => { const timedOut = now() - testBefore > (mutation.testTimeout || spec.testTimeout || 30 * 1000); const operation = account.operations.find( (o) => o.id === optimisticOperation.id ); if (timedOut && !operation) { throw new Error( "could not find optimisticOperation " + optimisticOperation.id ); } if (operation) { try { const arg = { accountBeforeTransaction, transaction, status, optimisticOperation, operation, account, }; transactionTest(arg); if (spec.test) spec.test(arg); if (mutation.test) mutation.test(arg); report.testDuration = now() - testBefore; } catch (e) { // We never reach the final test success if (timedOut) { report.testDuration = now() - testBefore; throw e; } // We will try again return; } } return operation; }; const result = await awaitAccountOperation({ account, step, }); report.finalAccount = result.account; report.operation = result.operation; report.confirmedTime = now(); log( "engine", `spec ${spec.name}/${account.name}/${optimisticOperation.hash} confirmed` ); } catch (error: any) { log("mutation-error", spec.name + ": " + String(error)); report.error = error; } report.latestSignOperationEvent = latestSignOperationEvent; return report; } async function syncAccount(initialAccount: Account): Promise<Account> { const acc = await getAccountBridge(initialAccount) .sync(initialAccount, { paginationConfig: {}, }) .pipe( reduce((a, f: (arg0: Account) => Account) => f(a), initialAccount), timeoutWith( 10 * 60 * 1000, throwError(new Error("account sync timeout for " + initialAccount.name)) ) ) .toPromise(); return acc; } export function autoSignTransaction<T extends Transaction>({ transport, deviceAction, appCandidate, account, transaction, status, }: { transport: any; deviceAction: DeviceAction<T, any>; appCandidate: AppCandidate; account: Account; transaction: T; status: TransactionStatus; }) { let sub; let observer; let state; const recentEvents: SignOperationEvent[] = []; return mergeMap<SignOperationEvent, Observable<SignOperationEvent>>((e) => { if (e.type === "device-signature-requested") { return new Observable((o) => { if (observer) { o.error( new Error("device-signature-requested should not be called twice!") ); return; } observer = o; o.next(e); const timeout = setTimeout(() => { o.error( new Error( "device action timeout. Recent events was:\n" + recentEvents.map((e) => JSON.stringify(e)).join("\n") ) ); }, 60 * 1000); sub = transport.automationEvents.subscribe({ next: (event) => { recentEvents.push(event); if (recentEvents.length > 5) { recentEvents.shift(); } try { state = deviceAction({ appCandidate, account, transaction, event, transport, state, status, }); } catch (e) { o.error(e); } }, complete: () => { o.complete(); }, error: (e) => { o.error(e); }, }); return () => { clearTimeout(timeout); sub.unsubscribe(); }; }); } else if (observer) { observer.complete(); observer = null; } if (sub) { sub.unsubscribe(); } return of<SignOperationEvent>(e); }); } export function getImplicitDeviceAction(currency: CryptoCurrency) { const actions = deviceActions[currency.family]; const accept = actions && actions.acceptTransaction; invariant( accept, "a acceptTransaction is missing for family %s", currency.family ); return accept; } function awaitAccountOperation({ account, step, }: { account: Account; step: (arg0: Account) => Operation | null | undefined; }): Promise<{ account: Account; operation: Operation; }> { log("engine", "awaitAccountOperation on " + account.name); let syncCounter = 0; let acc = account; async function loop() { const operation = step(acc); if (operation) { log("engine", "found " + operation.id); return { account: acc, operation, }; } await delay(5000); log("engine", "sync #" + syncCounter++ + " on " + account.name); acc = await syncAccount(acc); const r = await loop(); return r; } return loop(); } // generic transaction test: make sure you are sure all coins suit the tests here function transactionTest<T>({ operation, optimisticOperation, account, }: TransactionTestInput<T>) { const timingThreshold = 30 * 60 * 1000; // FIXME: .valueOf to do arithmetic operations on date with typescript const dt = Date.now().valueOf() - operation.date.valueOf(); invariant(dt > 0, "operation.date must not be in in future"); expect(dt).toBeLessThan(timingThreshold); invariant(!operation.hasFailed, "operation must be hasFailed"); const { blockAvgTime } = account.currency; if (blockAvgTime && account.blockHeight) { const expected = getOperationConfirmationNumber(operation, account); const expectedMax = Math.ceil(timingThreshold / blockAvgTime); invariant( expected <= expectedMax, "There are way too much operation confirmation for a small amount of time. %s < %s", expected, expectedMax ); } invariant( !optimisticOperation.value.isNaN(), "optimisticOperation.value must not be NaN" ); invariant( !optimisticOperation.fee.isNaN(), "optimisticOperation.fee must not be NaN" ); invariant(!operation.value.isNaN(), "operation.value must not be NaN"); invariant(!operation.fee.isNaN(), "operation.fee must not be NaN"); }
the_stack
import {IronResizableBehavior} from '@polymer/iron-resizable-behavior/iron-resizable-behavior.js'; import {IronScrollTargetBehavior} from '@polymer/iron-scroll-target-behavior/iron-scroll-target-behavior.js'; import {OptionalMutableDataBehavior} from '@polymer/polymer/lib/legacy/mutable-data-behavior.js'; import {Polymer} from '@polymer/polymer/lib/legacy/polymer-fn.js'; import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js'; import {Templatizer} from '@polymer/polymer/lib/legacy/templatizer-behavior.js'; import {animationFrame, idlePeriod, microTask} from '@polymer/polymer/lib/utils/async.js'; import {Debouncer} from '@polymer/polymer/lib/utils/debounce.js'; import {enqueueDebouncer, flush} from '@polymer/polymer/lib/utils/flush.js'; import {html} from '@polymer/polymer/lib/utils/html-tag.js'; import {matches, translate} from '@polymer/polymer/lib/utils/path.js'; import {TemplateInstanceBase} from '@polymer/polymer/lib/utils/templatize.js'; import {LegacyElementMixin} from '@polymer/polymer/lib/legacy/legacy-element-mixin.js'; /** * `iron-list` displays a virtual, 'infinite' list. The template inside * the iron-list element represents the DOM to create for each list item. * The `items` property specifies an array of list item data. * * For performance reasons, not every item in the list is rendered at once; * instead a small subset of actual template elements *(enough to fill the * viewport)* are rendered and reused as the user scrolls. As such, it is important * that all state of the list template is bound to the model driving it, since the * view may be reused with a new model at any time. Particularly, any state that * may change as the result of a user interaction with the list item must be bound * to the model to avoid view state inconsistency. * * ### Sizing iron-list * * `iron-list` must either be explicitly sized, or delegate scrolling to an * explicitly sized parent. By "explicitly sized", we mean it either has an * explicit CSS `height` property set via a class or inline style, or else is sized * by other layout means (e.g. the `flex` or `fit` classes). * * #### Flexbox - [jsbin](https://jsbin.com/vejoni/edit?html,output) * * ```html * <template is="x-list"> * <style> * :host { * display: block; * height: 100vh; * display: flex; * flex-direction: column; * } * * iron-list { * flex: 1 1 auto; * } * </style> * <app-toolbar>App name</app-toolbar> * <iron-list items="[[items]]"> * <template> * <div> * ... * </div> * </template> * </iron-list> * </template> * ``` * #### Explicit size - [jsbin](https://jsbin.com/vopucus/edit?html,output) * ```html * <template is="x-list"> * <style> * :host { * display: block; * } * * iron-list { * height: 100vh; /* don't use % values unless the parent element is sized. * \/ * } * </style> * <iron-list items="[[items]]"> * <template> * <div> * ... * </div> * </template> * </iron-list> * </template> * ``` * #### Main document scrolling - * [jsbin](https://jsbin.com/wevirow/edit?html,output) * ```html * <head> * <style> * body { * height: 100vh; * margin: 0; * display: flex; * flex-direction: column; * } * * app-toolbar { * position: fixed; * top: 0; * left: 0; * right: 0; * } * * iron-list { * /* add padding since the app-toolbar is fixed at the top *\/ * padding-top: 64px; * } * </style> * </head> * <body> * <app-toolbar>App name</app-toolbar> * <iron-list scroll-target="document"> * <template> * <div> * ... * </div> * </template> * </iron-list> * </body> * ``` * * `iron-list` must be given a `<template>` which contains exactly one element. In * the examples above we used a `<div>`, but you can provide any element (including * custom elements). * * ### Template model * * List item templates should bind to template models of the following structure: * * ```js * { * index: 0, // index in the item array * selected: false, // true if the current item is selected * tabIndex: -1, // a dynamically generated tabIndex for focus management * item: {} // user data corresponding to items[index] * } * ``` * * Alternatively, you can change the property name used as data index by changing * the `indexAs` property. The `as` property defines the name of the variable to * add to the binding scope for the array. * * For example, given the following `data` array: * * ##### data.json * * ```js * [ * {"name": "Bob"}, * {"name": "Tim"}, * {"name": "Mike"} * ] * ``` * * The following code would render the list (note the name property is bound from * the model object provided to the template scope): * * ```html * <iron-ajax url="data.json" last-response="{{data}}" auto></iron-ajax> * <iron-list items="[[data]]" as="item"> * <template> * <div> * Name: [[item.name]] * </div> * </template> * </iron-list> * ``` * * ### Grid layout * * `iron-list` supports a grid layout in addition to linear layout by setting * the `grid` attribute. In this case, the list template item must have both fixed * width and height (e.g. via CSS). Based on this, the number of items * per row are determined automatically based on the size of the list viewport. * * ### Accessibility * * `iron-list` automatically manages the focus state for the items. It also * provides a `tabIndex` property within the template scope that can be used for * keyboard navigation. For example, users can press the up and down keys to move * to previous and next items in the list: * * ```html * <iron-list items="[[data]]" as="item"> * <template> * <div tabindex$="[[tabIndex]]"> * Name: [[item.name]] * </div> * </template> * </iron-list> * ``` * * ### Styling * * You can use the `--iron-list-items-container` mixin to style the container of * items: * * ```css * iron-list { * --iron-list-items-container: { * margin: auto; * }; * } * ``` * * ### Resizing * * `iron-list` lays out the items when it receives a notification via the * `iron-resize` event. This event is fired by any element that implements * `IronResizableBehavior`. * * By default, elements such as `iron-pages`, `paper-tabs` or `paper-dialog` will * trigger this event automatically. If you hide the list manually (e.g. you use * `display: none`) you might want to implement `IronResizableBehavior` or fire * this event manually right after the list became visible again. For example: * * ```js * document.querySelector('iron-list').fire('iron-resize'); * ``` * * ### When should `<iron-list>` be used? * * `iron-list` should be used when a page has significantly more DOM nodes than the * ones visible on the screen. e.g. the page has 500 nodes, but only 20 are visible * at a time. This is why we refer to it as a `virtual` list. In this case, a * `dom-repeat` will still create 500 nodes which could slow down the web app, but * `iron-list` will only create 20. * * However, having an `iron-list` does not mean that you can load all the data at * once. Say you have a million records in the database, you want to split the data * into pages so you can bring in a page at the time. The page could contain 500 * items, and iron-list will only render 20. */ interface IronListElement extends Templatizer, IronResizableBehavior, IronScrollTargetBehavior, OptionalMutableDataBehavior, LegacyElementMixin, HTMLElement { readonly _defaultScrollTarget: any; /** * An array containing items determining how many instances of the template * to stamp and that that each template instance should bind to. */ items: any[]|null|undefined; /** * The name of the variable to add to the binding scope for the array * element associated with a given template instance. */ as: string|null|undefined; /** * The name of the variable to add to the binding scope with the index * for the row. */ indexAs: string|null|undefined; /** * The name of the variable to add to the binding scope to indicate * if the row is selected. */ selectedAs: string|null|undefined; /** * When true, the list is rendered as a grid. Grid items must have * fixed width and height set via CSS. e.g. * * ```html * <iron-list grid> * <template> * <div style="width: 100px; height: 100px;"> 100x100 </div> * </template> * </iron-list> * ``` */ grid: boolean|null|undefined; /** * When true, tapping a row will select the item, placing its data model * in the set of selected items retrievable via the selection property. * * Note that tapping focusable elements within the list item will not * result in selection, since they are presumed to have their * own action. */ selectionEnabled: boolean|null|undefined; /** * When `multiSelection` is false, this is the currently selected item, or * `null` if no item is selected. */ selectedItem: object|null|undefined; /** * When `multiSelection` is true, this is an array that contains the * selected items. */ selectedItems: object|null|undefined; /** * When `true`, multiple items may be selected at once (in this case, * `selected` is an array of currently selected items). When `false`, * only one item may be selected at a time. */ multiSelection: boolean|null|undefined; /** * The offset top from the scrolling element to the iron-list element. * This value can be computed using the position returned by * `getBoundingClientRect()` although it's preferred to use a constant value * when possible. * * This property is useful when an external scrolling element is used and * there's some offset between the scrolling element and the list. For * example: a header is placed above the list. */ scrollOffset: number|null|undefined; /** * The ratio of hidden tiles that should remain in the scroll direction. * Recommended value ~0.5, so it will distribute tiles evenly in both * directions. * */ _ratio: number; /** * The padding-top value for the list. * */ _scrollerPaddingTop: number; /** * This value is a cached value of `scrollTop` from the last `scroll` event. * */ _scrollPosition: number; /** * The sum of the heights of all the tiles in the DOM. * */ _physicalSize: number; /** * The average `offsetHeight` of the tiles observed till now. * */ _physicalAverage: number; /** * The number of tiles which `offsetHeight` > 0 observed until now. * */ _physicalAverageCount: number; /** * The Y position of the item rendered in the `_physicalStart` * tile relative to the scrolling list. * */ _physicalTop: number; /** * The number of items in the list. * */ _virtualCount: number; /** * The estimated scroll height based on `_physicalAverage` * */ _estScrollHeight: number; /** * The scroll height of the dom node * */ _scrollHeight: number; /** * The height of the list. This is referred as the viewport in the context of * list. * */ _viewportHeight: number; /** * The width of the list. This is referred as the viewport in the context of * list. * */ _viewportWidth: number; /** * An array of DOM nodes that are currently in the tree */ _physicalItems: HTMLElement[]|null; /** * An array of heights for each item in `_physicalItems` */ _physicalSizes: number[]|null; /** * A cached value for the first visible index. * See `firstVisibleIndex` */ _firstVisibleIndexVal: number|null; /** * A cached value for the last visible index. * See `lastVisibleIndex` */ _lastVisibleIndexVal: number|null; /** * The max number of pages to render. One page is equivalent to the height of * the list. * */ _maxPages: number; /** * The currently focused physical item. * */ _focusedItem: null; /** * The virtual index of the focused item. * */ _focusedVirtualIndex: any; /** * The physical index of the focused item. * */ _focusedPhysicalIndex: any; /** * The item that backfills the `_offscreenFocusedItem` in the physical items * list when that item is moved offscreen. */ _focusBackfillItem: HTMLElement|null; /** * The maximum items per row * */ _itemsPerRow: number; /** * The width of each grid item * */ _itemWidth: number; /** * The height of the row in grid layout. * */ _rowHeight: number; /** * The cost of stamping a template in ms. * */ _templateCost: number; /** * Needed to pass event.model property to declarative event handlers - * see polymer/polymer#4339. * */ _parentModel: boolean; /** * The bottom of the physical content. * */ readonly _physicalBottom: any; /** * The bottom of the scroll. * */ readonly _scrollBottom: any; /** * The n-th item rendered in the last physical item. * */ readonly _virtualEnd: any; /** * The height of the physical content that isn't on the screen. * */ readonly _hiddenContentSize: any; /** * The parent node for the _userTemplate. * */ readonly _itemsParent: any; /** * The maximum scroll top value. * */ readonly _maxScrollTop: any; /** * The largest n-th value for an item such that it can be rendered in * `_physicalStart`. * */ readonly _maxVirtualStart: any; _virtualStart: any; _physicalStart: any; /** * The k-th tile that is at the bottom of the scrolling list. * */ readonly _physicalEnd: any; _physicalCount: any; /** * An optimal physical size such that we will have enough physical items * to fill up the viewport and recycle when the user scrolls. * * This default value assumes that we will at least have the equivalent * to a viewport of physical items above and below the user's viewport. * */ readonly _optPhysicalSize: any; /** * True if the current list is visible. * */ readonly _isVisible: any; /** * Gets the index of the first visible item in the viewport. */ readonly firstVisibleIndex: any; /** * Gets the index of the last visible item in the viewport. */ readonly lastVisibleIndex: any; readonly _virtualRowCount: any; readonly _estRowsInView: any; readonly _physicalRows: any; readonly _scrollOffset: any; attached(): void; detached(): void; /** * Recycles the physical items when needed. */ _scrollHandler(): void; ready(): void; /** * Set the overflow property if this element has its own scrolling region */ _setOverflow(scrollTarget: any): void; /** * Invoke this method if you dynamically update the viewport's * size or CSS padding. */ updateViewportBoundaries(): void; /** * Returns an object that contains the indexes of the physical items * that might be reused and the physicalTop. * * @param fromTop If the potential reusable items are above the scrolling region. */ _getReusables(fromTop: boolean): any; /** * Update the list of items, starting from the `_virtualStart` item. */ _update(itemSet?: number[], movingUp?: number[]): void; /** * Creates a pool of DOM elements and attaches them to the local dom. * * @param size Size of the pool */ _createPool(size: number): any; _isClientFull(): any; /** * Increases the pool size. */ _increasePoolIfNeeded(count: any): void; /** * Renders the a new list. */ _render(): void; /** * Templetizes the user template. */ _ensureTemplatized(): void; _gridChanged(newGrid: any, oldGrid: any): void; /** * Called when the items have changed. That is, reassignments * to `items`, splices or updates to a single item. */ _itemsChanged(change: any): void; _forwardItemPath(path: any, value: any): void; _adjustVirtualIndex(splices: object[]): void; _removeItem(item: any): void; /** * Executes a provided function per every physical index in `itemSet` * `itemSet` default value is equivalent to the entire set of physical * indexes. */ _iterateItems(fn: (p0: number, p1: number) => any, itemSet?: number[]): any; /** * Returns the virtual index for a given physical index * * @param pidx Physical index */ _computeVidx(pidx: number): number; /** * Assigns the data models to a given set of items. */ _assignModels(itemSet?: number[]): void; /** * Updates the height for a given set of items. */ _updateMetrics(itemSet?: number[]): void; _updateGridMetrics(): void; /** * Updates the position of the physical items. */ _positionItems(): void; _getPhysicalSizeIncrement(pidx: any): any; /** * Returns, based on the current index, * whether or not the next index will need * to be rendered on a new row. * * @param vidx Virtual index */ _shouldRenderNextRow(vidx: number): boolean; /** * Adjusts the scroll position when it was overestimated. */ _adjustScrollPosition(): void; /** * Sets the position of the scroll. */ _resetScrollPosition(pos: any): void; /** * Sets the scroll height, that's the height of the content, * * @param forceUpdate If true, updates the height no matter what. */ _updateScrollerSize(forceUpdate?: boolean): void; /** * Scroll to a specific item in the virtual list regardless * of the physical items in the DOM tree. * * @param item The item to be scrolled to */ scrollToItem(item: object|null): any; /** * Scroll to a specific index in the virtual list regardless * of the physical items in the DOM tree. * * @param idx The index of the item */ scrollToIndex(idx: number): void; /** * Reset the physical average and the average count. */ _resetAverage(): void; /** * A handler for the `iron-resize` event triggered by `IronResizableBehavior` * when the element is resized. */ _resizeHandler(): void; /** * Selects the given item. * * @param item The item instance. */ selectItem(item: object|null): any; /** * Selects the item at the given index in the items array. * * @param index The index of the item in the items array. */ selectIndex(index: number): void; /** * Deselects the given item. * * @param item The item instance. */ deselectItem(item: object|null): any; /** * Deselects the item at the given index in the items array. * * @param index The index of the item in the items array. */ deselectIndex(index: number): void; /** * Selects or deselects a given item depending on whether the item * has already been selected. * * @param item The item object. */ toggleSelectionForItem(item: object|null): any; /** * Selects or deselects the item at the given index in the items array * depending on whether the item has already been selected. * * @param index The index of the item in the items array. */ toggleSelectionForIndex(index: number): void; /** * Clears the current selection in the list. */ clearSelection(): void; /** * Add an event listener to `tap` if `selectionEnabled` is true, * it will remove the listener otherwise. */ _selectionEnabledChanged(selectionEnabled: any): void; /** * Select an item from an event object. */ _selectionHandler(e: any): void; _multiSelectionChanged(multiSelection: any): void; /** * Updates the size of a given list item. * * @param item The item instance. */ updateSizeForItem(item: object|null): any; /** * Updates the size of the item at the given index in the items array. * * @param index The index of the item in the items array. */ updateSizeForIndex(index: number): any; /** * Creates a temporary backfill item in the rendered pool of physical items * to replace the main focused item. The focused item has tabIndex = 0 * and might be currently focused by the user. * * This dynamic replacement helps to preserve the focus state. */ _manageFocus(): void; /** * Converts a random index to the index of the item that completes it's row. * Allows for better order and fill computation when grid == true. */ _convertIndexToCompleteRow(idx: any): any; _isIndexRendered(idx: any): any; _isIndexVisible(idx: any): any; _getPhysicalIndex(vidx: any): any; focusItem(idx: any): void; _focusPhysicalItem(idx: any): void; _removeFocusedItem(): void; _createFocusBackfillItem(): void; _restoreFocusedItem(): void; _didFocus(e: any): void; _keydownHandler(e: any): void; _clamp(v: any, min: any, max: any): any; _debounce(name: any, cb: any, asyncModule: any): void; _forwardProperty(inst: any, name: any, value: any): void; /** * Templatizer bindings for v2 */ _forwardHostPropV2(prop: any, value: any): void; _notifyInstancePropV2(inst: any, prop: any, value: any): void; /** * Templatizer bindings for v1 */ _getStampedChildren(): any; _forwardInstancePath(inst: any, path: any, value: any): void; _forwardParentPath(path: any, value: any): void; _forwardParentProp(prop: any, value: any): void; /** * Gets the activeElement of the shadow root/host that contains the list. */ _getActiveElement(): any; } export {IronListElement}; declare global { interface HTMLElementTagNameMap { "iron-list": IronListElement; } }
the_stack
* Unit tests for activations.ts. */ import * as tfc from '@tensorflow/tfjs-core'; import {scalar, Tensor, tensor1d, tensor2d, tensor3d} from '@tensorflow/tfjs-core'; import {epsilon} from './backend/common'; import * as losses from './losses'; import {describeMathCPUAndGPU, expectTensorsClose} from './utils/test_utils'; describeMathCPUAndGPU('meanSquaredError', () => { it('1D', () => { const yTrue = tfc.zeros([3]); const yPred = tensor1d([1, 2, 3]); const expectedVal = scalar((1 * 1 + 2 * 2 + 3 * 3) / 3); const result = losses.meanSquaredError(yTrue, yPred); expectTensorsClose(result, expectedVal); }); it('2D', () => { const yTrue = tfc.zeros([2, 2]); const yPred = tensor2d([[1, 2], [3, 4]], [2, 2]); const expectedVal = tensor1d([(1 * 1 + 2 * 2) / 2, (3 * 3 + 4 * 4) / 2]); const result = losses.meanSquaredError(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('meanAbsoluteError', () => { it('1D', () => { const yTrue = tfc.zeros([3]); const yPred = tensor1d([-1, -2, -3]); const expectedVal = scalar((1 + 2 + 3) / 3); const result = losses.meanAbsoluteError(yTrue, yPred); expectTensorsClose(result, expectedVal); }); it('2D', () => { const yTrue = tfc.zeros([2, 2]); const yPred = tensor2d([[-1, -2], [-3, -4]], [2, 2]); const expectedVal = tensor1d([(1 + 2) / 2, (3 + 4) / 2]); const result = losses.meanAbsoluteError(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('meanAbsolutePercentageError', () => { it('1D', () => { const yTrue = tensor1d([-1, -2, -3]); const yPred = tfc.zeros([3]); const expectedVal = scalar((1 + 2 + 3) / (1 + 2 + 3) * 100); const result = losses.meanAbsolutePercentageError(yTrue, yPred); expectTensorsClose(result, expectedVal); }); it('2D', () => { const yTrue = tensor2d([[-1, -2], [-3, -4]], [2, 2]); const yPred = tfc.zeros([2, 2]); const expectedVal = tensor1d([(1 + 2) / (1 + 2) * 100, (3 + 4) / (3 + 4) * 100]); const result = losses.meanAbsolutePercentageError(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('meanSquaredLogarithmicError', () => { function meanSquaredLogErrorFor1DArray(x: number[], y: number[]): number { const calcLog = (val: number) => Math.log(Math.max(val, epsilon()) + 1); const logX = x.map(calcLog); const logY = y.map(calcLog); let acc = 0.0; for (let i = 0; i < x.length; i++) { const diff = logX[i] - logY[i]; acc += diff * diff; } return acc / x.length; } it('2D', () => { const yTrue = tfc.zeros([2, 2]); const yPred = tensor2d([[1, 2], [3, 4]], [2, 2]); const expectedVal = tensor1d([ meanSquaredLogErrorFor1DArray([1, 2], [0, 0]), meanSquaredLogErrorFor1DArray([3, 4], [0, 0]) ]); const result = losses.meanSquaredLogarithmicError(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('squaredHinge', () => { it('2D', () => { const yTrue = tensor2d([[-1, 2], [-3, 2]], [2, 2]); const yPred = tensor2d([[-3, 5], [3, -2]], [2, 2]); // First row has correct predictions, so loss is 0. const secondRow = [1 - (-3 * 3), 1 - (2 * -2)].map(x => x * x); const expectedVal = tensor1d([0, (secondRow[0] + secondRow[1]) / 2]); const result = losses.squaredHinge(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('hinge', () => { it('2D', () => { const yTrue = tensor2d([[-1, 2], [-3, 2]], [2, 2]); const yPred = tensor2d([[-3, 5], [3, -2]], [2, 2]); // First row has correct predictions, so loss is 0. const secondRow = [1 - (-3 * 3), 1 - (2 * -2)]; const expectedVal = tensor1d([0, (secondRow[0] + secondRow[1]) / 2]); const result = losses.hinge(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('categoricalHinge', () => { it('2D', () => { const yTrue = tensor2d([[0, 1, 0], [1, 0, 0]], [2, 3]); const yPred = tensor2d([[0, 2, 0], [1, 3, 2]], [2, 3]); // First row has correct predictions, so loss is 0. const secondRowPos = 1 * 1; const secondRowNeg = Math.max(1 * 3, 1 * 2); const secondRowVal = secondRowNeg - secondRowPos + 1; const expectedVal = tensor1d([0, secondRowVal]); const result = losses.categoricalHinge(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('logcosh', () => { function _logcosh(x: number): number { return x + Math.log(Math.exp(-2 * x) + 1) - Math.log(2); } it('2D', () => { const yTrue = tfc.zeros([2, 2]); const yPred = tensor2d([[1, 2], [3, 4]], [2, 2]); const firstRow = [1, 2].map(_logcosh); const secondRow = [3, 4].map(_logcosh); const firstVal = (firstRow[0] + firstRow[1]) / 2; const secondVal = (secondRow[0] + secondRow[1]) / 2; const expectedVal = tensor1d([firstVal, secondVal]); const result = losses.logcosh(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('categoricalCrossentropy ', () => { it('from logits', () => { const x = tensor2d([[1, 2], [3, 4]], [2, 2]); const target = tensor2d([[0.25, 0.75], [0.1, 0.9]], [2, 2]); const expected = tensor1d([ -1 * (Math.log(Math.exp(1) / (Math.exp(1) + Math.exp(2))) * 0.25 + Math.log(Math.exp(2) / (Math.exp(1) + Math.exp(2))) * 0.75), -1 * (Math.log(Math.exp(3) / (Math.exp(3) + Math.exp(4))) * 0.1 + Math.log(Math.exp(4) / (Math.exp(3) + Math.exp(4))) * 0.9) ]); const result = losses.categoricalCrossentropy(target, x, true); expectTensorsClose(result, expected); }); it('from softmax', () => { const x = tensor2d([[0.3, 0.7], [0.4, 0.6]], [2, 2]); const target = tensor2d([[0.25, 0.75], [0.1, 0.9]], [2, 2]); const expected = tensor1d([ -1 * (Math.log(0.3) * 0.25 + Math.log(0.7) * 0.75), -1 * (Math.log(0.4) * 0.1 + Math.log(0.6) * 0.9) ]); const result = losses.categoricalCrossentropy(target, x, false); expectTensorsClose(result, expected); }); // Reference Python code // ```python // import numpy as np // import tensorflow as tf // from tensorflow import keras // // x_value = np.array([[[0.3, 0.7], [0.4, 0.6]], [[0.2, 0.8], [0.55, 0.45]]]) // target_value = np.array([[[0, 1], [1, 0]], [[0, 1], [1, 0]]]) // // with tf.Session() as sess: // x = tf.placeholder(tf.float32, [2, 2, 2]) // target = tf.placeholder(tf.float32, [2, 2, 2]) // y = keras.backend.categorical_crossentropy(target, x) // print(sess.run(y, feed_dict={ // x: x_value, // target: target_value // })) // ``` it('from softmax, sequence output', () => { const x = tensor3d([[[0.3, 0.7], [0.4, 0.6]], [[0.2, 0.8], [0.55, 0.45]]], [ 2, 2, 2, ]); const target = tensor3d([[[0, 1], [1, 0]], [[0, 1], [1, 0]]], [2, 2, 2]); const result = losses.categoricalCrossentropy(target, x, false); expectTensorsClose( result, tensor2d([[0.35667497, 0.9162907], [0.22314353, 0.597837]])); }); }); describeMathCPUAndGPU('sparseCategoricalCrossentropy ', () => { // Reference Python TensorFlow code: // ```py // import numpy as np // import tensorflow as tf // // with tf.Session() as sess: // x = tf.placeholder(tf.float32, [None, 3]) // target = tf.placeholder(tf.float32, [None]) // crossentropy = tf.keras.backend.sparse_categorical_crossentropy( // target, x) // out = sess.run( // crossentropy, // feed_dict={ // x: np.array([[0.1, 0.2, 0.7], [0.2, 0.3, 0.5]], // dtype=np.float32), // target: np.array([0, 2], dtype=np.float32) // }) // print(out) // ``` it('sparseCategoricalCrossentropy', () => { const x = tensor2d([[0.1, 0.2, 0.7], [0.2, 0.3, 0.5]], [2, 3]); const target = tensor1d([0, 2]); const result = losses.sparseCategoricalCrossentropy(target, x); expectTensorsClose(result, tensor1d([2.3025851, 0.6931472])); }); }); describeMathCPUAndGPU('sigmoidCrossEntropyWithLogits', () => { it('outputs sigmoid cross-entropy', () => { const x = tensor2d([[1, 2], [3, 4]], [2, 2]); const target = tensor2d([[0.25, 0.75], [0.1, 0.9]], [2, 2]); const targetComplement = tfc.add(scalar(1), tfc.neg(target)); const sigmoidX = tfc.sigmoid(x); const sigmoidXComplement = tfc.add(scalar(1), tfc.neg(sigmoidX)); const expected = tfc.add( tfc.mul(target, tfc.neg(tfc.log(sigmoidX))), tfc.mul(targetComplement, tfc.neg(tfc.log(sigmoidXComplement)))); const result = losses.sigmoidCrossEntropyWithLogits(target, x); expectTensorsClose(result, expected); }); // Python TensorFlow reference code: // ```py // import numpy as np // import tensorflow as tf // // tf.enable_eager_execution() // // logits = np.array([[-10, -10, -10], // [-5, -5, -5], // [0, 0, 0], // [0.5, 0.5, 0.5], // [2, 2, 2]], dtype=np.float32) // labels = np.array([[0, 0.5, 1], // [0, 0.5, 1], // [0, 0.5, 1], // [0, 0.5, 1], // [0, 0.5, 1]], dtype=np.float32) // // print(tf.nn.sigmoid_cross_entropy_with_logits( // logits=logits, labels=labels)) // ``` it('Comparison with TensorFlow references values', () => { const logits = tensor2d( [[-10, -10, -10], [-5, -5, -5], [0, 0, 0], [0.5, 0.5, 0.5], [2, 2, 2]]); const labels = tensor2d( [[0, 0.5, 1], [0, 0.5, 1], [0, 0.5, 1], [0, 0.5, 1], [0, 0.5, 1]]); const outputs = losses.sigmoidCrossEntropyWithLogits(labels, logits); expectTensorsClose(outputs, tensor2d([ [4.5398901e-05, 5.0000453e+00, 1.0000046e+01], [6.7153485e-03, 2.5067153e+00, 5.0067153e+00], [6.9314718e-01, 6.9314718e-01, 6.9314718e-01], [9.7407699e-01, 7.2407699e-01, 4.7407699e-01], [2.1269281e+00, 1.1269280e+00, 1.2692800e-01] ])); }); }); describeMathCPUAndGPU('categoricalCrossentropy', () => { it('2D', () => { const yTrue = tensor2d([[1, 0], [0, 1]], [2, 2]); const yPred = yTrue; const expectedVal = tfc.zeros([2]); const result = losses.categoricalCrossentropy(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('sparseCategoricalCrossentropy', () => { it('2D', () => { const yTrue = tensor1d([0, 1]); const yPred = tensor2d([[1, 0], [0, 1]], [2, 2]); const expectedVal = tfc.zeros([2]); const result = losses.sparseCategoricalCrossentropy(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('binaryCrossentropy', () => { function _binaryCrossentropy(target: Tensor, output: Tensor): Tensor { const targetComplement = tfc.add(scalar(1), tfc.neg(target)); const outputComplement = tfc.add(scalar(1), tfc.neg(output)); return tfc.mean( tfc.neg(tfc.add( tfc.mul(target, tfc.log(output)), tfc.mul(targetComplement, tfc.log(outputComplement)))), -1); } it('from sigmoid', () => { const x = tensor2d([[0.3, 0.7], [0.4, 0.6]], [2, 2]); const target = tensor2d([[0.25, 0.75], [0.1, 0.9]], [2, 2]); const expected = _binaryCrossentropy(target, x); const result = losses.binaryCrossentropy(target, x); expectTensorsClose(result, expected); }); }); describeMathCPUAndGPU('kullbackLeiblerDivergence', () => { function klElement(actual: number, predicted: number): number { actual = Math.max(actual, epsilon()); predicted = Math.max(predicted, epsilon()); return actual * Math.log(actual / predicted); } it('2D', () => { const yTrue = tensor2d([[1, 0], [1, 0]], [2, 2]); const yPred = tensor2d([[0.25, 0.75], [0.9, 0.1]], [2, 2]); const expectedVal = tensor1d([ klElement(1, 0.25) + klElement(0, 0.75), klElement(1, 0.9) + klElement(0, 0.1), ]); const result = losses.kullbackLeiblerDivergence(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('poisson', () => { function poissonElement(actual: number, predicted: number): number { return predicted - actual * Math.log(predicted + epsilon()); } it('2D', () => { const yTrue = tensor2d([[1, 0], [1, 0]], [2, 2]); const yPred = tensor2d([[0.25, 0.75], [0.9, 0.1]], [2, 2]); const expectedVal = tensor1d([ (poissonElement(1, 0.25) + poissonElement(0, 0.75)) / 2, (poissonElement(1, 0.9) + poissonElement(0, 0.1)) / 2, ]); const result = losses.poisson(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describeMathCPUAndGPU('cosineProximity', () => { it('2D', () => { const z = Math.sqrt(2) / 2; const yTrue = tensor2d([[1, 0], [1, 0]], [2, 2]); const yPred = tensor2d([[z, z], [0, 1]], [2, 2]); const expectedVal = tensor1d([-1 * z, 0]); const result = losses.cosineProximity(yTrue, yPred); expectTensorsClose(result, expectedVal); }); }); describe('losses get', () => { for (const lossName of ['meanSquaredError', 'meanAbsoluteError', 'meanAbsolutePercentageError', 'meanSquaredLogarithmicError', 'squaredHinge', 'hinge', 'categoricalHinge', 'logcosh', 'categoricalCrossentropy', 'sparseCategoricalCrossentropy', 'binaryCrossentropy', 'kullbackLeiblerDivergence', 'poisson', 'cosineProximity']) { it(`can get ${lossName}`, () => { losses.get(lossName); }); } it(`get custom loss works`, () => { const customLoss = (x: Tensor, y: Tensor) => scalar(42.0); expect(losses.get(customLoss)).toEqual(customLoss); }); }); describeMathCPUAndGPU('l2Normalize', () => { it('normalizes with no axis defined.', () => { const x = tensor2d([[1, 2], [3, 4]], [2, 2]); const norm = Math.sqrt(1 * 1 + 2 * 2 + 3 * 3 + 4 * 4); const expected = tensor2d([[1 / norm, 2 / norm], [3 / norm, 4 / norm]], [2, 2]); const result = losses.l2Normalize(x); expectTensorsClose(result, expected); }); it('normalizes along axis = -1.', () => { const x = tensor2d([[1, 2], [3, 4]], [2, 2]); const firstNorm = Math.sqrt(1 * 1 + 2 * 2); const secondNorm = Math.sqrt(3 * 3 + 4 * 4); const expected = tensor2d( [[1 / firstNorm, 2 / firstNorm], [3 / secondNorm, 4 / secondNorm]], [2, 2]); const result = losses.l2Normalize(x, -1); expectTensorsClose(result, expected); }); it('normalizes with zeros.', () => { const x = tfc.zeros([2, 2]); const result = losses.l2Normalize(x); expectTensorsClose(result, x); }); it('normalizes casts int32 as float32.', () => { const x = tensor2d([[1, 2], [3, 4]], [2, 2], 'int32'); const norm = Math.sqrt(1 * 1 + 2 * 2 + 3 * 3 + 4 * 4); const expected = tensor2d([[1 / norm, 2 / norm], [3 / norm, 4 / norm]], [2, 2]); const result = losses.l2Normalize(x); expectTensorsClose(result, expected); }); it('normalizes casts bool as float32.', () => { const x = tensor2d([[1, 1]], [1, 2], 'bool'); const norm = Math.sqrt(1 * 1 + 1 * 1); const expected = tensor2d([[1 / norm, 1 / norm]], [1, 2]); const result = losses.l2Normalize(x); expectTensorsClose(result, expected); }); });
the_stack
import { getContext2D } from "./canvas"; import { Color, Order } from "./enums"; import { DestinationRect, SourceRect, getImageData, setImageDataToCanvas, } from "./image_data"; import { loadImageByUrl, loadImageFromFileInput } from "./image_source"; /** * @protected */ function flatten<T>(arr: ArrayLike<T>): ArrayLike<T> { return arr instanceof Array ? Array.prototype.concat.apply( [], arr.map((arr) => flatten(arr)) ) : arr; } /** * @protected */ function normalizeBiasTuple(arr: number[] | number): number[] { if (typeof arr === "number") { return [arr, arr, arr, arr]; } if (arr.length == 4) { return [arr[0], arr[1], arr[2], arr[3]]; } else if (arr.length == 3) { return [arr[0], arr[1], arr[2], arr[0]]; } else if (arr.length == 1) { return [arr[0], arr[0], arr[0], arr[0]]; } throw new Error( "bias and scale must be scalar number or array of length 1 or 3 or 4." ); } /** * Option structure of [[webdnn/image.getImageArray|`WebDNN.Image.getImageArray`]] */ export interface ImageArrayOption { /** Type of packed array */ type?: { new (length: number): Float32Array | Int32Array }; /** The color format */ color?: Color; /** The data order */ order?: Order; /** Bias value, which is parsed based on [[webdnn/image.ImageArrayOption.order|`order`]] value */ bias?: number[] | number; /** Scale value, which is parsed based on [[webdnn/image.ImageArrayOption.order|`order`]] value */ scale?: number[] | number; } /** * Types which are drawable at `HTMLCanvasElement` */ export type Drawable = | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | ImageData; /** * All type of image source which `WebDNN.Image` can be handled. For `string`, only the url of image resource is valid. */ export type ImageSource = string | HTMLInputElement | Drawable; /** * Get image array as `{Float32 or Int32}ArrayBufferView` from ImageData object. * * @returns {ArrayBufferView} buffer with specified type * @protected */ export function getImageArrayFromImageData( imageData: ImageData, options: SourceRect & DestinationRect & ImageArrayOption = {} ): Float32Array | Int32Array { const { type = Float32Array, color = Color.RGB, order = Order.HWC, bias = [0, 0, 0], scale = [1, 1, 1], } = options, bias_n = normalizeBiasTuple(bias), scale_n = normalizeBiasTuple(scale), { width } = imageData, { height } = imageData, { data } = imageData; let array: Float32Array | Int32Array, biasA: number, biasB: number, biasG: number, biasR: number, scaleA: number, scaleB: number, scaleG: number, scaleR: number; switch (color) { case Color.RGB: array = new type(width * height * 3); [scaleR, scaleG, scaleB] = scale_n; [biasR, biasG, biasB] = bias_n; switch (order) { case Order.HWC: for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { array[(h * width + w) * 3 + 0] = (data[(h * width + w) * 4 + 0] - biasR) / scaleR; array[(h * width + w) * 3 + 1] = (data[(h * width + w) * 4 + 1] - biasG) / scaleG; array[(h * width + w) * 3 + 2] = (data[(h * width + w) * 4 + 2] - biasB) / scaleB; } } break; case Order.CHW: for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { array[(0 * height + h) * width + w] = (data[(h * width + w) * 4 + 0] - biasR) / scaleR; array[(Number(height) + h) * width + w] = (data[(h * width + w) * 4 + 1] - biasG) / scaleG; array[(2 * height + h) * width + w] = (data[(h * width + w) * 4 + 2] - biasB) / scaleB; } } break; } break; case Color.BGR: array = new type(width * height * 3); [biasR, biasG, biasB] = bias_n; [scaleR, scaleG, scaleB] = scale_n; switch (order) { case Order.HWC: for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { array[(h * width + w) * 3 + 0] = (data[(h * width + w) * 4 + 2] - biasB) / scaleB; array[(h * width + w) * 3 + 1] = (data[(h * width + w) * 4 + 1] - biasG) / scaleG; array[(h * width + w) * 3 + 2] = (data[(h * width + w) * 4 + 0] - biasR) / scaleR; } } break; case Order.CHW: for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { array[(0 * height + h) * width + w] = (data[(h * width + w) * 4 + 2] - biasB) / scaleB; array[(Number(height) + h) * width + w] = (data[(h * width + w) * 4 + 1] - biasG) / scaleG; array[(2 * height + h) * width + w] = (data[(h * width + w) * 4 + 0] - biasR) / scaleR; } } break; } break; case Color.RGBA: array = new type(width * height * 4); [scaleR, scaleG, scaleB, scaleA] = scale_n; [biasR, biasG, biasB, biasA] = bias_n; switch (order) { case Order.HWC: for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { array[(h * width + w) * 4 + 0] = (data[(h * width + w) * 4 + 0] - biasR) / scaleR; array[(h * width + w) * 4 + 1] = (data[(h * width + w) * 4 + 1] - biasG) / scaleG; array[(h * width + w) * 4 + 2] = (data[(h * width + w) * 4 + 2] - biasB) / scaleB; array[(h * width + w) * 4 + 3] = (data[(h * width + w) * 4 + 3] - biasA) / scaleA; } } break; case Order.CHW: for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { array[(0 * height + h) * width + w] = (data[(h * width + w) * 4 + 0] - biasR) / scaleR; array[(Number(height) + h) * width + w] = (data[(h * width + w) * 4 + 1] - biasG) / scaleG; array[(2 * height + h) * width + w] = (data[(h * width + w) * 4 + 2] - biasB) / scaleB; array[(3 * height + h) * width + w] = (data[(h * width + w) * 4 + 3] - biasA) / scaleA; } } break; } break; case Color.BGRA: array = new type(width * height * 4); [biasR, biasG, biasB, biasA] = bias_n; [scaleR, scaleG, scaleB, scaleA] = scale_n; switch (order) { case Order.HWC: for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { array[(h * width + w) * 4 + 0] = (data[(h * width + w) * 4 + 2] - biasB) / scaleB; array[(h * width + w) * 4 + 1] = (data[(h * width + w) * 4 + 1] - biasG) / scaleG; array[(h * width + w) * 4 + 2] = (data[(h * width + w) * 4 + 0] - biasR) / scaleR; array[(h * width + w) * 4 + 3] = (data[(h * width + w) * 4 + 3] - biasA) / scaleA; } } break; case Order.CHW: for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { array[(0 * height + h) * width + w] = (data[(h * width + w) * 4 + 2] - biasB) / scaleB; array[(Number(height) + h) * width + w] = (data[(h * width + w) * 4 + 1] - biasG) / scaleG; array[(2 * height + h) * width + w] = (data[(h * width + w) * 4 + 0] - biasR) / scaleR; array[(3 * height + h) * width + w] = (data[(h * width + w) * 4 + 3] - biasA) / scaleA; } } break; } break; case Color.GREY: array = new type(width * height); [scaleR, scaleG, scaleB] = scale_n; [biasR, biasG, biasB] = bias_n; for (let h = 0; h < height; h++) { for (let w = 0; w < width; w++) { const r = data[(h * width + w) * 4 + 0], g = data[(h * width + w) * 4 + 1], b = data[(h * width + w) * 4 + 2]; array[h * width + w] = (0.2126 * (r - biasR)) / scaleR + (0.7162 * (g - biasG)) / scaleG + (0.0722 * (b - biasB)) / scaleB; } } break; default: throw Error(`Unknown color format: ${color}`); } return array; } /** * Get image array from canvas element as `{Float32 or Int32}ArrayBufferView`. * * @returns {ImageData} buffer with specified type * @protected */ export function getImageArrayFromCanvas( canvas: HTMLCanvasElement, options: SourceRect & DestinationRect & ImageArrayOption = {} ): Float32Array | Int32Array { const { type = Float32Array, color = Color.RGB, order = Order.HWC, srcX = 0, srcY = 0, srcW = canvas.width, srcH = canvas.height, dstX = 0, dstY = 0, bias = [0, 0, 0], scale = [1, 1, 1], } = options, { dstW = srcW, dstH = srcH } = options, imageData = getImageData(canvas, { srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH, }); return getImageArrayFromImageData(imageData, { type, color, order, bias, scale, }); } /** * Get image array from image element as `{Float32 or Int32}ArrayBufferView`. * * @returns {ImageData} buffer with specified type * @protected */ export function getImageArrayFromDrawable( drawable: Drawable, options: SourceRect & DestinationRect & ImageArrayOption = {} ): Float32Array | Int32Array { let srcH: number, srcW: number; if (drawable instanceof HTMLVideoElement) { srcW = drawable.videoWidth; srcH = drawable.videoHeight; } else if (drawable instanceof HTMLImageElement) { srcW = drawable.naturalWidth; srcH = drawable.naturalHeight; } else if (drawable instanceof HTMLCanvasElement) { return getImageArrayFromCanvas(drawable, options); } else if (drawable instanceof ImageData) { const canvas = document.createElement("canvas"); canvas.height = drawable.height; canvas.width = drawable.width; const context = getContext2D(canvas); context.putImageData(drawable, 0, 0); return getImageArrayFromCanvas(canvas, options); } else throw TypeError( 'Failed to execute "getImageDataFromDrawable(drawable, options)": "drawable" must be an instanceof Drawable' ); const { type = Float32Array, color = Color.RGB, order = Order.HWC, srcX = 0, srcY = 0, dstX = 0, dstY = 0, dstW = srcW, dstH = srcH, bias = [0, 0, 0], scale = [1, 1, 1], } = options, canvas = document.createElement("canvas"); canvas.width = dstX + dstW; canvas.height = dstY + dstH; const context = getContext2D(canvas); context.drawImage(drawable, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH); return getImageArrayFromCanvas(canvas, { type, color, order, bias, scale }); } /** * Create typed array by packing image data from image source with specified options. * * First, this method loads specified image resource. The behavior of this method depends on the `image` argument. * * - If `image` is an instance of `string`, it will be regarded as image url, and this method fetches that url. * * - If `image` is an instance of `HTMLInputElement`, it will be regarded as file input, * and this method loads the selected image file. * * - Otherwise, `image` will be regarded as drawable object. * * Then, loaded images are packed into typed array based on `options` argument. * * - The image is cropped based on [[SourceRect|`{srcX, srcY, srcW, srcH}`]]. * As default, entire image is used. * * - The image is resized and translated into [[DestinationRect|`{dstX, dstY, dstW, dstH}`]]. * As default, no resize and translation is performed. * * - [[ImageArrayOption.type|`options.type`]] is the type of packed typed array. As default, Float32Array is used. * * - [[ImageArrayOption.type|`options.color`]] is the color format of packed typed array. As default, [[Color.RGB|`RGB`]] is used. * * - [[ImageArrayOption.type|`options.order`]] is the data order of packed typed array. As default, [[Order.HWC|`HWC`]] is used. * * - [[ImageArrayOption.bias|`options.bias`]] is the bias value. * If specified, this method **subtracts** this value from original pixel value. * * - [[ImageArrayOption.scale|`options.scale`]] is the scale value. If specified, original pixel values are **divided** by this value. * [[ImageArrayOption.scale|`options.scale`]] and [[ImageArrayOption.bias|`options.bias`]] is used for converting pixel value `x` and * packed value `y` as follows: * * - `y = (x - bias) / scale` * - `x = y * scale + bias` * - Note that color order is always RGB, not BGR. * * ### Examples * * - Load image of specified url * * ```ts * let image = await WebDNN.Image.load('./cat.png'); * ``` * * - Load image selected in file input and resize it into 224 x 224 * * ```ts * let input = document.querySelector('input[type=file]'); * let image = await WebDNN.Image.load(input, { dstW: 224, dstH: 224 }); * ``` * * - Load image data from canvas, normalize it into range `[-1, 1)`. In this case, normalized value `y` can be * calculated from pixel value `x` as follows: `y = (x - 128) / 128`. * * ```ts * let canvas = document.getElementsByTagName('canvas')[0]; * let image = await WebDNN.Image.load(canvas, { bias: [128, 128, 128], scale: [128, 128, 128] }); * ``` * * @param image please see above descriptions * @param options please see above descriptions. * @returns Created typed array */ export async function getImageArray( image: ImageSource, options: SourceRect & DestinationRect & ImageArrayOption = {} ): Promise<Float32Array | Int32Array> { if (typeof image === "string") { return getImageArrayFromDrawable(await loadImageByUrl(image), options); } else if (image instanceof HTMLInputElement) { return getImageArrayFromDrawable( await loadImageFromFileInput(image), options ); } else if (image instanceof HTMLCanvasElement) { return getImageArrayFromCanvas(image, options); } else if ( image instanceof HTMLImageElement || image instanceof HTMLVideoElement || image instanceof ImageData ) { return getImageArrayFromDrawable(image, options); /* * FIXME: This feature is not supported for all web browsers. * } else if (image === null) { * return getImageArrayFromDrawable(await loadImageByDialog(), options); */ } throw TypeError( 'Failed to execute "getImageData(image, options)": "image" must be an instance of string,' + " HTMLInputElement, HTMLCanvasElement, HTMLImageElement, HTMLVideoElement, or ImageData object" ); } function createImageData( array: Uint8ClampedArray, width: number, height: number ): ImageData { try { return new ImageData(array, width, height); } catch (e) { /* * FIXME: Removing this warning causes the following error. Maybe bug in webpack? * Uncaught (in promise) SyntaxError: Identifier 'n' has already been declared */ console.warn(`new ImageData failed: ${e}`); // IE11 does not support ImageData constructor const canvas_ = document.createElement("canvas"), context = getContext2D(canvas_), data = context.createImageData(width, height); data.data.set(array); return data; } } /** * Set image array data into canvas. * * ### Examples * * - Show DNN model's result * * ```ts * let runner = await WebDNN.load('./model'); * let output = runner.outputs[0]; * * await runner.run(); * * WebDNN.Image.setImageArrayToCanvas(output.toActual(), 256, 256, document.getElementById('canvas')) * ``` * * - Generally image generation model's result contains noise pixel at their edge because of convolution's padding. * In follow example, these noise are cut off. * * ```ts * WebDNN.Image.setImageArrayToCanvas(output, 256, 256, canvas, { * srcX: 16, srcY: 16, srcH: 256-16*2, srcW: 256-16*2, // Discard both ends 16px * dstW: 256, dstH: 256 // Resize cropped image into original output size. * }); * ``` * * @param array array which contains image data * @param imageW width of image * @param imageH height of image. The length of `array` must be `imageW * imageH * (# of channels)` * @param canvas destination canvas * @param options please see above descriptions and descriptions in [[webdnn/image.getImageArray|getImageArray()]]. * `srcW` and `srcH` is ignored (overwritten by `imageW` and `imageH`). */ export function setImageArrayToCanvas( array: ArrayLike<number>, imageW: number, imageH: number, canvas: HTMLCanvasElement, options: SourceRect & DestinationRect & ImageArrayOption = {} ): void { const { color = Color.RGB, order = Order.HWC, srcX = 0, srcY = 0, dstX = 0, dstY = 0, dstW = canvas.width, dstH = canvas.height, bias = [0, 0, 0], scale = [1, 1, 1], } = options, bias_n = normalizeBiasTuple(bias), scale_n = normalizeBiasTuple(scale), srcW = imageW, srcH = imageH; array = flatten(array); const data = new Uint8ClampedArray(srcW * srcH * 4); let biasA: number, biasB: number, biasG: number, biasR: number, scaleA: number, scaleB: number, scaleG: number, scaleR: number; switch (color) { case Color.RGB: [biasR, biasG, biasB] = bias_n; [scaleR, scaleG, scaleB] = scale_n; switch (order) { case Order.HWC: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = array[(h * imageW + w) * 3 + 0] * scaleR + biasR; data[(h * imageW + w) * 4 + 1] = array[(h * imageW + w) * 3 + 1] * scaleG + biasG; data[(h * imageW + w) * 4 + 2] = array[(h * imageW + w) * 3 + 2] * scaleB + biasB; data[(h * imageW + w) * 4 + 3] = 255; } } break; case Order.CHW: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = array[(0 * imageH + h) * imageW + w] * scaleR + biasR; data[(h * imageW + w) * 4 + 1] = array[(Number(imageH) + h) * imageW + w] * scaleG + biasG; data[(h * imageW + w) * 4 + 2] = array[(2 * imageH + h) * imageW + w] * scaleB + biasB; data[(h * imageW + w) * 4 + 3] = 255; } } break; } break; case Color.BGR: [biasR, biasG, biasB] = bias_n; [scaleR, scaleG, scaleB] = scale_n; switch (order) { case Order.HWC: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = array[(h * imageW + w) * 3 + 2] * scaleR + biasR; data[(h * imageW + w) * 4 + 1] = array[(h * imageW + w) * 3 + 1] * scaleG + biasG; data[(h * imageW + w) * 4 + 2] = array[(h * imageW + w) * 3 + 0] * scaleB + biasB; data[(h * imageW + w) * 4 + 3] = 255; } } break; case Order.CHW: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = array[(2 * imageH + h) * imageW + w] * scaleR + biasR; data[(h * imageW + w) * 4 + 1] = array[(Number(imageH) + h) * imageW + w] * scaleG + biasG; data[(h * imageW + w) * 4 + 2] = array[(0 * imageH + h) * imageW + w] * scaleB + biasB; data[(h * imageW + w) * 4 + 3] = 255; } } break; } break; case Color.RGBA: [biasR, biasG, biasB, biasA] = bias_n; [scaleR, scaleG, scaleB, scaleA] = scale_n; switch (order) { case Order.HWC: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = array[(h * imageW + w) * 3 + 0] * scaleR + biasR; data[(h * imageW + w) * 4 + 1] = array[(h * imageW + w) * 3 + 1] * scaleG + biasG; data[(h * imageW + w) * 4 + 2] = array[(h * imageW + w) * 3 + 2] * scaleB + biasB; data[(h * imageW + w) * 4 + 3] = array[(h * imageW + w) * 3 + 3] * scaleA + biasA; } } break; case Order.CHW: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = array[(0 * imageH + h) * imageW + w] * scaleR + biasR; data[(h * imageW + w) * 4 + 1] = array[(Number(imageH) + h) * imageW + w] * scaleG + biasG; data[(h * imageW + w) * 4 + 2] = array[(2 * imageH + h) * imageW + w] * scaleB + biasB; data[(h * imageW + w) * 4 + 3] = array[(3 * imageH + h) * imageW + w] * scaleA + biasA; } } break; } break; case Color.BGRA: [biasR, biasG, biasB, biasA] = bias_n; [scaleR, scaleG, scaleB, scaleA] = scale_n; switch (order) { case Order.HWC: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = array[(h * imageW + w) * 4 + 2] * scaleR + biasR; data[(h * imageW + w) * 4 + 1] = array[(h * imageW + w) * 4 + 1] * scaleG + biasG; data[(h * imageW + w) * 4 + 2] = array[(h * imageW + w) * 4 + 0] * scaleB + biasB; data[(h * imageW + w) * 4 + 3] = array[(h * imageW + w) * 4 + 3] * scaleA + biasA; } } break; case Order.CHW: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = array[(2 * imageH + h) * imageW + w] * scaleR + biasR; data[(h * imageW + w) * 4 + 1] = array[(Number(imageH) + h) * imageW + w] * scaleG + biasG; data[(h * imageW + w) * 4 + 2] = array[(0 * imageH + h) * imageW + w] * scaleB + biasB; data[(h * imageW + w) * 4 + 3] = array[(3 * imageH + h) * imageW + w] * scaleA + biasA; } } break; } break; case Color.GREY: for (let h = srcY; h < srcY + srcH; h++) { for (let w = srcX; w < srcX + srcW; w++) { data[(h * imageW + w) * 4 + 0] = data[(h * imageW + w) * 4 + 1] = data[(h * imageW + w) * 4 + 2] = array[h * imageW + w] * scale_n[0] + bias_n[0]; data[(h * imageW + w) * 4 + 3] = 255; } } break; } setImageDataToCanvas(createImageData(data, srcW, srcH), canvas, { srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH, }); }
the_stack
import { Component, OnInit, OnDestroy, Optional, ViewChild, ElementRef } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { Params } from '@angular/router'; import { CoreCourse } from '@features/course/services/course'; import { CoreCourseModuleData } from '@features/course/services/course-helper'; import { CoreGradesHelper, CoreGradesMenuItem } from '@features/grades/services/grades-helper'; import { CoreUser, CoreUserProfile } from '@features/user/services/user'; import { CanLeave } from '@guards/can-leave'; import { IonContent, IonRefresher } from '@ionic/angular'; import { CoreNavigator } from '@services/navigator'; import { CoreSites } from '@services/sites'; import { CoreSync } from '@services/sync'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreTextUtils } from '@services/utils/text'; import { Translate } from '@singletons'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreForms } from '@singletons/form'; import { AddonModWorkshopAssessmentStrategyComponent } from '../../components/assessment-strategy/assessment-strategy'; import { AddonModWorkshopProvider, AddonModWorkshop, AddonModWorkshopPhase, AddonModWorkshopSubmissionChangedEventData, AddonModWorkshopAction, AddonModWorkshopData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, AddonModWorkshopAssessmentSavedChangedEventData, } from '../../services/workshop'; import { AddonModWorkshopHelper, AddonModWorkshopSubmissionAssessmentWithFormData, AddonModWorkshopSubmissionDataWithOfflineData, } from '../../services/workshop-helper'; import { AddonModWorkshopOffline } from '../../services/workshop-offline'; import { AddonModWorkshopSyncProvider, AddonModWorkshopAutoSyncData } from '../../services/workshop-sync'; /** * Page that displays a workshop submission. */ @Component({ selector: 'page-addon-mod-workshop-submission-page', templateUrl: 'submission.html', }) export class AddonModWorkshopSubmissionPage implements OnInit, OnDestroy, CanLeave { @ViewChild(AddonModWorkshopAssessmentStrategyComponent) assessmentStrategy?: AddonModWorkshopAssessmentStrategyComponent; @ViewChild('feedbackFormEl') formElement?: ElementRef; module!: CoreCourseModuleData; workshop!: AddonModWorkshopData; access!: AddonModWorkshopGetWorkshopAccessInformationWSResponse; assessment?: AddonModWorkshopSubmissionAssessmentWithFormData; submissionInfo!: AddonModWorkshopSubmissionDataWithOfflineData; profile?: CoreUserProfile; courseId!: number; submission?: AddonModWorkshopSubmissionDataWithOfflineData; title?: string; loaded = false; ownAssessment?: AddonModWorkshopSubmissionAssessmentWithFormData; strategy?: string; assessmentId?: number; assessmentUserId?: number; evaluate?: AddonWorkshopSubmissionEvaluateData; canAddFeedback = false; canEdit = false; canDelete = false; evaluationGrades: CoreGradesMenuItem[] = []; evaluateGradingByProfile?: CoreUserProfile; evaluateByProfile?: CoreUserProfile; feedbackForm: FormGroup; // The form group. submissionId!: number; protected workshopId!: number; protected currentUserId: number; protected userId?: number; protected siteId: string; protected originalEvaluation: Omit<AddonWorkshopSubmissionEvaluateData, 'grade'> & { grade: number | string} = { published: false, text: '', grade: '', }; protected hasOffline = false; protected component = AddonModWorkshopProvider.COMPONENT; protected forceLeave = false; protected obsAssessmentSaved: CoreEventObserver; protected syncObserver: CoreEventObserver; protected isDestroyed = false; protected fetchSuccess = false; constructor( protected fb: FormBuilder, @Optional() protected content: IonContent, ) { this.currentUserId = CoreSites.getCurrentSiteUserId(); this.siteId = CoreSites.getCurrentSiteId(); this.feedbackForm = new FormGroup({}); this.feedbackForm.addControl('published', this.fb.control('')); this.feedbackForm.addControl('grade', this.fb.control('')); this.feedbackForm.addControl('text', this.fb.control('')); this.obsAssessmentSaved = CoreEvents.on(AddonModWorkshopProvider.ASSESSMENT_SAVED, (data) => { this.eventReceived(data); }, this.siteId); // Refresh workshop on sync. this.syncObserver = CoreEvents.on(AddonModWorkshopSyncProvider.AUTO_SYNCED, (data) => { // Update just when all database is synced. this.eventReceived(data); }, this.siteId); } /** * Component being initialized. */ async ngOnInit(): Promise<void> { try { this.submissionId = CoreNavigator.getRequiredRouteNumberParam('submissionId'); this.module = CoreNavigator.getRequiredRouteParam<CoreCourseModuleData>('module'); this.workshop = CoreNavigator.getRequiredRouteParam<AddonModWorkshopData>('workshop'); this.access = CoreNavigator.getRequiredRouteParam<AddonModWorkshopGetWorkshopAccessInformationWSResponse>('access'); this.courseId = CoreNavigator.getRequiredRouteNumberParam('courseId'); this.profile = CoreNavigator.getRouteParam<CoreUserProfile>('profile'); this.submissionInfo = CoreNavigator.getRequiredRouteParam<AddonModWorkshopSubmissionDataWithOfflineData>('submission'); this.assessment = CoreNavigator.getRouteParam<AddonModWorkshopSubmissionAssessmentWithFormData>('assessment'); } catch (error) { CoreDomUtils.showErrorModal(error); CoreNavigator.back(); return; } this.title = this.module.name; this.workshopId = this.module.instance || this.workshop.id; this.userId = this.submissionInfo?.authorid; this.strategy = (this.assessment && this.assessment.strategy) || (this.workshop && this.workshop.strategy); this.assessmentId = this.assessment?.id; this.assessmentUserId = this.assessment?.reviewerid; await this.fetchSubmissionData(); this.logView(); } /** * Check if we can leave the page or not. * * @return Resolved if we can leave it, rejected if not. */ async canLeave(): Promise<boolean> { const assessmentHasChanged = this.assessmentStrategy?.hasDataChanged(); if (this.forceLeave || (!this.hasEvaluationChanged() && !assessmentHasChanged)) { return true; } // Show confirmation if some data has been modified. await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); CoreForms.triggerFormCancelledEvent(this.formElement, this.siteId); return true; } /** * Goto edit submission page. */ editSubmission(): void { const params: Params = { module: module, access: this.access, }; CoreNavigator.navigate(String(this.submissionId) + '/edit', params); } /** * Function called when we receive an event of submission changes. * * @param data Event data received. */ protected eventReceived(data: AddonModWorkshopAutoSyncData | AddonModWorkshopAssessmentSavedChangedEventData): void { if (this.workshopId === data.workshopId) { this.content?.scrollToTop(); this.loaded = false; this.refreshAllData(); } } /** * Fetch the submission data. * * @return Resolved when done. */ protected async fetchSubmissionData(): Promise<void> { try { this.submission = await AddonModWorkshopHelper.getSubmissionById(this.workshopId, this.submissionId, { cmId: this.module.id, }); const promises: Promise<void>[] = []; this.submission.grade = this.submissionInfo?.grade; this.submission.gradinggrade = this.submissionInfo?.gradinggrade; this.submission.gradeover = this.submissionInfo?.gradeover; this.userId = this.submission.authorid || this.userId; this.canEdit = this.currentUserId == this.userId && this.access.cansubmit && this.access.modifyingsubmissionallowed; this.canDelete = this.access.candeletesubmissions; this.canAddFeedback = !this.assessmentId && this.workshop.phase > AddonModWorkshopPhase.PHASE_ASSESSMENT && this.workshop.phase < AddonModWorkshopPhase.PHASE_CLOSED && this.access.canoverridegrades; this.ownAssessment = undefined; if (this.access.canviewallassessments) { // Get new data, different that came from stateParams. promises.push(AddonModWorkshop.getSubmissionAssessments(this.workshopId, this.submissionId, { cmId: this.module.id, }).then((subAssessments) => { // Only allow the student to delete their own submission if it's still editable and hasn't been assessed. if (this.canDelete) { this.canDelete = !subAssessments.length; } this.submissionInfo.reviewedby = subAssessments; this.submissionInfo.reviewedby.forEach((assessment) => { assessment = AddonModWorkshopHelper.realGradeValue(this.workshop, assessment); if (this.currentUserId == assessment.reviewerid) { this.ownAssessment = assessment; assessment.ownAssessment = true; } }); return; })); } else if (this.currentUserId == this.userId && this.assessmentId) { // Get new data, different that came from stateParams. promises.push(AddonModWorkshop.getAssessment(this.workshopId, this.assessmentId, { cmId: this.module.id, }).then((assessment) => { // Only allow the student to delete their own submission if it's still editable and hasn't been assessed. if (this.canDelete) { this.canDelete = !assessment; } this.submissionInfo.reviewedby = [this.parseAssessment(assessment)]; return; })); } else if (this.workshop.phase == AddonModWorkshopPhase.PHASE_CLOSED && this.userId == this.currentUserId) { const assessments = await AddonModWorkshop.getSubmissionAssessments(this.workshopId, this.submissionId, { cmId: this.module.id, }); this.submissionInfo.reviewedby = assessments.map((assessment) => this.parseAssessment(assessment)); } if (this.canAddFeedback || this.workshop.phase == AddonModWorkshopPhase.PHASE_CLOSED) { this.evaluate = { published: this.submission.published, text: this.submission.feedbackauthor || '', }; } if (this.canAddFeedback) { if (!this.isDestroyed) { // Block the workshop. CoreSync.blockOperation(this.component, this.workshopId); } const defaultGrade = Translate.instant('addon.mod_workshop.notoverridden'); promises.push(CoreGradesHelper.makeGradesMenu(this.workshop.grade || 0, undefined, defaultGrade, -1) .then(async (grades) => { this.evaluationGrades = grades; this.evaluate!.grade = { label: CoreGradesHelper.getGradeLabelFromValue(grades, this.submissionInfo.gradeover) || defaultGrade, value: this.submissionInfo.gradeover || -1, }; try { const offlineSubmission = await AddonModWorkshopOffline.getEvaluateSubmission(this.workshopId, this.submissionId); this.hasOffline = true; this.evaluate!.published = offlineSubmission.published; this.evaluate!.text = offlineSubmission.feedbacktext; this.evaluate!.grade = { label: CoreGradesHelper.getGradeLabelFromValue( grades, parseInt(offlineSubmission.gradeover, 10), ) || defaultGrade, value: offlineSubmission.gradeover || -1, }; } catch { // Ignore errors. this.hasOffline = false; } finally { this.originalEvaluation.published = this.evaluate!.published; this.originalEvaluation.text = this.evaluate!.text; this.originalEvaluation.grade = this.evaluate!.grade.value; this.feedbackForm.controls['published'].setValue(this.evaluate!.published); this.feedbackForm.controls['grade'].setValue(this.evaluate!.grade.value); this.feedbackForm.controls['text'].setValue(this.evaluate!.text); } return; })); } else if (this.workshop.phase == AddonModWorkshopPhase.PHASE_CLOSED && this.submission.gradeoverby && this.evaluate && this.evaluate.text) { promises.push(CoreUser.getProfile(this.submission.gradeoverby, this.courseId, true).then((profile) => { this.evaluateByProfile = profile; return; })); } if (this.assessment && !this.access.assessingallowed && this.assessment.feedbackreviewer && this.assessment.gradinggradeoverby) { promises.push(CoreUser.getProfile(this.assessment.gradinggradeoverby, this.courseId, true) .then((profile) => { this.evaluateGradingByProfile = profile; return; })); } await Promise.all(promises); const submissionsActions = await AddonModWorkshopOffline.getSubmissions(this.workshopId); this.submission = await AddonModWorkshopHelper.applyOfflineData(this.submission, submissionsActions); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); } finally { this.loaded = true; } } /** * Parse assessment to be shown. * * @param assessment Original assessment. * @return Parsed assessment. */ protected parseAssessment( assessment: AddonModWorkshopSubmissionAssessmentWithFormData, ): AddonModWorkshopSubmissionAssessmentWithFormData { assessment = AddonModWorkshopHelper.realGradeValue(this.workshop, assessment); if (this.currentUserId == assessment.reviewerid) { this.ownAssessment = assessment; assessment.ownAssessment = true; } return assessment; } /** * Force leaving the page, without checking for changes. */ protected forceLeavePage(): void { this.forceLeave = true; CoreNavigator.back(); } /** * Check if data has changed. * * @return True if changed, false otherwise. */ protected hasEvaluationChanged(): boolean { if (!this.loaded || !this.access.canoverridegrades) { return false; } const inputData = this.feedbackForm.value; if (this.originalEvaluation.published != inputData.published) { return true; } if (this.originalEvaluation.text != inputData.text) { return true; } if (this.originalEvaluation.grade != inputData.grade) { return true; } return false; } /** * Convenience function to refresh all the data. * * @return Resolved when done. */ protected async refreshAllData(): Promise<void> { const promises: Promise<void>[] = []; promises.push(AddonModWorkshop.invalidateSubmissionData(this.workshopId, this.submissionId)); promises.push(AddonModWorkshop.invalidateSubmissionsData(this.workshopId)); promises.push(AddonModWorkshop.invalidateSubmissionAssesmentsData(this.workshopId, this.submissionId)); if (this.assessmentId) { promises.push(AddonModWorkshop.invalidateAssessmentFormData(this.workshopId, this.assessmentId)); promises.push(AddonModWorkshop.invalidateAssessmentData(this.workshopId, this.assessmentId)); } if (this.assessmentUserId) { promises.push(AddonModWorkshop.invalidateReviewerAssesmentsData(this.workshopId, this.assessmentId)); } try { await Promise.all(promises); } finally { CoreEvents.trigger(AddonModWorkshopProvider.ASSESSMENT_INVALIDATED, null, this.siteId); await this.fetchSubmissionData(); this.logView(); } } /** * Pull to refresh. * * @param refresher Refresher. */ refreshSubmission(refresher: IonRefresher): void { if (this.loaded) { this.refreshAllData().finally(() => { refresher?.complete(); }); } } /** * Save the assessment. */ async saveAssessment(): Promise<void> { if (this.assessmentStrategy?.hasDataChanged()) { try { await this.assessmentStrategy.saveAssessment(); this.forceLeavePage(); } catch { // Error, stay on the page. } } else { // Nothing to save, just go back. this.forceLeavePage(); } } /** * Save the submission evaluation. */ async saveEvaluation(): Promise<void> { // Check if data has changed. if (this.hasEvaluationChanged()) { await this.sendEvaluation(); this.forceLeavePage(); } else { // Nothing to save, just go back. this.forceLeavePage(); } } /** * Sends the evaluation to be saved on the server. * * @return Resolved when done. */ protected async sendEvaluation(): Promise<void> { const modal = await CoreDomUtils.showModalLoading('core.sending', true); const inputData: { grade: number | string; text: string; published: boolean; } = this.feedbackForm.value; inputData.grade = inputData.grade >= 0 ? inputData.grade : ''; // Add some HTML to the message if needed. inputData.text = CoreTextUtils.formatHtmlLines(inputData.text); // Try to send it to server. try { const result = await AddonModWorkshop.evaluateSubmission( this.workshopId, this.submissionId, this.courseId, inputData.text, inputData.published, String(inputData.grade), ); CoreForms.triggerFormSubmittedEvent(this.formElement, !!result, this.siteId); await AddonModWorkshop.invalidateSubmissionData(this.workshopId, this.submissionId).finally(() => { const data: AddonModWorkshopSubmissionChangedEventData = { workshopId: this.workshopId, submissionId: this.submissionId, }; CoreEvents.trigger(AddonModWorkshopProvider.SUBMISSION_CHANGED, data, this.siteId); }); } catch (message) { CoreDomUtils.showErrorModalDefault(message, 'Cannot save submission evaluation'); } finally { modal.dismiss(); } } /** * Perform the submission delete action. */ async deleteSubmission(): Promise<void> { try { await CoreDomUtils.showDeleteConfirm('addon.mod_workshop.submissiondeleteconfirm'); } catch { return; } const modal = await CoreDomUtils.showModalLoading('core.deleting', true); let success = false; try { await AddonModWorkshop.deleteSubmission(this.workshopId, this.submissionId, this.courseId); success = true; await AddonModWorkshop.invalidateSubmissionData(this.workshopId, this.submissionId); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Cannot delete submission'); } finally { modal.dismiss(); if (success) { const data: AddonModWorkshopSubmissionChangedEventData = { workshopId: this.workshopId, submissionId: this.submissionId, }; CoreEvents.trigger(AddonModWorkshopProvider.SUBMISSION_CHANGED, data, this.siteId); this.forceLeavePage(); } } } /** * Undo the submission delete action. * * @return Resolved when done. */ async undoDeleteSubmission(): Promise<void> { await AddonModWorkshopOffline.deleteSubmissionAction( this.workshopId, AddonModWorkshopAction.DELETE, ).finally(async () => { const data: AddonModWorkshopSubmissionChangedEventData = { workshopId: this.workshopId, submissionId: this.submissionId, }; CoreEvents.trigger(AddonModWorkshopProvider.SUBMISSION_CHANGED, data, this.siteId); await this.refreshAllData(); }); } /** * Log submission viewed. */ protected async logView(): Promise<void> { if (this.fetchSuccess) { return; // Already done. } this.fetchSuccess = true; try { await AddonModWorkshop.logViewSubmission(this.submissionId, this.workshopId, this.workshop.name); CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata); } catch { // Ignore errors. } } /** * Component being destroyed. */ ngOnDestroy(): void { this.isDestroyed = true; this.syncObserver?.off(); this.obsAssessmentSaved?.off(); // Restore original back functions. CoreSync.unblockOperation(this.component, this.workshopId); } } type AddonWorkshopSubmissionEvaluateData = { published: boolean; text: string; grade?: CoreGradesMenuItem; };
the_stack
import arrayFrom from '../polyfills/arrayFrom.js'; import inspect from '../jsutils/inspect.js'; import memoize3 from '../jsutils/memoize3.js'; import invariant from '../jsutils/invariant.js'; import devAssert from '../jsutils/devAssert.js'; import isPromise from '../jsutils/isPromise.js'; import isObjectLike from '../jsutils/isObjectLike.js'; import isCollection from '../jsutils/isCollection.js'; import promiseReduce from '../jsutils/promiseReduce.js'; import promiseForObject from '../jsutils/promiseForObject.js'; import { addPath, pathToArray } from '../jsutils/Path.js'; import { GraphQLError } from '../error/GraphQLError.js'; import { locatedError } from '../error/locatedError.js'; import { Kind } from '../language/kinds.js'; import { assertValidSchema } from '../type/validate.js'; import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from '../type/introspection.js'; import { GraphQLIncludeDirective, GraphQLSkipDirective } from '../type/directives.js'; import { isObjectType, isAbstractType, isLeafType, isListType, isNonNullType } from '../type/definition.js'; import { typeFromAST } from '../utilities/typeFromAST.js'; import { getOperationRootType } from '../utilities/getOperationRootType.js'; import { getVariableValues, getArgumentValues, getDirectiveValues } from './values.js'; /** * Terminology * * "Definitions" are the generic name for top-level statements in the document. * Examples of this include: * 1) Operations (such as a query) * 2) Fragments * * "Operations" are a generic name for requests in the document. * Examples of this include: * 1) query, * 2) mutation * * "Selections" are the definitions that can appear legally and at * single level of the query. These include: * 1) field references e.g "a" * 2) fragment "spreads" e.g. "...c" * 3) inline fragment "spreads" e.g. "...on Type { a }" */ /** * Data that must be available at all points during query execution. * * Namely, schema of the type system that is currently executing, * and the fragments defined in the query document */ export function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver) { /* eslint-enable no-redeclare */ // Extract arguments from object args if provided. return arguments.length === 1 ? executeImpl(argsOrSchema) : executeImpl({ schema: argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver }); } function executeImpl(args) { const { schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver } = args; // If arguments are missing or incorrect, throw an error. assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, // a "Response" with only errors is returned. const exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, typeResolver); // Return early errors if execution context failed. if (Array.isArray(exeContext)) { return { errors: exeContext }; } // Return a Promise that will eventually resolve to the data described by // The "Response" section of the GraphQL specification. // // If errors are encountered while executing a GraphQL field, only that // field and its descendants will be omitted, and sibling fields will still // be executed. An execution which encounters errors will still result in a // resolved Promise. const data = executeOperation(exeContext, exeContext.operation, rootValue); return buildResponse(exeContext, data); } /** * Given a completed execution context and data, build the { errors, data } * response defined by the "Response" section of the GraphQL specification. */ function buildResponse(exeContext, data) { if (isPromise(data)) { return data.then(resolved => buildResponse(exeContext, resolved)); } return exeContext.errors.length === 0 ? { data } : { errors: exeContext.errors, data }; } /** * Essential assertions before executing to provide developer feedback for * improper use of the GraphQL library. * * @internal */ export function assertValidExecutionArguments(schema, document, rawVariableValues) { devAssert(document, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. assertValidSchema(schema); // Variables, if provided, must be an object. devAssert(rawVariableValues == null || isObjectLike(rawVariableValues), 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.'); } /** * Constructs a ExecutionContext object from the arguments passed to * execute, which we will pass throughout the other execution methods. * * Throws a GraphQLError if a valid execution context cannot be created. * * @internal */ export function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver, typeResolver) { let operation; const fragments = Object.create(null); for (const definition of document.definitions) { switch (definition.kind) { case Kind.OPERATION_DEFINITION: if (operationName == null) { if (operation !== undefined) { return [new GraphQLError('Must provide operation name if query contains multiple operations.')]; } operation = definition; } else if (definition.name?.value === operationName) { operation = definition; } break; case Kind.FRAGMENT_DEFINITION: fragments[definition.name.value] = definition; break; } } if (!operation) { if (operationName != null) { return [new GraphQLError(`Unknown operation named "${operationName}".`)]; } return [new GraphQLError('Must provide an operation.')]; } /* istanbul ignore next (See https://github.com/graphql/graphql-js/issues/2203) */ const variableDefinitions = operation.variableDefinitions ?? []; const coercedVariableValues = getVariableValues(schema, variableDefinitions, rawVariableValues ?? {}, { maxErrors: 50 }); if (coercedVariableValues.errors) { return coercedVariableValues.errors; } return { schema, fragments, rootValue, contextValue, operation, variableValues: coercedVariableValues.coerced, fieldResolver: fieldResolver ?? defaultFieldResolver, typeResolver: typeResolver ?? defaultTypeResolver, errors: [] }; } /** * Implements the "Evaluating operations" section of the spec. */ function executeOperation(exeContext, operation, rootValue) { const type = getOperationRootType(exeContext.schema, operation); const fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); const path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level, // at which point we still log the error and null the parent field, which // in this case is the entire response. // // Similar to completeValueCatchingError. try { const result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields); if (isPromise(result)) { return result.then(undefined, error => { exeContext.errors.push(error); return Promise.resolve(null); }); } return result; } catch (error) { exeContext.errors.push(error); return null; } } /** * Implements the "Evaluating selection sets" section of the spec * for "write" mode. */ function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { return promiseReduce(Object.keys(fields), (results, responseName) => { const fieldNodes = fields[responseName]; const fieldPath = addPath(path, responseName); const result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); if (result === undefined) { return results; } if (isPromise(result)) { return result.then(resolvedResult => { results[responseName] = resolvedResult; return results; }); } results[responseName] = result; return results; }, Object.create(null)); } /** * Implements the "Evaluating selection sets" section of the spec * for "read" mode. */ function executeFields(exeContext, parentType, sourceValue, path, fields) { const results = Object.create(null); let containsPromise = false; for (const responseName of Object.keys(fields)) { const fieldNodes = fields[responseName]; const fieldPath = addPath(path, responseName); const result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); if (result !== undefined) { results[responseName] = result; if (!containsPromise && isPromise(result)) { containsPromise = true; } } } // If there are no promises, we can just return the object if (!containsPromise) { return results; } // Otherwise, results is a map from field name to the result of resolving that // field, which is possibly a promise. Return a promise that will return this // same map, but with any promises replaced with the values they resolved to. return promiseForObject(results); } /** * Given a selectionSet, adds all of the fields in that selection to * the passed in map of fields, and returns it at the end. * * CollectFields requires the "runtime type" of an object. For a field which * returns an Interface or Union type, the "runtime type" will be the actual * Object type returned by that field. * * @internal */ export function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) { for (const selection of selectionSet.selections) { switch (selection.kind) { case Kind.FIELD: { if (!shouldIncludeNode(exeContext, selection)) { continue; } const name = getFieldEntryKey(selection); if (!fields[name]) { fields[name] = []; } fields[name].push(selection); break; } case Kind.INLINE_FRAGMENT: { if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) { continue; } collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames); break; } case Kind.FRAGMENT_SPREAD: { const fragName = selection.name.value; if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) { continue; } visitedFragmentNames[fragName] = true; const fragment = exeContext.fragments[fragName]; if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) { continue; } collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); break; } } } return fields; } /** * Determines if a field should be included based on the @include and @skip * directives, where @skip has higher precedence than @include. */ function shouldIncludeNode(exeContext, node) { const skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues); if (skip?.if === true) { return false; } const include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues); if (include?.if === false) { return false; } return true; } /** * Determines if a fragment is applicable to the given type. */ function doesFragmentConditionMatch(exeContext, fragment, type) { const typeConditionNode = fragment.typeCondition; if (!typeConditionNode) { return true; } const conditionalType = typeFromAST(exeContext.schema, typeConditionNode); if (conditionalType === type) { return true; } if (isAbstractType(conditionalType)) { return exeContext.schema.isSubType(conditionalType, type); } return false; } /** * Implements the logic to compute the key of a given field's entry */ function getFieldEntryKey(node) { return node.alias ? node.alias.value : node.name.value; } /** * Resolves the field on the given source object. In particular, this * figures out the value that the field returns by calling its resolve function, * then calls completeValue to complete promises, serialize scalars, or execute * the sub-selection-set for objects. */ function resolveField(exeContext, parentType, source, fieldNodes, path) { const fieldNode = fieldNodes[0]; const fieldName = fieldNode.name.value; const fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); if (!fieldDef) { return; } const resolveFn = fieldDef.resolve ?? exeContext.fieldResolver; const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal // or abrupt (error). const result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info); return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result); } /** * @internal */ export function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { // The resolve function's optional fourth argument is a collection of // information about the current execution state. return { fieldName: fieldDef.name, fieldNodes, returnType: fieldDef.type, parentType, path, schema: exeContext.schema, fragments: exeContext.fragments, rootValue: exeContext.rootValue, operation: exeContext.operation, variableValues: exeContext.variableValues }; } /** * Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` * function. Returns the result of resolveFn or the abrupt-return Error object. * * @internal */ export function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) { try { // Build a JS object of arguments from the field.arguments AST, using the // variables scope to fulfill any variable references. // TODO: find a way to memoize, in case this field is within a List type. const args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that // is provided to every resolve function within an execution. It is commonly // used to represent an authenticated user, or request-specific caches. const contextValue = exeContext.contextValue; const result = resolveFn(source, args, contextValue, info); return isPromise(result) ? result.then(undefined, asErrorInstance) : result; } catch (error) { return asErrorInstance(error); } } // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a // consistent Error interface. function asErrorInstance(error) { if (error instanceof Error) { return error; } return new Error('Unexpected error value: ' + inspect(error)); } // This is a small wrapper around completeValue which detects and logs errors // in the execution context. function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) { try { let completed; if (isPromise(result)) { completed = result.then(resolved => completeValue(exeContext, returnType, fieldNodes, info, path, resolved)); } else { completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); } if (isPromise(completed)) { // Note: we don't rely on a `catch` method, but we do expect "thenable" // to take a second callback for the error case. return completed.then(undefined, error => handleFieldError(error, fieldNodes, path, returnType, exeContext)); } return completed; } catch (error) { return handleFieldError(error, fieldNodes, path, returnType, exeContext); } } function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) { const error = locatedError(asErrorInstance(rawError), fieldNodes, pathToArray(path)); // If the field type is non-nullable, then it is resolved without any // protection from errors, however it still properly locates the error. if (isNonNullType(returnType)) { throw error; } // Otherwise, error protection is applied, logging the error and resolving // a null value for this field if one is encountered. exeContext.errors.push(error); return null; } /** * Implements the instructions for completeValue as defined in the * "Field entries" section of the spec. * * If the field type is Non-Null, then this recursively completes the value * for the inner type. It throws a field error if that completion returns null, * as per the "Nullability" section of the spec. * * If the field type is a List, then this recursively completes the value * for the inner type on each item in the list. * * If the field type is a Scalar or Enum, ensures the completed value is a legal * value of the type by calling the `serialize` method of GraphQL type * definition. * * If the field is an abstract type, determine the runtime type of the value * and then complete based on that type * * Otherwise, the field type expects a sub-selection set, and will complete the * value by evaluating all sub-selections. */ function completeValue(exeContext, returnType, fieldNodes, info, path, result) { // If result is an Error, throw a located error. if (result instanceof Error) { throw result; } // If field type is NonNull, complete for inner type, and throw field error // if result is null. if (isNonNullType(returnType)) { const completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); if (completed === null) { throw new Error(`Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`); } return completed; } // If result value is null or undefined then return null. if (result == null) { return null; } // If field type is List, complete each item in the list with the inner type if (isListType(returnType)) { return completeListValue(exeContext, returnType, fieldNodes, info, path, result); } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, // returning null if serialization is not possible. if (isLeafType(returnType)) { return completeLeafValue(returnType, result); } // If field type is an abstract type, Interface or Union, determine the // runtime Object type and complete for that type. if (isAbstractType(returnType)) { return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); } // If field type is Object, execute and complete all sub-selections. if (isObjectType(returnType)) { return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); } // Not reachable. All possible output types have been considered. invariant(false, 'Cannot complete value of unexpected output type: ' + inspect(returnType)); } /** * Complete a list value by completing each item in the list with the * inner type */ function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { if (!isCollection(result)) { throw new GraphQLError(`Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`); } // This is specified as a simple map, however we're optimizing the path // where the list contains no Promises by avoiding creating another Promise. const itemType = returnType.ofType; let containsPromise = false; const completedResults = arrayFrom(result, (item, index) => { // No need to modify the info object containing the path, // since from here on it is not ever accessed by resolver functions. const fieldPath = addPath(path, index); const completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item); if (!containsPromise && isPromise(completedItem)) { containsPromise = true; } return completedItem; }); return containsPromise ? Promise.all(completedResults) : completedResults; } /** * Complete a Scalar or Enum by serializing to a valid value, returning * null if serialization is not possible. */ function completeLeafValue(returnType, result) { const serializedResult = returnType.serialize(result); if (serializedResult === undefined) { throw new Error(`Expected a value of type "${inspect(returnType)}" but ` + `received: ${inspect(result)}`); } return serializedResult; } /** * Complete a value of an abstract type by determining the runtime object type * of that value, then complete the value for that type. */ function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { const resolveTypeFn = returnType.resolveType ?? exeContext.typeResolver; const contextValue = exeContext.contextValue; const runtimeType = resolveTypeFn(result, contextValue, info, returnType); if (isPromise(runtimeType)) { return runtimeType.then(resolvedRuntimeType => completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result)); } return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); } function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) { const runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName; if (!isObjectType(runtimeType)) { throw new GraphQLError(`Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + `value ${inspect(result)}, received "${inspect(runtimeType)}". ` + `Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, fieldNodes); } if (!exeContext.schema.isSubType(returnType, runtimeType)) { throw new GraphQLError(`Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, fieldNodes); } return runtimeType; } /** * Complete an Object value by executing all sub-selections. */ function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { // If there is an isTypeOf predicate function, call it with the // current result. If isTypeOf returns false, then raise an error rather // than continuing execution. if (returnType.isTypeOf) { const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); if (isPromise(isTypeOf)) { return isTypeOf.then(resolvedIsTypeOf => { if (!resolvedIsTypeOf) { throw invalidReturnTypeError(returnType, result, fieldNodes); } return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); }); } if (!isTypeOf) { throw invalidReturnTypeError(returnType, result, fieldNodes); } } return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); } function invalidReturnTypeError(returnType, result, fieldNodes) { return new GraphQLError(`Expected value of type "${returnType.name}" but got: ${inspect(result)}.`, fieldNodes); } function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) { // Collect sub-fields to execute to complete this value. const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); return executeFields(exeContext, returnType, result, path, subFieldNodes); } /** * A memoized collection of relevant subfields with regard to the return * type. Memoizing ensures the subfields are not repeatedly calculated, which * saves overhead when resolving lists of values. */ const collectSubfields = memoize3(_collectSubfields); function _collectSubfields(exeContext, returnType, fieldNodes) { let subFieldNodes = Object.create(null); const visitedFragmentNames = Object.create(null); for (const node of fieldNodes) { if (node.selectionSet) { subFieldNodes = collectFields(exeContext, returnType, node.selectionSet, subFieldNodes, visitedFragmentNames); } } return subFieldNodes; } /** * If a resolveType function is not given, then a default resolve behavior is * used which attempts two strategies: * * First, See if the provided value has a `__typename` field defined, if so, use * that value as name of the resolved type. * * Otherwise, test each possible type for the abstract type by calling * isTypeOf for the object being coerced, returning the first type that matches. */ export const defaultTypeResolver = function (value, contextValue, info, abstractType) { // First, look for `__typename`. if (isObjectLike(value) && typeof value.__typename === 'string') { return value.__typename; } // Otherwise, test each possible type. const possibleTypes = info.schema.getPossibleTypes(abstractType); const promisedIsTypeOfResults = []; for (let i = 0; i < possibleTypes.length; i++) { const type = possibleTypes[i]; if (type.isTypeOf) { const isTypeOfResult = type.isTypeOf(value, contextValue, info); if (isPromise(isTypeOfResult)) { promisedIsTypeOfResults[i] = isTypeOfResult; } else if (isTypeOfResult) { return type; } } } if (promisedIsTypeOfResults.length) { return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => { for (let i = 0; i < isTypeOfResults.length; i++) { if (isTypeOfResults[i]) { return possibleTypes[i]; } } }); } }; /** * If a resolve function is not given, then a default resolve behavior is used * which takes the property of the source object of the same name as the field * and returns it as the result, or if it's a function, returns the result * of calling that function while passing along args and context value. */ export const defaultFieldResolver = function (source, args, contextValue, info) { // ensure source is a value for which property access is acceptable. if (isObjectLike(source) || typeof source === 'function') { const property = source[info.fieldName]; if (typeof property === 'function') { return source[info.fieldName](args, contextValue, info); } return property; } }; /** * This method looks up the field on the given type definition. * It has special casing for the two introspection fields, __schema * and __typename. __typename is special because it can always be * queried as a field, even in situations where no other fields * are allowed, like on a Union. __schema could get automatically * added to the query type, but that would require mutating type * definitions, which would cause issues. * * @internal */ export function getFieldDef(schema, parentType, fieldName) { if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { return SchemaMetaFieldDef; } else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { return TypeMetaFieldDef; } else if (fieldName === TypeNameMetaFieldDef.name) { return TypeNameMetaFieldDef; } return parentType.getFields()[fieldName]; }
the_stack
import { ResourceCollection, Service, ServiceAccount, ClusterRole, ClusterRoleBinding, Deployment, Role, RoleBinding, V1ServicemonitorResource } from "@opstrace/kubernetes"; import { KubeConfig } from "@kubernetes/client-node"; import { DockerImages, getImagePullSecrets } from "@opstrace/controller-config"; export function KubeStateMetricsResources( kubeConfig: KubeConfig, namespace: string ): ResourceCollection { const collection = new ResourceCollection(); collection.add( new V1ServicemonitorResource( { apiVersion: "monitoring.coreos.com/v1", kind: "ServiceMonitor", metadata: { labels: { "k8s-app": "kube-state-metrics", tenant: "system" }, name: "kube-state-metrics", namespace }, spec: { endpoints: [ { bearerTokenFile: "/var/run/secrets/kubernetes.io/serviceaccount/token", honorLabels: true, interval: "30s", port: "https-main", scheme: "https", scrapeTimeout: "30s", tlsConfig: { insecureSkipVerify: true } }, { bearerTokenFile: "/var/run/secrets/kubernetes.io/serviceaccount/token", interval: "30s", port: "https-self", scheme: "https", tlsConfig: { insecureSkipVerify: true } } ], jobLabel: "k8s-app", selector: { matchLabels: { "k8s-app": "kube-state-metrics" } } } }, kubeConfig ) ); collection.add( new ServiceAccount( { apiVersion: "v1", kind: "ServiceAccount", metadata: { name: "kube-state-metrics", namespace } }, kubeConfig ) ); collection.add( new Service( { apiVersion: "v1", kind: "Service", metadata: { labels: { "k8s-app": "kube-state-metrics" }, name: "kube-state-metrics", namespace }, spec: { clusterIP: "None", ports: [ { name: "https-main", port: 8443, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: "https-main" as any }, { name: "https-self", port: 9443, // eslint-disable-next-line @typescript-eslint/no-explicit-any targetPort: "https-self" as any } ], selector: { app: "kube-state-metrics" } } }, kubeConfig ) ); collection.add( new Deployment( { apiVersion: "apps/v1", kind: "Deployment", metadata: { labels: { app: "kube-state-metrics" }, name: "kube-state-metrics", namespace }, spec: { replicas: 1, selector: { matchLabels: { app: "kube-state-metrics" } }, template: { metadata: { labels: { app: "kube-state-metrics" } }, spec: { imagePullSecrets: getImagePullSecrets(), containers: [ { args: [ "--logtostderr", "--secure-listen-address=:8443", "--tls-cipher-suites=TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "--upstream=http://127.0.0.1:8081/" ], image: DockerImages.kubeRBACProxy, name: "kube-rbac-proxy-main", ports: [ { containerPort: 8443, name: "https-main" } ], resources: { limits: { cpu: "1000m", memory: "40Mi" }, requests: { cpu: "50m", memory: "20Mi" } } }, { args: [ "--logtostderr", "--secure-listen-address=:9443", "--tls-cipher-suites=TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "--upstream=http://127.0.0.1:8082/" ], image: DockerImages.kubeRBACProxy, name: "kube-rbac-proxy-self", ports: [ { containerPort: 9443, name: "https-self" } ], resources: { limits: { cpu: "500m", memory: "40Mi" }, requests: { cpu: "50m", memory: "20Mi" } } }, { args: [ "--host=127.0.0.1", "--port=8081", "--telemetry-host=127.0.0.1", "--telemetry-port=8082" ], image: DockerImages.kubeStateMetrics, name: "kube-state-metrics", resources: { limits: { cpu: "200m", memory: "150Mi" }, requests: { cpu: "50m", memory: "100Mi" } } }, { command: [ "/pod_nanny", "--container=kube-state-metrics", "--cpu=200m", "--extra-cpu=2m", "--memory=150Mi", "--extra-memory=30Mi", "--threshold=5", "--deployment=kube-state-metrics" ], env: [ { name: "MY_POD_NAME", valueFrom: { fieldRef: { apiVersion: "v1", fieldPath: "metadata.name" } } }, { name: "MY_POD_NAMESPACE", valueFrom: { fieldRef: { apiVersion: "v1", fieldPath: "metadata.namespace" } } } ], image: DockerImages.addonResizer, name: "addon-resizer", resources: { limits: { cpu: "250m", memory: "30Mi" }, requests: { cpu: "50m", memory: "30Mi" } } } ], nodeSelector: { "kubernetes.io/os": "linux" }, securityContext: { runAsNonRoot: true, runAsUser: 65534 }, serviceAccountName: "kube-state-metrics" } } } }, kubeConfig ) ); collection.add( new Role( { apiVersion: "rbac.authorization.k8s.io/v1", kind: "Role", metadata: { name: "kube-state-metrics", namespace }, rules: [ { apiGroups: [""], resources: ["pods"], verbs: ["get"] }, { apiGroups: ["extensions"], resourceNames: ["kube-state-metrics"], resources: ["deployments"], verbs: ["get", "update"] }, { apiGroups: ["apps"], resourceNames: ["kube-state-metrics"], resources: ["deployments"], verbs: ["get", "update"] } ] }, kubeConfig ) ); collection.add( new RoleBinding( { apiVersion: "rbac.authorization.k8s.io/v1", kind: "RoleBinding", metadata: { name: "kube-state-metrics", namespace }, roleRef: { apiGroup: "rbac.authorization.k8s.io", kind: "Role", name: "kube-state-metrics" }, subjects: [ { kind: "ServiceAccount", name: "kube-state-metrics", namespace } ] }, kubeConfig ) ); collection.add( new ClusterRoleBinding( { apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRoleBinding", metadata: { name: "kube-state-metrics" }, roleRef: { apiGroup: "rbac.authorization.k8s.io", kind: "ClusterRole", name: "kube-state-metrics" }, subjects: [ { kind: "ServiceAccount", name: "kube-state-metrics", namespace } ] }, kubeConfig ) ); collection.add( new ClusterRole( { apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRole", metadata: { name: "kube-state-metrics" }, rules: [ { apiGroups: [""], resources: [ "configmaps", "secrets", "nodes", "pods", "services", "resourcequotas", "replicationcontrollers", "limitranges", "persistentvolumeclaims", "persistentvolumes", "namespaces", "endpoints" ], verbs: ["list", "watch"] }, { apiGroups: ["extensions"], resources: [ "daemonsets", "deployments", "replicasets", "ingresses" ], verbs: ["list", "watch"] }, { apiGroups: ["apps"], resources: [ "statefulsets", "daemonsets", "deployments", "replicasets" ], verbs: ["list", "watch"] }, { apiGroups: ["batch"], resources: ["cronjobs", "jobs"], verbs: ["list", "watch"] }, { apiGroups: ["autoscaling"], resources: ["horizontalpodautoscalers"], verbs: ["list", "watch"] }, { apiGroups: ["authentication.k8s.io"], resources: ["tokenreviews"], verbs: ["create"] }, { apiGroups: ["authorization.k8s.io"], resources: ["subjectaccessreviews"], verbs: ["create"] }, { apiGroups: ["policy"], resources: ["poddisruptionbudgets"], verbs: ["list", "watch"] }, { apiGroups: ["certificates.k8s.io"], resources: ["certificatesigningrequests"], verbs: ["list", "watch"] }, { apiGroups: ["storage.k8s.io"], resources: ["storageclasses"], verbs: ["list", "watch"] } ] }, kubeConfig ) ); return collection; }
the_stack
declare const describe: any; declare const it: any; declare const expect: any; import * as Immutable from "immutable"; import * as moment from "moment"; import Moment = moment.Moment; import { collection, Collection } from "../src/collection"; import { duration } from "../src/duration"; import { event, indexedEvent, timeEvent, timeRangeEvent } from "../src/event"; import { avg, max, sum } from "../src/functions"; import { index, Index } from "../src/index"; import { time, Time } from "../src/time"; import { timerange } from "../src/timerange"; import { indexedSeries, timeRangeSeries, TimeSeries, timeSeries, TimeSeriesWireFormat } from "../src/timeseries"; import { TimeAlignment } from "../src/types"; import { window } from "../src/window"; const EVENT_DATA = { name: "avg temps", events: Immutable.List([ event(time("2015-04-22T03:30:00Z"), Immutable.Map({ in: 1, out: 2 })), event(time("2015-04-22T03:31:00Z"), Immutable.Map({ in: 3, out: 4 })) ]) }; const COLLECTION_DATA = { name: "avg coll", collection: collection( Immutable.List([ event(time("2015-04-22T02:30:00Z"), Immutable.Map({ a: 5, b: 6 })), event(time("2015-04-22T03:30:00Z"), Immutable.Map({ a: 4, b: 2 })) ]) ) }; const TIMESERIES_TEST_DATA = { name: "traffic", columns: ["time", "value", "status"], points: [ [1400425947000, 52, "ok"], [1400425948000, 18, "ok"], [1400425949000, 26, "fail"], [1400425950000, 93, "offline"] ] }; const AVAILABILITY_DATA = { name: "availability", columns: ["index", "uptime"], points: [ ["2014-07", "100%"], ["2014-08", "88%"], ["2014-09", "95%"], ["2014-10", "99%"], ["2014-11", "91%"], ["2014-12", "99%"], ["2015-01", "100%"], ["2015-02", "92%"], ["2015-03", "99%"], ["2015-04", "87%"], ["2015-05", "92%"], ["2015-06", "100%"] ] }; const AVAILABILITY_DATA_2 = { name: "availability", columns: ["index", "uptime", "notes", "outages"], points: [ ["2014-07", 100, "", 2], ["2014-08", 88, "", 17], ["2014-09", 95, "", 6], ["2014-10", 99, "", 3], ["2014-11", 91, "", 14], ["2014-12", 99, "", 3], ["2015-01", 100, "", 0], ["2015-02", 92, "", 12], ["2015-03", 99, "Minor outage March 2", 4], ["2015-04", 87, "Planned downtime in April", 82], ["2015-05", 92, "Router failure June 12", 26], ["2015-06", 100, "", 0] ] }; const INDEXED_DATA = { index: "1d-625", name: "traffic", columns: ["time", "value", "status"], points: [ [1400425947000, 52, "ok"], [1400425948000, 18, "ok"], [1400425949000, 26, "fail"], [1400425950000, 93, "offline"] ] }; const INTERFACE_TEST_DATA = { name: "star-cr5:to_anl_ip-a_v4", description: "star-cr5->anl(as683):100ge:site-ex:show:intercloud", device: "star-cr5", id: 169, interface: "to_anl_ip-a_v4", is_ipv6: false, is_oscars: false, oscars_id: null, resource_uri: "", site: "anl", site_device: "noni", site_interface: "et-1/0/0", stats_type: "Standard", title: null, columns: ["time", "in", "out"], points: [ [1400425947000, 52, 34], [1400425948000, 18, 13], [1400425949000, 26, 67], [1400425950000, 93, 91] ] }; const fmt = "YYYY-MM-DD HH:mm"; const BISECT_TEST_DATA = { name: "test", columns: ["time", "value"], points: [ [moment("2012-01-11 01:00", fmt).valueOf(), 22], [moment("2012-01-11 02:00", fmt).valueOf(), 33], [moment("2012-01-11 03:00", fmt).valueOf(), 44], [moment("2012-01-11 04:00", fmt).valueOf(), 55], [moment("2012-01-11 05:00", fmt).valueOf(), 66], [moment("2012-01-11 06:00", fmt).valueOf(), 77], [moment("2012-01-11 07:00", fmt).valueOf(), 88] ] }; const TRAFFIC_DATA_IN = { name: "star-cr5:to_anl_ip-a_v4", columns: ["time", "in"], points: [[1400425947000, 52], [1400425948000, 18], [1400425949000, 26], [1400425950000, 93]] }; const TRAFFIC_DATA_OUT = { name: "star-cr5:to_anl_ip-a_v4", columns: ["time", "out"], points: [[1400425947000, 34], [1400425948000, 13], [1400425949000, 67], [1400425950000, 91]] }; const PARTIAL_TRAFFIC_PART_A = { name: "star-cr5:to_anl_ip-a_v4", columns: ["time", "value"], points: [[1400425947000, 34], [1400425948000, 13], [1400425949000, 67], [1400425950000, 91]] }; const PARTIAL_TRAFFIC_PART_B = { name: "star-cr5:to_anl_ip-a_v4", columns: ["time", "value"], points: [[1400425951000, 65], [1400425952000, 86], [1400425953000, 27], [1400425954000, 72]] }; const TRAFFIC_BNL_TO_NEWY = { name: "BNL to NEWY", columns: ["time", "in"], points: [ [1441051950000, 2998846524.2666664], [1441051980000, 2682032885.3333335], [1441052010000, 2753537586.9333334] ] }; const TRAFFIC_NEWY_TO_BNL = { name: "NEWY to BNL", columns: ["time", "out"], points: [ [1441051950000, 22034579982.4], [1441051980000, 24783871443.2], [1441052010000, 26907368572.800003] ] }; const sumPart1 = { name: "part1", columns: ["time", "in", "out"], points: [ [1400425951000, 1, 6], [1400425952000, 2, 7], [1400425953000, 3, 8], [1400425954000, 4, 9] ] }; const sumPart2 = { name: "part2", columns: ["time", "in", "out"], points: [ [1400425951000, 9, 1], [1400425952000, 7, 2], [1400425953000, 5, 3], [1400425954000, 3, 4] ] }; const sept2014Data = { utc: false, name: "traffic", columns: ["time", "value"], points: [ [1409529600000, 80], [1409533200000, 88], [1409536800000, 52], [1409540400000, 80], [1409544000000, 26], [1409547600000, 37], [1409551200000, 6], [1409554800000, 32], [1409558400000, 69], [1409562000000, 21], [1409565600000, 6], [1409569200000, 54], [1409572800000, 88], [1409576400000, 41], [1409580000000, 35], [1409583600000, 43], [1409587200000, 84], [1409590800000, 32], [1409594400000, 41], [1409598000000, 57], [1409601600000, 27], [1409605200000, 50], [1409608800000, 13], [1409612400000, 63], [1409616000000, 58], [1409619600000, 80], [1409623200000, 59], [1409626800000, 96], [1409630400000, 2], [1409634000000, 20], [1409637600000, 64], [1409641200000, 7], [1409644800000, 50], [1409648400000, 88], [1409652000000, 34], [1409655600000, 31], [1409659200000, 16], [1409662800000, 38], [1409666400000, 94], [1409670000000, 78], [1409673600000, 86], [1409677200000, 13], [1409680800000, 34], [1409684400000, 29], [1409688000000, 48], [1409691600000, 80], [1409695200000, 30], [1409698800000, 15], [1409702400000, 62], [1409706000000, 66], [1409709600000, 44], [1409713200000, 94], [1409716800000, 78], [1409720400000, 29], [1409724000000, 21], [1409727600000, 4], [1409731200000, 83], [1409734800000, 15], [1409738400000, 89], [1409742000000, 53], [1409745600000, 70], [1409749200000, 41], [1409752800000, 47], [1409756400000, 30], [1409760000000, 68], [1409763600000, 89], [1409767200000, 29], [1409770800000, 17], [1409774400000, 38], [1409778000000, 67], [1409781600000, 75], [1409785200000, 89], [1409788800000, 47], [1409792400000, 82], [1409796000000, 33], [1409799600000, 67], [1409803200000, 93], [1409806800000, 86], [1409810400000, 97], [1409814000000, 19], [1409817600000, 19], [1409821200000, 31], [1409824800000, 56], [1409828400000, 19], [1409832000000, 43], [1409835600000, 29], [1409839200000, 72], [1409842800000, 27], [1409846400000, 21], [1409850000000, 88], [1409853600000, 18], [1409857200000, 30], [1409860800000, 46], [1409864400000, 34], [1409868000000, 31], [1409871600000, 20], [1409875200000, 45], [1409878800000, 17], [1409882400000, 24], [1409886000000, 84], [1409889600000, 6], [1409893200000, 91], [1409896800000, 82], [1409900400000, 71], [1409904000000, 97], [1409907600000, 43], [1409911200000, 38], [1409914800000, 1], [1409918400000, 71], [1409922000000, 50], [1409925600000, 19], [1409929200000, 19], [1409932800000, 86], [1409936400000, 65], [1409940000000, 93], [1409943600000, 35] ] }; const OUTAGE_EVENT_LIST = Immutable.List([ { startTime: "2015-03-04T09:00:00Z", endTime: "2015-03-04T14:00:00Z", title: "ANL Scheduled Maintenance", description: "ANL will be switching border routers...", completed: true, external_ticket: "", esnet_ticket: "ESNET-20150302-002", organization: "ANL", type: "Planned" }, { startTime: "2015-04-22T03:30:00Z", endTime: "2015-04-22T13:00:00Z", description: "At 13:33 pacific circuit 06519 went down.", title: "STAR-CR5 < 100 ge 06519 > ANL - Outage", completed: true, external_ticket: "", esnet_ticket: "ESNET-20150421-013", organization: "Internet2 / Level 3", type: "Unplanned" }, { startTime: "2015-04-22T03:35:00Z", endTime: "2015-04-22T16:50:00Z", title: "STAR-CR5 < 100 ge 06519 > ANL - Outage", description: "The listed circuit was unavailable due to bent pins.", completed: true, external_ticket: "3576:144", esnet_ticket: "ESNET-20150421-013", organization: "Internet2 / Level 3", type: "Unplanned" } ]); const TIMERANGE_EVENT_LIST = OUTAGE_EVENT_LIST.map(evt => { const { startTime, endTime, ...other } = evt; const b = new Date(startTime); const e = new Date(endTime); return timeRangeEvent(timerange(b, e), Immutable.Map(other as {})); }); const weather = Immutable.List([ { date: "2014-7-1", actual_mean_temp: 81, actual_min_temp: 72, actual_max_temp: 89, average_min_temp: 68, average_max_temp: 83, record_min_temp: 52, record_max_temp: 100, record_min_temp_year: 1943, record_max_temp_year: 1901, actual_precipitation: 0, average_precipitation: 0.12, record_precipitation: 2.17 }, { date: "2014-7-2", actual_mean_temp: 82, actual_min_temp: 72, actual_max_temp: 91, average_min_temp: 68, average_max_temp: 83, record_min_temp: 56, record_max_temp: 100, record_min_temp_year: 2001, record_max_temp_year: 1966, actual_precipitation: 0.96, average_precipitation: 0.13, record_precipitation: 1.79 }, { date: "2014-7-3", actual_mean_temp: 78, actual_min_temp: 69, actual_max_temp: 87, average_min_temp: 68, average_max_temp: 83, record_min_temp: 54, record_max_temp: 103, record_min_temp_year: 1933, record_max_temp_year: 1966, actual_precipitation: 1.78, average_precipitation: 0.12, record_precipitation: 2.8 } ]); describe("Creation", () => { it("can create a series with a list of events", () => { const series = new TimeSeries(EVENT_DATA); expect(series).toBeDefined(); }); it("can create a series with a collection", () => { const series = new TimeSeries(COLLECTION_DATA); expect(series).toBeDefined(); }); it("can create a timeseries with our wire format", () => { const series = timeSeries(TIMESERIES_TEST_DATA); expect(series).toBeDefined(); }); it("can create an indexed series with our wire format", () => { const series = indexedSeries(AVAILABILITY_DATA); expect(series).toBeDefined(); }); it("can create an series with a list of Events", () => { const events = []; events.push(timeEvent(time(new Date(2015, 7, 1)), Immutable.Map({ value: 27 }))); events.push(timeEvent(time(new Date(2015, 8, 1)), Immutable.Map({ value: 14 }))); const series = new TimeSeries({ name: "events", events: Immutable.List(events) }); expect(series.size()).toBe(2); }); it("can create an series with a list of Indexed Events", () => { const events = weather.map(item => { const { date, actual_min_temp, actual_max_temp, record_min_temp, record_max_temp } = item; return indexedEvent( index(date), Immutable.Map({ temp: [ +record_min_temp, // tslint-disable-line +actual_min_temp, // tslint-disable-line +actual_max_temp, // tslint-disable-line +record_max_temp // tslint-disable-line ] }) ); }); const c = new Collection(events); const series = new TimeSeries({ name, collection: c }); expect(series.size()).toBe(3); }); it("can create an series with no events", () => { const events = []; const series = new TimeSeries({ name: "events", events: Immutable.List(events) }); expect(series.size()).toBe(0); }); it("can create a timerange series with the right timerange", () => { const series = new TimeSeries({ name: "outages", events: TIMERANGE_EVENT_LIST }); expect(series.range().toString()).toBe('{"timerange":[1425459600000,1429721400000]}'); }); }); describe("Basic Query API", () => { // tslint:disable:max-line-length it("can return the size of the series", () => { const series = timeSeries(TIMESERIES_TEST_DATA); expect(series.size()).toBe(4); }); it("can return an item in the series as an event", () => { const series = timeSeries(TIMESERIES_TEST_DATA); const e = series.at(1); expect(e.keyType()).toBe("time"); }); it("can return an item in the series with the correct data", () => { const series = timeSeries(TIMESERIES_TEST_DATA); const e = series.at(1); expect(JSON.stringify(e.getData())).toBe(`{"value":18,"status":"ok"}`); expect(e.timestamp().getTime()).toBe(1400425948000); }); it("can serialize to a string", () => { const series = timeSeries(TIMESERIES_TEST_DATA); const expectedString = `{"name":"traffic","tz":"Etc/UTC","columns":["time","value","status"],"points":[[1400425947000,52,"ok"],[1400425948000,18,"ok"],[1400425949000,26,"fail"],[1400425950000,93,"offline"]]}`; expect(series.toString()).toBe(expectedString); }); it("can return the time range of the series", () => { const series = timeSeries(TIMESERIES_TEST_DATA); const expectedString = "[Sun, 18 May 2014 15:12:27 GMT, Sun, 18 May 2014 15:12:30 GMT]"; expect(series.timerange().toUTCString()).toBe(expectedString); }); }); describe("Meta Data", () => { it("can create a series with meta data and get that data back", () => { const series = timeSeries(INTERFACE_TEST_DATA); const expected = `{"site_interface":"et-1/0/0","tz":"Etc/UTC","site":"anl","name":"star-cr5:to_anl_ip-a_v4","site_device":"noni","device":"star-cr5","oscars_id":null,"title":null,"is_oscars":false,"interface":"to_anl_ip-a_v4","stats_type":"Standard","id":169,"resource_uri":"","is_ipv6":false,"description":"star-cr5->anl(as683):100ge:site-ex:show:intercloud","columns":["time","in","out"],"points":[[1400425947000,52,34],[1400425948000,18,13],[1400425949000,26,67],[1400425950000,93,91]]}`; expect(series.toString()).toBe(expected); expect(series.meta("interface")).toBe("to_anl_ip-a_v4"); }); it("can create a series and set a new name", () => { const series = timeSeries(INTERFACE_TEST_DATA); expect(series.name()).toBe("star-cr5:to_anl_ip-a_v4"); const newSeries = series.setName("bob"); expect(newSeries.name()).toBe("bob"); }); it("can create a series with meta data and get that data back", () => { const series = timeSeries(INTERFACE_TEST_DATA); expect(series.meta("site_interface")).toBe("et-1/0/0"); const newSeries = series.setMeta("site_interface", "bob"); expect(newSeries.meta("site_interface")).toBe("bob"); expect(newSeries.at(0).get("in")).toBe(52); expect(newSeries.meta("site")).toBe("anl"); }); }); describe("Deep Event Data", () => { it("can create a series with a nested object", () => { const series = timeSeries({ name: "Map Traffic", columns: ["time", "NASA_north", "NASA_south"], points: [ [1400425951000, { in: 100, out: 200 }, { in: 145, out: 135 }], [1400425952000, { in: 200, out: 400 }, { in: 146, out: 142 }], [1400425953000, { in: 300, out: 600 }, { in: 147, out: 158 }], [1400425954000, { in: 400, out: 800 }, { in: 155, out: 175 }] ] }); expect( series .at(0) .get("NASA_north") .get("in") ).toBe(100); expect( series .at(0) .get("NASA_north") .get("out") ).toBe(200); expect(series.at(0).get("NASA_north.in")).toBe(100); expect(series.at(0).get(["NASA_north", "in"])).toBe(100); }); it("can create a series with nested events", () => { const events = []; events.push( timeEvent( time(new Date(2015, 6, 1)), Immutable.Map({ NASA_north: { in: 100, out: 200 }, NASA_south: { in: 145, out: 135 } }) ) ); events.push( timeEvent( time(new Date(2015, 7, 1)), Immutable.Map({ NASA_north: { in: 200, out: 400 }, NASA_south: { in: 146, out: 142 } }) ) ); events.push( timeEvent( time(new Date(2015, 8, 1)), Immutable.Map({ NASA_north: { in: 300, out: 600 }, NASA_south: { in: 147, out: 158 } }) ) ); events.push( timeEvent( time(new Date(2015, 9, 1)), Immutable.Map({ NASA_north: { in: 400, out: 800 }, NASA_south: { in: 155, out: 175 } }) ) ); const series = new TimeSeries({ name: "Map traffic", events: Immutable.List(events) }); expect(series.at(0).get("NASA_north").in).toBe(100); expect(series.at(3).get("NASA_south").out).toBe(175); expect(series.size()).toBe(4); }); }); describe("Comparing TimeSeries", () => { it("can compare a series and a reference to a series as being equal", () => { const series = timeSeries(TIMESERIES_TEST_DATA); const refSeries = series; expect(series).toBe(refSeries); }); it("can use the equals() comparator to compare a series and a copy of the series as true", () => { const series = timeSeries(TIMESERIES_TEST_DATA); const copyOfSeries = new TimeSeries(series); expect(TimeSeries.equal(series, copyOfSeries)).toBeTruthy(); }); it("can use the equals() comparator to compare a series and a value equivalent series as false", () => { const series = timeSeries(TIMESERIES_TEST_DATA); const otherSeries = timeSeries(TIMESERIES_TEST_DATA); expect(TimeSeries.equal(series, otherSeries)).toBeFalsy(); }); it("can use the is() comparator to compare a series and a value equivalent series as true", () => { const series = timeSeries(TIMESERIES_TEST_DATA); const otherSeries = timeSeries(TIMESERIES_TEST_DATA); expect(TimeSeries.is(series, otherSeries)).toBeTruthy(); }); it("can use the is() comparator to compare a series and a value different series as false", () => { const series = timeSeries(sumPart1); const otherSeries = timeSeries(sumPart2); expect(TimeSeries.is(series, otherSeries)).toBeFalsy(); }); }); describe("Bisect", () => { it("can find the bisect starting from 0", () => { const series = timeSeries(BISECT_TEST_DATA); expect(series.bisect(moment("2012-01-11 00:30", fmt).toDate())).toBe(0); expect(series.bisect(moment("2012-01-11 03:00", fmt).toDate())).toBe(2); expect(series.bisect(moment("2012-01-11 03:30", fmt).toDate())).toBe(2); expect(series.bisect(moment("2012-01-11 08:00", fmt).toDate())).toBe(6); }); it("can find the bisect starting from an begin index", () => { const series = timeSeries(BISECT_TEST_DATA); expect(series.bisect(moment("2012-01-11 03:00", fmt).toDate(), 2)).toBe(2); expect(series.bisect(moment("2012-01-11 03:30", fmt).toDate(), 3)).toBe(2); expect(series.bisect(moment("2012-01-11 03:30", fmt).toDate(), 4)).toBe(3); const first = series.bisect(moment("2012-01-11 03:30", fmt).toDate()); const second = series.bisect(moment("2012-01-11 04:30", fmt).toDate(), first); expect(series.at(first).get()).toBe(44); expect(series.at(second).get()).toBe(55); }); }); describe("Time Range Events", () => { it("can make a timeseries with the right timerange", () => { const series = new TimeSeries({ name: "outages", events: TIMERANGE_EVENT_LIST }); expect(series.range().toString()).toBe('{"timerange":[1425459600000,1429721400000]}'); }); it("can make a timeseries that can be serialized to a string", () => { const series = new TimeSeries({ name: "outages", events: TIMERANGE_EVENT_LIST }); const expected = `{"name":"outages","tz":"Etc/UTC","columns":["timerange","title","description","completed","external_ticket","esnet_ticket","organization","type"],"points":[[[1425459600000,1425477600000],"ANL Scheduled Maintenance","ANL will be switching border routers...",true,"","ESNET-20150302-002","ANL","Planned"],[[1429673400000,1429707600000],"STAR-CR5 < 100 ge 06519 > ANL - Outage","At 13:33 pacific circuit 06519 went down.",true,"","ESNET-20150421-013","Internet2 / Level 3","Unplanned"],[[1429673700000,1429721400000],"STAR-CR5 < 100 ge 06519 > ANL - Outage","The listed circuit was unavailable due to bent pins.",true,"3576:144","ESNET-20150421-013","Internet2 / Level 3","Unplanned"]]}`; expect(series.toString()).toBe(expected); }); it("can make a timeseries that can be serialized to JSON and then used to construct a TimeSeries again", () => { const series = new TimeSeries({ name: "outages", events: TIMERANGE_EVENT_LIST }); const newSeries = timeRangeSeries(series.toJSON() as TimeSeriesWireFormat); expect(series.toString()).toBe(newSeries.toString()); }); }); describe("Indexed Events", () => { it("can serialize to a string", () => { const series = timeSeries(INDEXED_DATA); const expectedString = `{"index":"1d-625","name":"traffic","tz":"Etc/UTC","columns":["time","value","status"],"points":[[1400425947000,52,"ok"],[1400425948000,18,"ok"],[1400425949000,26,"fail"],[1400425950000,93,"offline"]]}`; expect(series.toString()).toBe(expectedString); }); it("can return the time range of the series", () => { const series = timeSeries(INDEXED_DATA); const expectedString = "[Sat, 18 Sep 1971 00:00:00 GMT, Sun, 19 Sep 1971 00:00:00 GMT]"; expect(series.indexAsRange().toUTCString()).toBe(expectedString); }); it("can create an series with indexed data (in UTC time)", () => { const series = indexedSeries(AVAILABILITY_DATA); const e = series.at(2); expect(e.timerangeAsUTCString()).toBe( "[Mon, 01 Sep 2014 00:00:00 GMT, Tue, 30 Sep 2014 23:59:59 GMT]" ); expect( series .range() .begin() .getTime() ).toBe(1404172800000); expect( series .range() .end() .getTime() ).toBe(1435708799999); }); }); describe("Slicing a timeseries", () => { it("can create a slice of a series", () => { const series = indexedSeries(AVAILABILITY_DATA); const expectedLastTwo = `{"name":"availability","tz":"Etc/UTC","columns":["index","uptime"],"points":[["2015-05","92%"],["2015-06","100%"]]}`; const lastTwo = series.slice(-2); expect(lastTwo.toString()).toBe(expectedLastTwo); const expectedFirstThree = `{"name":"availability","tz":"Etc/UTC","columns":["index","uptime"],"points":[["2014-07","100%"],["2014-08","88%"],["2014-09","95%"]]}`; const firstThree = series.slice(0, 3); expect(firstThree.toString()).toBe(expectedFirstThree); const expectedAll = `{"name":"availability","tz":"Etc/UTC","columns":["index","uptime"],"points":[["2014-07","100%"],["2014-08","88%"],["2014-09","95%"],["2014-10","99%"],["2014-11","91%"],["2014-12","99%"],["2015-01","100%"],["2015-02","92%"],["2015-03","99%"],["2015-04","87%"],["2015-05","92%"],["2015-06","100%"]]}`; const sliceAll = series.slice(); expect(sliceAll.toString()).toBe(expectedAll); }); }); describe("Cropping a timeseries", () => { it("can create crop a series", () => { const series = timeSeries({ name: "exact timestamps", columns: ["time", "value"], points: [ [1504014065240, 1], [1504014065243, 2], [1504014065244, 3], [1504014065245, 4], [1504014065249, 5] ] }); const ts1 = series.crop(timerange(1504014065243, 1504014065245)); expect(ts1.size()).toBe(3); const ts2 = series.crop(timerange(1504014065242, 1504014065245)); expect(ts2.size()).toBe(3); const ts3 = series.crop(timerange(1504014065243, 1504014065247)); expect(ts3.size()).toBe(3); const ts4 = series.crop(timerange(1504014065242, 1504014065247)); expect(ts4.size()).toBe(3); }); }); describe("Merging two timeseries together", () => { it("can merge two timeseries columns together using merge", () => { const inTraffic = timeSeries(TRAFFIC_DATA_IN); const outTraffic = timeSeries(TRAFFIC_DATA_OUT); const trafficSeries = TimeSeries.timeSeriesListMerge<Time>({ name: "traffic", seriesList: [inTraffic, outTraffic], fieldSpec: ["in", "out"] }); expect(trafficSeries.at(2).get("in")).toBe(26); expect(trafficSeries.at(2).get("out")).toBe(67); }); it("can append two timeseries together using merge", () => { const tile1 = timeSeries(PARTIAL_TRAFFIC_PART_A); const tile2 = timeSeries(PARTIAL_TRAFFIC_PART_B); const trafficSeries = TimeSeries.timeSeriesListMerge<Time>({ name: "traffic", source: "router", seriesList: [tile1, tile2], fieldSpec: "value" }); expect(trafficSeries.size()).toBe(8); expect(trafficSeries.at(0).get()).toBe(34); expect(trafficSeries.at(1).get()).toBe(13); expect(trafficSeries.at(2).get()).toBe(67); expect(trafficSeries.at(3).get()).toBe(91); expect(trafficSeries.at(4).get()).toBe(65); expect(trafficSeries.at(5).get()).toBe(86); expect(trafficSeries.at(6).get()).toBe(27); expect(trafficSeries.at(7).get()).toBe(72); expect(trafficSeries.name()).toBe("traffic"); expect(trafficSeries.meta("source")).toBe("router"); }); it("can merge two series and preserve the correct time format", () => { const inTraffic = timeSeries(TRAFFIC_BNL_TO_NEWY); const outTraffic = timeSeries(TRAFFIC_NEWY_TO_BNL); const trafficSeries = TimeSeries.timeSeriesListMerge<Time>({ name: "traffic", seriesList: [inTraffic, outTraffic] }); expect(trafficSeries.at(0).timestampAsUTCString()).toBe("Mon, 31 Aug 2015 20:12:30 GMT"); expect(trafficSeries.at(1).timestampAsUTCString()).toBe("Mon, 31 Aug 2015 20:13:00 GMT"); expect(trafficSeries.at(2).timestampAsUTCString()).toBe("Mon, 31 Aug 2015 20:13:30 GMT"); }); it("can merge two irregular time series together", () => { const A = { name: "a", columns: ["time", "valueA"], points: [ [1400425947000, 34], [1400425948000, 13], [1400425949000, 67], [1400425950000, 91] ] }; const B = { name: "b", columns: ["time", "valueB"], points: [ [1400425951000, 65], [1400425952000, 86], [1400425953000, 27], [1400425954000, 72] ] }; const tile1 = timeSeries(A); const tile2 = timeSeries(B); const series = TimeSeries.timeSeriesListMerge({ name: "traffic", seriesList: [tile1, tile2] }); // console.log("series is ", series); const expected = `{"name":"traffic","tz":"Etc/UTC","columns":["time","valueA","valueB"],"points":[[1400425947000,34,null],[1400425948000,13,null],[1400425949000,67,null],[1400425950000,91,null],[1400425951000,null,65],[1400425952000,null,86],[1400425953000,null,27],[1400425954000,null,72]]}`; expect(series.toString()).toBe(expected); }); }); describe("Summing two timeseries together", () => { it("can merge two timeseries into a new timeseries that is the sum", () => { const part1 = timeSeries(sumPart1); const part2 = timeSeries(sumPart2); const result = TimeSeries.timeSeriesListReduce({ name: "sum", seriesList: [part1, part2], reducer: sum(), fieldSpec: ["in", "out"] }); // 10, 9, 8, 7 expect(result.at(0).get("in")).toBe(10); expect(result.at(1).get("in")).toBe(9); expect(result.at(2).get("in")).toBe(8); expect(result.at(3).get("in")).toBe(7); // 7, 9, 11, 13 expect(result.at(0).get("out")).toBe(7); expect(result.at(1).get("out")).toBe(9); expect(result.at(2).get("out")).toBe(11); expect(result.at(3).get("out")).toBe(13); }); }); describe("Averaging two timeseries together", () => { it("can merge two timeseries into a new timeseries that is the sum", () => { const part1 = timeSeries({ name: "part1", columns: ["time", "in", "out"], points: [ [1400425951000, 1, 6], [1400425952000, 2, 7], [1400425953000, 3, 8], [1400425954000, 4, 9] ] }); const part2 = timeSeries({ name: "part2", columns: ["time", "in", "out"], points: [ [1400425951000, 9, 1], [1400425952000, 7, 2], [1400425953000, 5, 3], [1400425954000, 3, 4] ] }); const avgSeries = TimeSeries.timeSeriesListReduce({ name: "avg", seriesList: [part1, part2], fieldSpec: ["in", "out"], reducer: avg() }); expect(avgSeries.at(0).get("in")).toBe(5); expect(avgSeries.at(1).get("in")).toBe(4.5); expect(avgSeries.at(2).get("in")).toBe(4); expect(avgSeries.at(3).get("in")).toBe(3.5); expect(avgSeries.at(0).get("out")).toBe(3.5); expect(avgSeries.at(1).get("out")).toBe(4.5); expect(avgSeries.at(2).get("out")).toBe(5.5); expect(avgSeries.at(3).get("out")).toBe(6.5); const avgSeries2 = TimeSeries.timeSeriesListReduce({ name: "avg", seriesList: [part1, part2], reducer: avg(), fieldSpec: ["in", "out"] }); expect(avgSeries2.at(0).get("in")).toBe(5); expect(avgSeries2.at(1).get("in")).toBe(4.5); expect(avgSeries2.at(2).get("in")).toBe(4); expect(avgSeries2.at(3).get("in")).toBe(3.5); }); }); describe("Collapsing down columns in a timeseries", () => { it("can collapse a timeseries into a new timeseries that is the sum of two columns", () => { const ts = timeSeries(sumPart1); const sums = ts.collapse({ fieldName: "sum", fieldSpecList: ["in", "out"], reducer: sum(), append: false }); expect(sums.at(0).get("sum")).toBe(7); expect(sums.at(1).get("sum")).toBe(9); expect(sums.at(2).get("sum")).toBe(11); expect(sums.at(3).get("sum")).toBe(13); }); it("can collapse a timeseries into a new timeseries that is the max of two columns", () => { const timeseries = timeSeries(sumPart2); const c = timeseries.collapse({ fieldName: "max_in_out", fieldSpecList: ["in", "out"], reducer: max(), append: true }); expect(c.at(0).get("max_in_out")).toBe(9); expect(c.at(1).get("max_in_out")).toBe(7); expect(c.at(2).get("max_in_out")).toBe(5); expect(c.at(3).get("max_in_out")).toBe(4); }); it("can collapse a timeseries into a new timeseries that is the sum of two columns, then find the max", () => { const ts = timeSeries(sumPart1); const sums = ts.collapse({ fieldName: "value", fieldSpecList: ["in", "out"], reducer: sum(), append: false }); expect(sums.max("value")).toBe(13); }); }); describe("Select specific columns in a TimeSeries", () => { it("can select a single column from a TimeSeries", () => { const timeseries = timeSeries(INTERFACE_TEST_DATA); expect(timeseries.columns()).toEqual(["in", "out"]); const ts = timeseries.select({ fields: ["in"] }); expect(ts.columns()).toEqual(["in"]); expect(ts.name()).toBe("star-cr5:to_anl_ip-a_v4"); }); it("can select multiple columns from a TimeSeries", () => { const timeseries = indexedSeries(AVAILABILITY_DATA_2); expect(timeseries.columns()).toEqual(["uptime", "notes", "outages"]); const ts = timeseries.select({ fields: ["uptime", "notes"] }); expect(ts.columns()).toEqual(["uptime", "notes"]); expect(ts.name()).toBe("availability"); }); it("can rename columns", () => { const ts = timeSeries(sumPart1); const newTs = ts.renameColumns({ renameMap: { in: "new_in", out: "new_out" } }); expect(newTs.columns()).toEqual(["new_in", "new_out"]); const series = indexedSeries(AVAILABILITY_DATA); const newSeries = series.renameColumns({ renameMap: { uptime: "new_uptime" } }); expect(newSeries.columns()).toEqual(["new_uptime"]); }); }); describe("Remapping Events in a TimeSeries", () => { it("can use re-mapping to reverse the values in a TimeSeries", () => { const timeseries = timeSeries(INTERFACE_TEST_DATA); expect(timeseries.columns()).toEqual(["in", "out"]); const ts = timeseries.map(e => e.setData(Immutable.Map({ in: e.get("out"), out: e.get("in") })) ); expect(ts.at(0).get("in")).toBe(34); expect(ts.at(0).get("out")).toBe(52); expect(ts.size()).toBe(timeseries.size()); }); it("can run a flat map over the TimeSeries", () => { const series = timeSeries({ name: "Map Traffic", columns: ["time", "NASA_north", "NASA_south"], points: [ [1400425951000, { in: 100, out: 200 }, { in: 145, out: 135 }], [1400425952000, { in: 200, out: 400 }, { in: 146, out: 142 }], [1400425953000, { in: 300, out: 600 }, { in: 147, out: 158 }], [1400425954000, { in: 400, out: 800 }, { in: 155, out: 175, other: 1 }] ] }); const split = series.flatMap(e => Immutable.List([e.setData(e.get("NASA_north")), e.setData(e.get("NASA_south"))]) ); expect(split.size()).toBe(8); expect(split.at(0).get("in")).toBe(100); expect(split.at(0).get("out")).toBe(200); expect(split.at(0).get("other")).toBeUndefined(); expect(split.at(1).get("in")).toBe(145); expect(split.at(1).get("out")).toBe(135); expect(split.at(1).get("other")).toBeUndefined(); expect(split.at(7).get("in")).toBe(155); expect(split.at(7).get("out")).toBe(175); expect(split.at(7).get("other")).toBe(1); }); it("can remap keys of a TimeSeries using mapKeys() from times to timeranges", () => { const series = timeSeries({ name: "series", columns: ["time", "a", "b"], points: [ [1400425951000, 100, 200], [1400425952000, 300, 400], [1400425953000, 800, 900] ] }); const remapped = series.mapKeys(t => t.toTimeRange(duration("5m"), TimeAlignment.Middle)); expect(remapped.size()).toBe(3); expect( remapped .at(0) .getKey() .duration() ).toBe(1000 * 60 * 5); expect( remapped .at(0) .getKey() .mid() .getTime() ).toBe(1400425951000); expect(remapped.at(0).get("a")).toBe(100); expect(remapped.at(0).get("b")).toBe(200); }); it("can remap keys of a TimeSeries using mapKeys() from indexes to times", () => { const series = indexedSeries({ name: "series", columns: ["index", "c", "d"], points: [["1d-1234", 100, 200], ["1d-1235", 300, 400], ["1d-1236", 800, 900]] }); const remapped = series.mapKeys<Time>((idx: Index) => idx.toTime(TimeAlignment.End)); expect( remapped .at(0) .getKey() .timestamp() .getTime() ).toBe(106704000000); expect(remapped.at(0).get("c")).toBe(100); expect(remapped.at(0).get("d")).toBe(200); }); }); describe("Rollups", () => { it("can generate 1 day fixed window averages over a TimeSeries", () => { const timeseries = timeSeries(sept2014Data); const everyDay = window(duration("1d")); const dailyAvg = timeseries.fixedWindowRollup({ window: everyDay, aggregation: { value: ["value", avg()] } }); expect(dailyAvg.size()).toBe(5); expect(dailyAvg.at(0).get()).toBe(46.875); expect(dailyAvg.at(2).get()).toBe(54.083333333333336); expect(dailyAvg.at(4).get()).toBe(51.85); }); it("can make Collections for each day in the TimeSeries", () => { const timeseries = timeSeries(sept2014Data); const eachDay = window(duration("1d")); const collections = timeseries.collectByWindow({ window: eachDay }); expect(collections["1d-16314"].size()).toBe(24); expect(collections["1d-16318"].size()).toBe(20); }); it("can correctly use atTime()", () => { const t = new Date(1476803711641); let c = new Collection(); c = c.addEvent(event(time(t), Immutable.Map({ value: 2 }))); // Test bisect to get element 0 const ts = new TimeSeries({ name: "coll", collection: c }); const bisect = ts.bisect(t); expect(bisect).toEqual(0); expect(ts.at(bisect).get()).toEqual(2); // Test atTime to get element 0 expect(ts.atTime(t).get()).toEqual(2); }); });
the_stack
import type { byte, Card, Restorable } from '../types'; import { debug, toHex } from '../util'; import { rom as readOnlyRom } from '../roms/cards/cffa'; import { read2MGHeader } from '../formats/2mg'; import { ProDOSVolume } from '../formats/prodos'; import createBlockDisk from '../formats/block'; import { dump } from '../formats/prodos/utils'; import { BlockDisk, BlockFormat, ENCODING_BLOCK, MassStorage, } from 'js/formats/types'; const rom = new Uint8Array(readOnlyRom); const COMMANDS = { ATACRead: 0x20, ATACWrite: 0x30, ATAIdentify: 0xEC }; // CFFA Card Settings const SETTINGS = { Max32MBPartitionsDev0: 0x800, Max32MBPartitionsDev1: 0x801, DefaultBootDevice: 0x802, DefaultBootPartition: 0x803, Reserved: 0x804, // 4 bytes WriteProtectBits: 0x808, MenuSnagMask: 0x809, MenuSnagKey: 0x80A, BootTimeDelayTenths: 0x80B, BusResetSeconds: 0x80C, CheckDeviceTenths: 0x80D, ConfigOptionBits: 0x80E, BlockOffsetDev0: 0x80F, // 3 bytes BlockOffsetDev1: 0x812, // 3 bytes Unused: 0x815 }; // CFFA ATA Register Locations const LOC = { ATADataHigh: 0x80, SetCSMask: 0x81, ClearCSMask: 0x82, WriteEEPROM: 0x83, NoWriteEEPROM: 0x84, ATADevCtrl: 0x86, ATAAltStatus: 0x86, ATADataLow: 0x88, AError: 0x89, ASectorCnt: 0x8a, ASector: 0x8b, ATACylinder: 0x8c, ATACylinderH: 0x8d, ATAHead: 0x8e, ATACommand: 0x8f, ATAStatus: 0x8f }; // ATA Status Bits const STATUS = { BSY: 0x80, // Busy DRDY: 0x40, // Drive ready. 1 when ready DWF: 0x20, // Drive write fault. 1 when fault DSC: 0x10, // Disk seek complete. 1 when not seeking DRQ: 0x08, // Data request. 1 when ready to write CORR: 0x04, // Correct data. 1 on correctable error IDX: 0x02, // 1 once per revolution ERR: 0x01 // Error. 1 on error }; // ATA Identity Block Locations const IDENTITY = { SectorCountLow: 58, SectorCountHigh: 57 }; export interface CFFAState { disks: Array<BlockDisk | null> } export default class CFFA implements Card, MassStorage, Restorable<CFFAState> { // CFFA internal Flags private _disableSignalling = false; private _writeEEPROM = true; private _lba = true; // LBA/CHS registers private _sectorCnt = 1; private _sector = 0; private _cylinder = 0; private _cylinderH = 0; private _head = 0; private _drive = 0; // CFFA Data High register private _dataHigh = 0; // Current Sector private _curSector: Uint16Array | number[]; private _curWord = 0; // ATA Status registers private _interruptsEnabled = false; private _altStatus = 0; private _error = 0; private _identity: number[][] = [[], []]; // Disk data private _partitions: Array<ProDOSVolume|null> = [ // Drive 1 null, // Drive 2 null ]; private _sectors: Uint16Array[][] = [ // Drive 1 [], // Drive 2 [] ]; constructor() { debug('CFFA'); for (let idx = 0; idx < 0x100; idx++) { this._identity[0][idx] = 0; this._identity[1][idx] = 0; } rom[SETTINGS.Max32MBPartitionsDev0] = 0x1; rom[SETTINGS.Max32MBPartitionsDev1] = 0x0; rom[SETTINGS.BootTimeDelayTenths] = 0x5; // 0.5 seconds rom[SETTINGS.CheckDeviceTenths] = 0x5; // 0.5 seconds } // Verbose debug method private _debug(..._args: any[]) { // debug.apply(this, arguments); } private _reset() { this._debug('reset'); this._sectorCnt = 1; this._sector = 0; this._cylinder = 0; this._cylinderH = 0; this._head = 0; this._drive = 0; this._dataHigh = 0; } // Convert status register into readable string private _statusString(status: byte) { const statusArray = []; let flag: keyof typeof STATUS; for (flag in STATUS) { if(status & STATUS[flag]) { statusArray.push(flag); } } return statusArray.join('|'); } // Dump sector as hex and ascii private _dumpSector(sector: number) { if (sector >= this._sectors[this._drive].length) { this._debug('dump sector out of range', sector); return; } for (let idx = 0; idx < 16; idx++) { const row = []; const charRow = []; for (let jdx = 0; jdx < 16; jdx++) { const val = this._sectors[this._drive][sector][idx * 16 + jdx]; row.push(toHex(val, 4)); const low = val & 0x7f; const hi = val >> 8 & 0x7f; charRow.push(low > 0x1f ? String.fromCharCode(low) : '.'); charRow.push(hi > 0x1f ? String.fromCharCode(hi) : '.'); } this._debug(row.join(' '), ' ', charRow.join('')); } } // Card I/O access private _access(off: byte, val: byte) { const readMode = val === undefined; let retVal; let sector; if (readMode) { retVal = 0; switch (off & 0x8f) { case LOC.ATADataHigh: // 0x00 retVal = this._dataHigh; break; case LOC.SetCSMask: // 0x01 this._disableSignalling = true; break; case LOC.ClearCSMask: // 0x02 this._disableSignalling = false; break; case LOC.WriteEEPROM: // 0x03 this._writeEEPROM = true; break; case LOC.NoWriteEEPROM: // 0x04 this._writeEEPROM = false; break; case LOC.ATAAltStatus: // 0x06 retVal = this._altStatus; break; case LOC.ATADataLow: // 0x08 this._dataHigh = this._curSector[this._curWord] >> 8; retVal = this._curSector[this._curWord] & 0xff; if (!this._disableSignalling) { this._curWord++; } break; case LOC.AError: // 0x09 retVal = this._error; break; case LOC.ASectorCnt: // 0x0A retVal = this._sectorCnt; break; case LOC.ASector: // 0x0B retVal = this._sector; break; case LOC.ATACylinder: // 0x0C retVal = this._cylinder; break; case LOC.ATACylinderH: // 0x0D retVal = this._cylinderH; break; case LOC.ATAHead: // 0x0E retVal = this._head | (this._lba ? 0x40 : 0) | (this._drive ? 0x10 : 0) | 0xA0; break; case LOC.ATAStatus: // 0x0F retVal = this._sectors[this._drive].length > 0 ? STATUS.DRDY | STATUS.DSC : 0; this._debug('returning status', this._statusString(retVal)); break; default: debug('read unknown soft switch', toHex(off)); } if (off & 0x7) { // Anything but data high/low this._debug('read soft switch', toHex(off), toHex(retVal)); } } else { if (off & 0x7) { // Anything but data high/low this._debug('write soft switch', toHex(off), toHex(val)); } switch (off & 0x8f) { case LOC.ATADataHigh: // 0x00 this._dataHigh = val; break; case LOC.SetCSMask: // 0x01 this._disableSignalling = true; break; case LOC.ClearCSMask: // 0x02 this._disableSignalling = false; break; case LOC.WriteEEPROM: // 0x03 this._writeEEPROM = true; break; case LOC.NoWriteEEPROM: // 0x04 this._writeEEPROM = false; break; case LOC.ATADevCtrl: // 0x06 this._debug('devCtrl:', toHex(val)); this._interruptsEnabled = (val & 0x04) ? true : false; this._debug('Interrupts', this._interruptsEnabled ? 'enabled' : 'disabled'); if (val & 0x02) { this._reset(); } break; case LOC.ATADataLow: // 0x08 this._curSector[this._curWord] = this._dataHigh << 8 | val; this._curWord++; break; case LOC.ASectorCnt: // 0x0a this._debug('setting sector count', val); this._sectorCnt = val; break; case LOC.ASector: // 0x0b this._debug('setting sector', toHex(val)); this._sector = val; break; case LOC.ATACylinder: // 0x0c this._debug('setting cylinder', toHex(val)); this._cylinder = val; break; case LOC.ATACylinderH: // 0x0d this._debug('setting cylinder high', toHex(val)); this._cylinderH = val; break; case LOC.ATAHead: this._head = val & 0xf; this._lba = val & 0x40 ? true : false; this._drive = val & 0x10 ? 1 : 0; this._debug('setting head', toHex(val & 0xf), 'drive', this._drive); if (!this._lba) { console.error('CHS mode not supported'); } break; case LOC.ATACommand: // 0x0f this._debug('command:', toHex(val)); sector = this._head << 24 | this._cylinderH << 16 | this._cylinder << 8 | this._sector; this._dumpSector(sector); switch (val) { case COMMANDS.ATAIdentify: this._debug('ATA identify'); this._curSector = this._identity[this._drive]; this._curWord = 0; break; case COMMANDS.ATACRead: this._debug('ATA read sector', toHex(this._cylinderH), toHex(this._cylinder), toHex(this._sector), sector); this._curSector = this._sectors[this._drive][sector]; this._curWord = 0; break; case COMMANDS.ATACWrite: this._debug('ATA write sector', toHex(this._cylinderH), toHex(this._cylinder), toHex(this._sector), sector); this._curSector = this._sectors[this._drive][sector]; this._curWord = 0; break; default: debug('unknown command', toHex(val)); } break; default: debug('write unknown soft switch', toHex(off), toHex(val)); } } return retVal; } ioSwitch(off: byte, val: byte) { return this._access(off, val); } read(page: byte, off: byte) { return rom[(page - 0xc0) << 8 | off]; } write(page: byte, off: byte, val: byte) { if (this._writeEEPROM) { this._debug('writing', toHex(page << 8 | off), toHex(val)); rom[(page - 0xc0) << 8 | off] - val; } } getState() { return { disks: this._partitions.map( (partition) => { let result: BlockDisk | null = null; if (partition) { const disk: BlockDisk = partition.disk(); result = { blocks: disk.blocks.map( (block) => new Uint8Array(block) ), encoding: ENCODING_BLOCK, readOnly: disk.readOnly, name: disk.name, }; } return result; } ) }; } setState(state: CFFAState) { state.disks.forEach( (disk, idx) => { if (disk) { this.setBlockVolume(idx + 1, disk); } else { this.resetBlockVolume(idx + 1); } } ); } resetBlockVolume(drive: number) { drive = drive - 1; this._sectors[drive] = []; this._identity[drive][IDENTITY.SectorCountHigh] = 0; this._identity[drive][IDENTITY.SectorCountLow] = 0; if (drive) { rom[SETTINGS.Max32MBPartitionsDev1] = 0x0; } else { rom[SETTINGS.Max32MBPartitionsDev0] = 0x0; } } setBlockVolume(drive: number, disk: BlockDisk) { drive = drive - 1; // Convert 512 byte blocks into 256 word sectors this._sectors[drive] = disk.blocks.map(function(block) { return new Uint16Array(block.buffer); }); this._identity[drive][IDENTITY.SectorCountHigh] = this._sectors[0].length & 0xffff; this._identity[drive][IDENTITY.SectorCountLow] = this._sectors[0].length >> 16; const prodos = new ProDOSVolume(disk); dump(prodos); this._partitions[drive] = prodos; if (drive) { rom[SETTINGS.Max32MBPartitionsDev1] = 0x1; } else { rom[SETTINGS.Max32MBPartitionsDev0] = 0x1; } return true; } // Assign a raw disk image to a drive. Must be 2mg or raw PO image. setBinary(drive: number, name: string, ext: BlockFormat, rawData: ArrayBuffer) { const volume = 254; const readOnly = false; if (ext === '2mg') { const { bytes, offset } = read2MGHeader(rawData); rawData = rawData.slice(offset, offset + bytes); } const options = { rawData, name, volume, readOnly }; const disk = createBlockDisk(options); return this.setBlockVolume(drive, disk); } }
the_stack
import assert from 'assert'; import sinon from 'sinon'; import path from 'path'; import mockfs from 'mock-fs'; import rewire from 'rewire'; import Config from './Config'; import precinct from '../precinct'; const expect = require('chai').expect; // needed for the lazy loading. require('module-definition'); require('detective-stylus'); require('../../../../../constants'); require('../../../../../utils'); require('../../../../../utils/is-relative-import'); require('../detectives/detective-css-and-preprocessors'); require('../detectives/detective-typescript'); require('../detectives/detective-css'); require('../detectives/detective-sass'); require('../detectives/detective-scss'); require('../detectives/detective-less'); require('../detectives/parser-helper'); require('../dependency-tree/Config'); require('../precinct'); require('../filing-cabinet'); const dependencyTreeRewired = rewire('./'); const dependencyTree = dependencyTreeRewired.default; const fixtures = path.resolve(`${__dirname}/../../../../../../fixtures/dependency-tree`); describe('dependencyTree', function() { this.timeout(8000); function testTreesForFormat(format, ext = '.js') { it('returns an object form of the dependency tree for a file', () => { const root = `${fixtures}/${format}`; const filename = path.normalize(`${root}/a${ext}`); const tree = dependencyTree({ filename, root }); assert(tree instanceof Object); const aSubTree = tree[filename]; assert.ok(aSubTree instanceof Object); const filesInSubTree = Object.keys(aSubTree); assert.equal(filesInSubTree.length, 2); }); } function mockStylus() { mockfs({ [`${fixtures}/stylus`]: { 'a.styl': ` @import "b" @require "c.styl" `, 'b.styl': '@import "c"', 'c.styl': '' } }); } function mockSass() { mockfs({ [`${fixtures}/sass`]: { 'a.scss': ` @import "_b"; @import "_c.scss"; `, '_b.scss': 'body { color: blue; }', '_c.scss': 'body { color: pink; }' } }); } function mockLess() { mockfs({ [`${fixtures}/less`]: { 'a.less': ` @import "b.css"; @import "c.less"; `, 'b.css': 'body { color: blue; }', 'c.less': 'body { color: pink; }' } }); } function mockes6() { mockfs({ [`${fixtures}/es6`]: { 'a.js': ` import b from './b'; import c from './c'; `, 'b.js': 'export default () => {};', 'c.js': 'export default () => {};', 'jsx.js': "import c from './c';\n export default <jsx />;", 'foo.jsx': "import React from 'react';\n import b from './b';\n export default <jsx />;", 'es7.js': "import c from './c';\n export default async function foo() {};" } }); } function mockTS() { mockfs({ [`${fixtures}/ts`]: { 'a.ts': ` import b from './b'; import c from './c'; `, 'b.ts': 'export default () => {};', 'c.ts': 'export default () => {};' } }); } afterEach(() => { mockfs.restore(); }); it('returns an empty object for a non-existent filename', () => { mockfs({ imaginary: {} }); const root = `${__dirname}/imaginary`; const filename = `${root}/notafile.js`; const tree = dependencyTree({ filename, root }); assert(tree instanceof Object); assert(!Object.keys(tree).length); }); it('handles nested tree structures', () => { mockfs({ [`${__dirname}/extended`]: { 'a.js': `var b = require('./b'); var c = require('./c');`, 'b.js': `var d = require('./d'); var e = require('./e');`, 'c.js': `var f = require('./f'); var g = require('./g');`, 'd.js': '', 'e.js': '', 'f.js': '', 'g.js': '' } }); const directory = `${__dirname}/extended`; const filename = path.normalize(`${directory}/a.js`); const tree = dependencyTree({ filename, directory }); assert(tree[filename] instanceof Object); // b and c const subTree = tree[filename]; assert.equal(subTree.length, 2); const bTree = tree[path.normalize(`${directory}/b.js`)]; const cTree = tree[path.normalize(`${directory}/c.js`)]; // d and e assert.equal(bTree.length, 2); // f ang g assert.equal(cTree.length, 2); }); it('does not include files that are not real (#13)', () => { mockfs({ [`${__dirname}/onlyRealDeps`]: { 'a.js': 'var notReal = require("./notReal");' } }); const directory = `${__dirname}/onlyRealDeps`; const filename = path.normalize(`${directory}/a.js`); const tree = dependencyTree({ filename, directory }); const subTree = tree[filename]; assert.ok(!Object.keys(subTree).some(dep => dep.indexOf('notReal') !== -1)); }); it('does not choke on cyclic dependencies', () => { mockfs({ [`${__dirname}/cyclic`]: { 'a.js': 'var b = require("./b");', 'b.js': 'var a = require("./a");' } }); const directory = `${__dirname}/cyclic`; const filename = path.normalize(`${directory}/a.js`); const spy = sinon.spy(dependencyTreeRewired, '_getDependencies'); const tree = dependencyTreeRewired.default({ filename, directory }); assert(spy.callCount === 2); assert(Object.keys(tree[filename]).length); dependencyTreeRewired._getDependencies.restore(); }); it('excludes Nodejs core modules by default', () => { const directory = `${fixtures}/commonjs`; const filename = path.normalize(`${directory}/b.js`); const tree = dependencyTree({ filename, directory }); assert(Object.keys(tree[filename]).length === 0); assert(Object.keys(tree)[0].indexOf('b.js') !== -1); }); it('traverses installed 3rd party node modules', () => { const directory = `${fixtures}/onlyRealDeps`; const filename = path.normalize(`${directory}/a.js`); const tree = dependencyTree({ filename, directory }); const subTree = tree[filename]; assert(subTree.includes(require.resolve('debug'))); }); it('returns a list of absolutely pathed files', () => { const directory = `${fixtures}/commonjs`; const filename = `${directory}/b.js`; const tree = dependencyTree({ filename, directory }); // eslint-disable-next-line for (const node in tree.nodes) { assert(node.indexOf(process.cwd()) !== -1); } }); describe('when given a detective configuration', () => { it('passes it through to precinct', () => { const spy = sinon.spy(precinct, 'paperwork'); const directory = path.normalize(`${fixtures}/onlyRealDeps`); const filename = path.normalize(`${directory}/a.js`); const detectiveConfig = { amd: { skipLazyLoaded: true } }; dependencyTree({ filename, directory, detective: detectiveConfig }); assert.ok(spy.calledWith(filename, detectiveConfig)); spy.restore(); }); }); describe('when given a list to store non existent partials', () => { describe('and the file contains no valid partials', () => { it('stores the invalid partials', () => { mockfs({ [`${__dirname}/onlyRealDeps`]: { 'a.js': 'var notReal = require("./notReal");' } }); const directory = path.normalize(`${__dirname}/onlyRealDeps`); const filename = path.normalize(`${directory}/a.js`); const nonExistent = []; dependencyTree({ filename, directory, nonExistent }); assert.equal(Object.keys(nonExistent).length, 1); assert.equal(nonExistent[filename][0], './notReal'); }); }); describe('and the file contains all valid partials', () => { it('does not store anything', () => { mockfs({ [`${__dirname}/onlyRealDeps`]: { 'a.js': 'var b = require("./b");', 'b.js': 'export default 1;' } }); const directory = `${__dirname}/onlyRealDeps`; const filename = `${directory}/a.js`; const nonExistent = []; dependencyTree({ filename, directory, nonExistent }); assert.equal(nonExistent.length, 0); }); }); describe('and the file contains a mix of invalid and valid partials', () => { it('stores the invalid ones', () => { mockfs({ [`${__dirname}/onlyRealDeps`]: { 'a.js': 'var b = require("./b");', 'b.js': 'var c = require("./c"); export default 1;', 'c.js': 'var crap = require("./notRealMan");' } }); const directory = path.normalize(`${__dirname}/onlyRealDeps`); const filename = path.normalize(`${directory}/a.js`); const nonExistent = []; dependencyTree({ filename, directory, nonExistent }); assert.equal(Object.keys(nonExistent).length, 1); assert.equal(nonExistent[path.normalize(`${directory}/c.js`)][0], './notRealMan'); }); }); describe('and there is more than one reference to the invalid partial', () => { it('should include the non-existent partial per file', () => { mockfs({ [`${__dirname}/onlyRealDeps`]: { 'a.js': 'var b = require("./b");\nvar crap = require("./notRealMan");', 'b.js': 'var c = require("./c"); export default 1;', 'c.js': 'var crap = require("./notRealMan");' } }); const directory = path.normalize(`${__dirname}/onlyRealDeps`); const filename = path.normalize(`${directory}/a.js`); const nonExistent = []; dependencyTree({ filename, directory, nonExistent }); assert.equal(Object.keys(nonExistent).length, 2); assert.equal(nonExistent[filename][0], './notRealMan'); assert.equal(nonExistent[path.normalize(`${directory}/c.js`)][0], './notRealMan'); }); }); }); describe('throws', () => { beforeEach(() => { // @ts-ignore this._directory = `${fixtures}/commonjs`; // @ts-ignore this._revert = dependencyTreeRewired.__set__('traverse', () => []); }); afterEach(() => { // @ts-ignore this._revert(); }); it('throws if the filename is missing', () => { assert.throws(() => { dependencyTree({ filename: undefined, // @ts-ignore directory: this._directory }); }); }); it('throws if the root is missing', () => { assert.throws(() => { dependencyTree({ filename: undefined }); }); }); it('throws if a supplied filter is not a function', () => { assert.throws(() => { const directory = `${fixtures}/onlyRealDeps`; const filename = `${directory}/a.js`; dependencyTree({ filename, directory, filter: 'foobar' }); }); }); it('does not throw on the legacy `root` option', () => { assert.doesNotThrow(() => { const directory = `${fixtures}/onlyRealDeps`; const filename = `${directory}/a.js`; dependencyTree({ filename, root: directory }); }); }); }); describe('on file error', () => { beforeEach(() => { // @ts-ignore this._directory = `${fixtures}/commonjs`; }); it('does not throw', () => { assert.doesNotThrow(() => { dependencyTree({ filename: 'foo', // @ts-ignore directory: this._directory }); }); }); it('returns no dependencies', () => { // @ts-ignore const tree = dependencyTree({ filename: 'foo', directory: this._directory }); assert(!tree.length); }); }); describe('memoization (#2)', () => { beforeEach(() => { // @ts-ignore this._spy = sinon.spy(dependencyTreeRewired, '_getDependencies'); }); afterEach(() => { dependencyTreeRewired._getDependencies.restore(); }); it('accepts a cache object for memoization (#2)', () => { const filename = path.normalize(`${fixtures}/amd/a.js`); const directory = path.normalize(`${fixtures}/amd`); const cache = {}; cache[path.normalize(`${fixtures}/amd/b.js`)] = { pathMap: { dependencies: [path.normalize(`${fixtures}/amd/b.js`), path.normalize(`${fixtures}/amd/c.js`)] } }; const tree = dependencyTree({ filename, directory, visited: cache }); assert.equal(Object.keys(tree[filename]).length, 2); // @ts-ignore assert(this._spy.neverCalledWith(path.normalize(`${fixtures}/amd/b.js`))); }); it('returns the precomputed list of a cached entry point', () => { const filename = `${fixtures}/amd/a.js`; const directory = `${fixtures}/amd`; const cache = { // Shouldn't process the first file's tree [filename]: { pathMap: { dependencies: [] } } }; const tree = dependencyTree({ filename, directory, visited: cache }); assert(!tree.length); }); }); describe('module formats', () => { describe('amd', () => { testTreesForFormat('amd'); }); describe('commonjs', () => { testTreesForFormat('commonjs'); }); describe('es6', () => { beforeEach(() => { // @ts-ignore this._directory = path.normalize(`${fixtures}/es6`); mockes6(); }); testTreesForFormat('es6'); it('resolves files that have jsx', () => { // @ts-ignore const filename = path.normalize(`${this._directory}/jsx.js`); const tree = dependencyTree({ filename, // @ts-ignore directory: this._directory }); // @ts-ignore assert.ok(tree[filename].includes(path.normalize(`${this._directory}/c.js`))); }); it('resolves files with a jsx extension', () => { // @ts-ignore const filename = path.normalize(`${this._directory}/foo.jsx`); const tree = dependencyTree({ filename, // @ts-ignore directory: this._directory }); // @ts-ignore assert.ok(tree[filename].includes(path.normalize(`${this._directory}/b.js`))); }); it('resolves files that have es7', () => { // @ts-ignore const filename = path.normalize(`${this._directory}/es7.js`); const tree = dependencyTree({ filename, // @ts-ignore directory: this._directory }); // @ts-ignore assert.ok(tree[filename].includes(path.normalize(`${this._directory}/c.js`))); }); }); describe('sass', () => { beforeEach(() => { mockSass(); }); testTreesForFormat('sass', '.scss'); }); describe('stylus', () => { beforeEach(() => { mockStylus(); }); testTreesForFormat('stylus', '.styl'); }); describe('less', () => { beforeEach(() => { mockLess(); }); testTreesForFormat('less', '.less'); }); describe('typescript', () => { beforeEach(() => { mockTS(); }); testTreesForFormat('ts', '.ts'); }); }); // skipping the webpack unit tests for now as it's not easy to wire up all the files together. // originally, in dependency-tree, the webpack.config.js is in the same directory of the index.js. // doing the same here will be confusing. instead, we have already e2e-tests in bit-bin of custom // module resolution, which takes advantage of the webpack config. describe.skip('webpack', () => { beforeEach(() => { // Note: not mocking because webpack's resolver needs a real project with dependencies; // otherwise, we'd have to mock a ton of files. // @ts-ignore this._root = path.join(__dirname, '../'); // @ts-ignore this._webpackConfig = `${this._root}/webpack.config.js`; // @ts-ignore this._testResolution = name => { const results = dependencyTree.toList({ filename: `${fixtures}/webpack/${name}.js`, // @ts-ignore directory: this._root, // @ts-ignore webpackConfig: this._webpackConfig, filter: filename => filename.indexOf('filing-cabinet') !== -1 }); assert.ok(results.some(filename => filename.indexOf('node_modules/filing-cabinet') !== -1)); }; }); it('resolves aliased modules', () => { this.timeout(5000); // @ts-ignore this._testResolution('aliased'); }); it('resolves unaliased modules', () => { this.timeout(5000); // @ts-ignore this._testResolution('unaliased'); }); }); describe('requirejs', () => { beforeEach(() => { mockfs({ root: { 'lodizzle.js': 'define({})', 'require.config.js': ` requirejs.config({ baseUrl: './', paths: { F: './lodizzle.js' } }); `, 'a.js': ` define([ 'F' ], function(F) { }); `, 'b.js': ` define([ './lodizzle' ], function(F) { }); ` } }); }); it('resolves aliased modules', () => { const tree = dependencyTree({ filename: 'root/a.js', directory: 'root', config: 'root/require.config.js' }); const filename = path.resolve(process.cwd(), 'root/a.js'); assert(tree[filename].includes(path.normalize('root/lodizzle.js'))); }); it('resolves non-aliased paths', () => { const tree = dependencyTree({ filename: 'root/b.js', directory: 'root', config: 'root/require.config.js' }); const filename = path.resolve(process.cwd(), 'root/b.js'); assert.ok(tree[filename].includes(path.normalize('root/lodizzle.js'))); }); }); describe('when a filter function is supplied', () => { it('uses the filter to determine if a file should be included in the results', () => { const directory = path.normalize(`${fixtures}/onlyRealDeps`); const filename = path.normalize(`${directory}/a.js`); const tree = dependencyTree({ filename, directory, // Skip all 3rd party deps filter: (filePath, moduleFile) => { assert.ok(require.resolve('debug')); assert.ok(moduleFile.includes(path.normalize('onlyRealDeps/a.js'))); return filePath.indexOf('node_modules') === -1; } }); const subTree = tree[filename]; assert.ok(Object.keys(tree).length); const has3rdPartyDep = Object.keys(subTree).some(dep => dep === require.resolve('debug')); assert.ok(!has3rdPartyDep); }); }); describe('when given a CJS file with lazy requires', () => { beforeEach(() => { mockfs({ [`${__dirname}/cjs`]: { 'foo.js': 'module.exports = function(bar = require("./bar")) {};', 'bar.js': 'module.exports = 1;' } }); }); it('includes the lazy dependency', () => { const directory = `${__dirname}/cjs`; const filename = path.normalize(`${directory}/foo.js`); const tree = dependencyTree({ filename, directory }); assert.ok(tree[filename].includes(path.normalize(`${directory}/bar.js`))); }); }); describe('when given an es6 file using CJS lazy requires', () => { beforeEach(() => { mockfs({ [`${__dirname}/es6`]: { 'foo.js': 'export default function(bar = require("./bar")) {};', 'bar.js': 'export default 1;' } }); }); describe('and mixedImport mode is turned on', () => { it('includes the lazy dependency', () => { const directory = `${__dirname}/es6`; const filename = path.normalize(`${directory}/foo.js`); const tree = dependencyTree({ filename, directory, detective: { es6: { mixedImports: true } } }); assert.ok(tree[filename].includes(path.normalize(`${directory}/bar.js`))); }); }); }); describe('when given an es6 file using dynamic imports', () => { beforeEach(() => { mockfs({ [`${__dirname}/es6`]: { 'foo.js': 'import("./bar");', 'bar.js': 'export default 1;' } }); }); it('includes the dynamic import', () => { const directory = path.normalize(`${__dirname}/es6`); const filename = path.normalize(`${directory}/foo.js`); const tree = dependencyTree({ filename, directory }); const subTree = tree[filename]; assert.ok(!(`${directory}/bar.js` in subTree)); }); }); describe('when a dependency of the main file is not supported', () => { beforeEach(() => { mockfs({ [`${__dirname}/baz`]: { 'foo.js': 'require("./bar.json");', 'bar.json': '{ "main": "I\'m a simple JSON object" }' } }); }); it('should include it as a dependency and not throw an error', () => { const directory = path.normalize(`${__dirname}/baz`); const filename = path.normalize(`${directory}/foo.js`); const tree = dependencyTree({ filename, directory }); assert.ok(`${directory}/bar.json` in tree); }); }); // nodeModulesConfig is a feature added to dependency-tree and filing-cabinet to support // "module" attribute of package.json, see here what this attribute is good for: // https://github.com/rollup/rollup/wiki/pkg.module // the commit of supporting it in filing-cabinet is here: https://github.com/dependents/node-filing-cabinet/commit/abef861a5a725b29c2342d01de94c6e2dd881aa0 describe.skip('when given a CJS file with module property in package.json', () => { beforeEach(() => { mockfs({ [`${__dirname}/es6`]: { 'module.entry.js': 'import * as module from "module.entry"', node_modules: { 'module.entry': { 'index.main.js': 'module.exports = () => {};', 'index.module.js': 'module.exports = () => {};', 'package.json': '{ "main": "index.main.js", "module": "index.module.js" }' } } } }); }); it('it includes the module entry as dependency', () => { const directory = `${__dirname}/es6`; const filename = `${directory}/module.entry.js`; const tree = dependencyTree({ filename, directory, nodeModulesConfig: { entry: 'module' } }); const subTree = tree[filename]; assert.ok(`${directory}/node_modules/module.entry/index.module.js` in subTree); }); }); describe('Config', () => { describe('when cloning', () => { describe('and a detective config was set', () => { it('retains the detective config in the clone', () => { const detectiveConfig = { es6: { mixedImports: true } }; const config = new Config({ detectiveConfig, filename: 'foo', directory: 'bar' }); const clone = config.clone(); assert.deepEqual(clone.detectiveConfig, detectiveConfig); }); }); }); }); describe('when a dependency has missing packages and is retrieved from the cache (visited)', () => { beforeEach(() => { mockfs({ [`${__dirname}/baz`]: { 'foo.js': 'require("non-exist-foo-pkg");', 'bar.js': 'require("./foo"); require("non-exist-bar-pkg")', 'baz.js': 'require("./foo"); require("./bar"); require("non-exist-baz-pkg")' } }); }); it('should not override the cache with wrong packages', () => { const directory = path.normalize(`${__dirname}/baz`); const fooFile = path.normalize(`${directory}/foo.js`); const barFile = path.normalize(`${directory}/bar.js`); const bazFile = path.normalize(`${directory}/baz.js`); const nonExistent = {}; const config = { directory, nonExistent, visited: {} }; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! config.filename = fooFile; dependencyTree(config); expect(nonExistent[fooFile]).to.deep.equal(['non-exist-foo-pkg']); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! config.filename = barFile; dependencyTree(config); expect(nonExistent[fooFile]).to.deep.equal(['non-exist-foo-pkg']); expect(nonExistent[barFile]).to.deep.equal(['non-exist-bar-pkg']); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! config.filename = bazFile; dependencyTree(config); expect(nonExistent[fooFile]).to.deep.equal(['non-exist-foo-pkg']); expect(nonExistent[barFile]).to.deep.equal(['non-exist-bar-pkg']); expect(nonExistent[bazFile]).to.deep.equal(['non-exist-baz-pkg']); }); }); describe('passing css files and then javascript files', () => { beforeEach(() => { mockfs({ [`${__dirname}/baz`]: { 'base.scss': 'li {} a {}', // don't change the content. it crash only with this for some reason 'index.jsx': "require('some-module');" } }); }); it('should not crash with "RangeError: Maximum call stack size exceeded" error', () => { const directory = path.normalize(`${__dirname}/baz`); const baseFile = path.normalize(`${directory}/base.scss`); const indexFile = path.normalize(`${directory}/index.jsx`); const config = { directory }; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! config.filename = baseFile; dependencyTree(config); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! config.filename = indexFile; const dependencies = dependencyTree(config); expect(dependencies).to.be.ok; }); }); describe('files with dynamic import', () => { it('should not show missing dependencies', () => { mockfs({ [`${__dirname}/dynamic`]: { 'foo.js': 'const a = "./b"; import(a); require(a);' } }); const directory = path.normalize(`${__dirname}/dynamic`); const filename = path.normalize(`${directory}/foo.js`); const visited = {}; dependencyTree({ filename, directory, visited }); expect(visited[filename].missing).to.be.undefined; }); }); describe('files with import from cdn (http, https)', () => { it('should not show missing dependencies when importing from https', () => { mockfs({ [`${__dirname}/cdn`]: { 'foo.js': 'import { a } from "https://unpkg.com";' } }); const directory = path.normalize(`${__dirname}/cdn`); const filename = path.normalize(`${directory}/foo.js`); const visited = {}; dependencyTree({ filename, directory, visited }); expect(visited[filename].missing).to.be.undefined; }); it('should not show missing dependencies when importing from http', () => { mockfs({ [`${__dirname}/cdn`]: { 'bar.js': 'const b = require("http://pkg.com");' } }); const directory = path.normalize(`${__dirname}/cdn`); const filename = path.normalize(`${directory}/bar.js`); const visited = {}; dependencyTree({ filename, directory, visited }); expect(visited[filename].missing).to.be.undefined; }); }); describe('resolve config when the dependency is "."', () => { it('should not set the dependency with isCustomResolveUsed=true', () => { mockfs({ [`${__dirname}/src`]: { 'foo.js': "require('.');", 'index.js': 'module.exports = {}' } }); const directory = path.normalize(`${__dirname}/src`); const filename = path.normalize(`${directory}/foo.js`); const config = { filename, directory, pathMap: [], resolveConfig: { aliases: { something: 'anything' } } }; dependencyTree(config); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const pathMapRecord = config.pathMap.find(f => f.file === filename); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(pathMapRecord.dependencies).to.have.lengthOf(1); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const dependency = pathMapRecord.dependencies[0]; expect(dependency).to.not.have.property('isCustomResolveUsed'); }); }); describe('resolve config when the dependency is ".."', () => { it('should not set the dependency with isCustomResolveUsed=true', () => { mockfs({ [`${__dirname}/src`]: { 'index.js': 'module.exports = {}', bar: { 'foo.js': "require('..');" } } }); const directory = path.normalize(`${__dirname}/src`); const filename = path.normalize(`${directory}/bar/foo.js`); const config = { filename, directory, pathMap: [], resolveConfig: { aliases: { something: 'anything' } } }; dependencyTree(config); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const pathMapRecord = config.pathMap.find(f => f.file === filename); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(pathMapRecord.dependencies).to.have.lengthOf(1); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const dependency = pathMapRecord.dependencies[0]; expect(dependency).to.not.have.property('isCustomResolveUsed'); }); }); });
the_stack
import { HttpRequest } from "./duktape/http"; import { Coroutine } from "./duktape/coroutine"; import Time = UnityEngine.Time; export function sampleTests() { // test protobuf // (function () { // // let writer = protobuf.Writer.create() // let msg = new protos.Ping() // msg.payload = "hello, protobuf" // msg.time = 123 // let w = protos.Ping.encode(msg) // let buf = w.finish() // // > go run examples\echoserver\src\main.go // // you need a simple echo server to run the code below // let ws = new DuktapeJS.WebSocket() // ws.connect("ws://127.0.0.1:8080/websocket") // ws.on("open", this, () => { // console.log("ws opened") // ws.send(buf) // }) // ws.on("close", this, () => { // console.log("ws closed") // }) // ws.on("data", this, data => { // let dmsg = protos.Ping.decode(data) // console.log(`msg.payload = ${dmsg.payload}`) // console.log(`msg.time = ${dmsg.time}`) // }) // let go = new UnityEngine.GameObject("ws") // go.AddComponent(DuktapeJS.Bridge).SetBridge({ // Update: () => { // ws.poll() // }, // OnDestroy: () => { // console.log("ws close") // ws.close() // }, // }) // })(); (function () { console.log("http requesting..."); HttpRequest.GET("http://t.weather.sojson.com/api/weather/city/101030100", null, (status, res) => { console.warn("http response:", status, res); if (status) { let obj = JSON.parse(res); console.log("as object", obj.message); } }); })(); (function () { let sample = new SampleNamespace.SampleClass("test match type"); sample.MethodOverride(new UnityEngine.Vector3(1, 2, 3)); })(); (function () { let Vector3 = UnityEngine.Vector3; let start: number; let DoNothing = SampleNamespace.SampleClass.DoNothing; start = Date.now(); for (let i = 1; i < 1000000; i++) { DoNothing(); } SampleNamespace.SampleClass.WriteLog(`js/DoNothing: ${(Date.now() - start) / 1000}`); let DoNothing1 = SampleNamespace.SampleClass.DoNothing1; start = Date.now(); for (let i = 1; i < 1000000; i++) { DoNothing1(i); } SampleNamespace.SampleClass.WriteLog(`js/DoNothing1: ${(Date.now() - start) / 1000}`); let v1 = new Vector3(0, 0, 0) start = Date.now(); for (let i = 1; i < 200000; i++) { v1.Set(i, i, i) v1.Normalize() } console.log("js/vector3/normailize", (Date.now() - start) / 1000); let v = Vector3.zero let w = Vector3.one start = Date.now(); for (let i = 1; i < 200000; i++) { v.Scale(w); } console.log("js/vector3/scale", (Date.now() - start) / 1000); let sum = 0; start = Date.now(); for (let i = 1; i < 20000000; i++) { sum += i; } console.log("js/number/add", (Date.now() - start) / 1000, sum); })(); (function () { console.log("### Vector3 (replaced)") let v1 = new UnityEngine.Vector3(1, 2, 3) console.log(`v: ${v1.x}, ${v1.y}, ${v1.z} (${v1.magnitude})`) console.log(`v: ${v1[0]}, ${v1[1]}, ${v1[2]}`) let v2 = v1.normalized console.log(`v: ${v2.x}, ${v2.y}, ${v2.z} (${v2.magnitude})`) v2.x += 10 console.log(`v: ${v2.x}, ${v2.y}, ${v2.z} (${v2.magnitude})`) let q1 = new UnityEngine.Quaternion(1, 2, 3, 1) console.log(`q: ${q1.x}, ${q1.y}, ${q1.z} eulerAngles: ${q1.eulerAngles.ToString()}`) })(); (function () { console.log("### Delegates begin") let d = new DuktapeJS.Delegate0<void>() d.on(this, () => { console.log("delegate0") }) d.dispatch() d.clear() d.dispatch() console.log("### Delegates end") })(); (function () { SampleNamespace.SampleClass.staticTestEvent.on(function () { console.log("sampleClass.staticTestEvent invoked!!!!") }) SampleNamespace.SampleClass.DispatchStaticTestEvent() let sampleClass = new SampleNamespace.SampleClass("sampleclass.constructor"); sampleClass.testEvent.on(function () { console.log("sampleClass.testEvent invoked!!!!") }) sampleClass.DispatchTestEvent(); sampleClass.delegateFoo4 = (a, b) => a + b; sampleClass.TestDelegate4(); console.log("trytrytrytry111", sampleClass.delegateFoo4); let d4 = new DuktapeJS.Delegate2<number, number, number>(); d4.on(sampleClass, function (a, b) { return (a + b) * 3; }); sampleClass.delegateFoo4 = d4; sampleClass.TestDelegate4(); console.log("trytrytrytry222", sampleClass.delegateFoo4); var fn = function () { console.log(this, "TestDelegate") }; SampleNamespace.SampleClass.TestDelegate(fn); SampleNamespace.SampleClass.TestDelegate(fn); let d = new DuktapeJS.Dispatcher() d.on("this", function () { console.log(this, "TestDelegate") }) SampleNamespace.SampleClass.TestDelegate(d) })(); console.log(UnityEngine.Mathf.PI); // UnityEngine.Debug.Log("greeting") (function () { let go = UnityEngine.GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Cube) go.name = "testing_cube" let hello = go.AddComponent(SampleNamespace.Hello); // DONT DO THIS, IT IS NOT READY // SCRATCH CODE { hello.StartCoroutine(new Coroutine(function () { console.warn("js function in unity coroutine 11"); Coroutine.yield(new UnityEngine.WaitForSeconds(2.5)); console.warn("js function in unity coroutine 22"); })); } console.log("hello.name = ", hello.gameObject.name) console.log("DuktapeJS.Bridge = ", DuktapeJS.Bridge) let bridge = go.AddComponent(DuktapeJS.Bridge) class MyBridge { hitInfo: any = {} gameObject: UnityEngine.GameObject transform: UnityEngine.Transform; private rotx = 10 private roty = 20 constructor(gameObject: UnityEngine.GameObject) { this.gameObject = gameObject this.transform = gameObject.transform; } OnEnable() { console.log("bridge.OnEnable") } Start() { console.log("bridge.Start") this.transform.localPosition = new UnityEngine.Vector3(3, 0, 0) } OnDisable() { console.log("bridge.OnDisable") } Update() { this.transform.localRotation = UnityEngine.Quaternion.Euler(this.rotx, this.roty, 0) this.rotx += Time.deltaTime * 3.0 this.roty += Time.deltaTime * 1.5 if (UnityEngine.Input.GetMouseButtonUp(0) || UnityEngine.Input.GetKeyUp(UnityEngine.KeyCode.Space)) { if (UnityExtensions.RaycastMousePosition(this.hitInfo, 1000, 1)) { console.log("you clicked " + this.hitInfo.collider.name) } } } OnDestroy() { console.log("bridge.OnDestroy") } } bridge.SetBridge(new MyBridge(go)) })(); (function () { let go2 = new UnityEngine.GameObject("testing2_wait_destroy") console.log("go2.activeSelf", go2.activeSelf) console.log("go2.activeSelf", go2.activeSelf) setTimeout(() => { go2.SetActive(false) }, 3500) setTimeout(() => { UnityEngine.Object.Destroy(go2) }, 30000) let time = 0; setInterval(() => { setTimeout(() => { time++; // setTimeout/setInterval gc test }, 50); }, 200); // if (DuktapeJS.Socket) { // var buffer = new Buffer(1024); // var sock = new DuktapeJS.Socket(1, 0); // var count = 0; // sock.connect("localhost", 1234); // console.log("buffer.length:", buffer.length); // setInterval(() => { // count++; // sock.send("test" + count); // var recv_size = sock.recv(buffer, 0, buffer.length); // if (recv_size > 0) { // console.log("echo", buffer.toString("utf8", 0, recv_size)); // } // }, 1000); // } else { // console.error("no DuktapeJS.Socket", DuktapeJS.SocketType, DuktapeJS.SocketFamily); // } })(); (function () { // console.log(UnityEngine.UI.Text) let textui = UnityEngine.GameObject.Find("/Canvas/Text").GetComponent(UnityEngine.UI.Text) if (textui) { textui.text = "hello, javascript" } let buttonui = UnityEngine.GameObject.Find("/Canvas/Button").GetComponent(UnityEngine.UI.Button) if (buttonui) { let delegate = new DuktapeJS.Delegate0<void>() delegate.on(buttonui, () => { if (textui) { textui.color = UnityEngine.Color.Lerp(UnityEngine.Color.black, UnityEngine.Color.green, UnityEngine.Random.value) } console.log("you clicked the button") }) delegate.on(buttonui, function () { console.log("another listener", this == buttonui) }) buttonui.onClick.AddListener(delegate) } })(); (function () { console.log("[Buffer] tests"); let buffer = SampleNamespace.SampleClass.GetBytes(); console.log(buffer); let str = SampleNamespace.SampleClass.InputBytes(buffer); console.log(str); setInterval(function () { SampleNamespace.SampleClass.AnotherBytesTest(buffer); }, 5000); })(); (function () { let co = new Coroutine(function (x) { console.log("duktape thread, start:", x); for (var i = 1; i <= 5; ++i) { let r = Coroutine.yield(i); console.log("duktape thread, yield:", r); } // Coroutine.break(); return "all done!"; }); let c = 'A'.charCodeAt(0); while (co.next(String.fromCharCode(c++))) { console.log("duktape thread, next:", co.value); } console.log("duktape thread, done:", co.value); })(); (function () { setTimeout(function () { let time_id = setInterval(function () { console.log(`[setInterval@${Time.frameCount}] test zero interval timer1`); }, 0); setTimeout(function () { clearInterval(time_id); console.log(`[setTimeout] clear interval timer1 [id:${time_id}]`); }, 0); console.log(`[setInterval@${Time.frameCount}] before timer2 ${Time.realtimeSinceStartup}`); let timer2frames = 0; let time_id2 = setInterval(function () { timer2frames++; console.log(`[setInterval@${Time.frameCount}] test zero interval timer2`); }, 0); setTimeout(function () { clearInterval(time_id2); console.log(`[setTimeout] clear interval timer2 [id:${time_id2}] realtime:${Time.realtimeSinceStartup} frames:${timer2frames}`); }, 150); }, 5000); })(); // (function () { // console.log("[error] tests"); // let u = null; // console.log(u.value); // })(); }
the_stack
import * as basic from './basic'; import * as named from './named'; export class EzspStruct { /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ static serialize(cls: any, obj: any): Buffer { /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ return Buffer.concat(cls._fields.map((field: any[]) => { const value = obj[field[0]]; console.assert(field[1]); return field[1].serialize(field[1], value); })); } /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ static deserialize(cls: any, data: Buffer): any[] { const r = new cls(); for (const [field_name, field_type] of cls._fields) { let v; [v, data] = field_type.deserialize(field_type, data); r[field_name] = v; } return [r, data]; } public toString(): string { return `${this.constructor.name}: ${JSON.stringify(this)}`; } } export class EmberNetworkParameters extends EzspStruct { public extendedPanId: number[]; public panId: number; public radioTxPower: number; public radioChannel: number; public joinMethod: named.EmberJoinMethod; public nwkManagerId: named.EmberNodeId; public nwkUpdateId: number; public channels: number; static _fields = [ // The network's extended PAN identifier. ['extendedPanId', basic.fixed_list(8, basic.uint8_t)], // The network's PAN identifier. ['panId', basic.uint16_t], // A power setting, in dBm. ['radioTxPower', basic.uint8_t], // A radio channel. ['radioChannel', basic.uint8_t], // The method used to initially join the network. ['joinMethod', named.EmberJoinMethod], // NWK Manager ID. The ID of the network manager in the current network. // This may only be set at joining when using USE_NWK_COMMISSIONING as // the join method. ['nwkManagerId', named.EmberNodeId], // NWK Update ID. The value of the ZigBee nwkUpdateId known by the // stack. This is used to determine the newest instance of the network // after a PAN ID or channel change. This may only be set at joining // when using USE_NWK_COMMISSIONING as the join method. ['nwkUpdateId', basic.uint8_t], // NWK channel mask. The list of preferred channels that the NWK manager // has told this device to use when searching for the network. This may // only be set at joining when using USE_NWK_COMMISSIONING as the join // method. ['channels', basic.uint32_t], ]; } export class EmberZigbeeNetwork extends EzspStruct { // The parameters of a ZigBee network. static _fields = [ // The 802.15.4 channel associated with the network. ['channel', basic.uint8_t], // The network's PAN identifier. ['panId', basic.uint16_t], // The network's extended PAN identifier. ['extendedPanId', basic.fixed_list(8, basic.uint8_t)], // Whether the network is allowing MAC associations. ['allowingJoin', named.Bool], // The Stack Profile associated with the network. ['stackProfile', basic.uint8_t], // The instance of the Network. ['nwkUpdateId', basic.uint8_t], ]; } export class EmberApsFrame extends EzspStruct { public profileId: number; public sequence: number; public clusterId: number; public sourceEndpoint: number; public destinationEndpoint: number; public groupId?: number; public options?: named.EmberApsOption; // ZigBee APS frame parameters. static _fields = [ // The application profile ID that describes the format of the message. ['profileId', basic.uint16_t], // The cluster ID for this message. ['clusterId', basic.uint16_t], // The source endpoint. ['sourceEndpoint', basic.uint8_t], // The destination endpoint. ['destinationEndpoint', basic.uint8_t], // A bitmask of options. ['options', named.EmberApsOption], // The group ID for this message, if it is multicast mode. ['groupId', basic.uint16_t], // The sequence number. ['sequence', basic.uint8_t], ]; } export class EmberBindingTableEntry extends EzspStruct { // An entry in the binding table. static _fields = [ // The type of binding. ['type', named.EmberBindingType], // The endpoint on the local node. ['local', basic.uint8_t], // A cluster ID that matches one from the local endpoint's simple // descriptor.This cluster ID is set by the provisioning application to // indicate which part an endpoint's functionality is bound to this // particular remote node and is used to distinguish between unicast and // multicast bindings.Note that a binding can be used to send messages // with any cluster ID, not just that listed in the binding. ['clusterId', basic.uint16_t], // The endpoint on the remote node [specified by identifier]. ['remote', basic.uint8_t], // A 64- bit identifier.This is either the destination EUI64 [for // unicasts] or the 64- bit group address [for multicasts]. ['identifier', named.EmberEUI64], // The index of the network the binding belongs to. ['networkIndex', basic.uint8_t], ]; } export class EmberMulticastTableEntry extends EzspStruct { public multicastId: number; public endpoint: number; public networkIndex: number; // A multicast table entry indicates that a particular endpoint is a member // of a particular multicast group.Only devices with an endpoint in a // multicast group will receive messages sent to that multicast group. static _fields = [ // The multicast group ID. ['multicastId', named.EmberMulticastId], // The endpoint that is a member, or 0 if this entry is not in use[the // ZDO is not a member of any multicast groups.] ['endpoint', basic.uint8_t], // The network index of the network the entry is related to. ['networkIndex', basic.uint8_t], ]; } export class EmberKeyData extends EzspStruct { public contents: Buffer; // A 128- bit key. static _fields = [ // The key data. ['contents', basic.fixed_list(16, basic.uint8_t)], ]; } export class EmberCertificateData extends EzspStruct { public contents: Buffer; // The implicit certificate used in CBKE. static _fields = [ // The certificate data. ['contents', basic.fixed_list(48, basic.uint8_t)], ]; } export class EmberPublicKeyData extends EzspStruct { public contents: Buffer; // The public key data used in CBKE. static _fields = [ // The public key data. ['contents', basic.fixed_list(22, basic.uint8_t)], ]; } export class EmberPrivateKeyData extends EzspStruct { public contents: Buffer; // The private key data used in CBKE. static _fields = [ // The private key data. ['contents', basic.fixed_list(21, basic.uint8_t)], ]; } export class EmberSmacData extends EzspStruct { // The Shared Message Authentication Code data used in CBKE. static _fields = [ // The Shared Message Authentication Code data. ['contents', basic.fixed_list(16, basic.uint8_t)], ]; } export class EmberSignatureData extends EzspStruct { // An ECDSA signature static _fields = [ // The signature data. ['contents', basic.fixed_list(42, basic.uint8_t)], ]; } export class EmberCertificate283k1Data extends EzspStruct { // The implicit certificate used in CBKE. static _fields = [ // The 283k1 certificate data. ['contents', basic.fixed_list(74, basic.uint8_t)], ]; } export class EmberPublicKey283k1Data extends EzspStruct { // The public key data used in CBKE. static _fields = [ // The 283k1 public key data. ['contents', basic.fixed_list(37, basic.uint8_t)], ]; } export class EmberPrivateKey283k1Data extends EzspStruct { // The private key data used in CBKE. static _fields = [ // The 283k1 private key data. ['contents', basic.fixed_list(36, basic.uint8_t)], ]; } export class EmberSignature283k1Data extends EzspStruct { // An ECDSA signature static _fields = [ // The 283k1 signature data. ['contents', basic.fixed_list(72, basic.uint8_t)], ]; } export class EmberMessageDigest extends EzspStruct { // The calculated digest of a message static _fields = [ // The calculated digest of a message. ['contents', basic.fixed_list(16, basic.uint8_t)], ]; } export class EmberAesMmoHashContext extends EzspStruct { // The hash context for an ongoing hash operation. static _fields = [ // The result of ongoing the hash operation. ['result', basic.fixed_list(16, basic.uint8_t)], // The total length of the data that has been hashed so far. ['length', basic.uint32_t], ]; } export class EmberNeighborTableEntry extends EzspStruct { // A neighbor table entry stores information about the reliability of RF // links to and from neighboring nodes. static _fields = [ // The neighbor's two byte network id ['shortId', basic.uint16_t], // An exponentially weighted moving average of the link quality values // of incoming packets from this neighbor as reported by the PHY. ['averageLqi', basic.uint8_t], // The incoming cost for this neighbor, computed from the average LQI. // Values range from 1 for a good link to 7 for a bad link. ['inCost', basic.uint8_t], // The outgoing cost for this neighbor, obtained from the most recently // received neighbor exchange message from the neighbor. A value of zero // means that a neighbor exchange message from the neighbor has not been // received recently enough, or that our id was not present in the most // recently received one. ['outCost', basic.uint8_t], // The number of aging periods elapsed since a link status message was // last received from this neighbor. The aging period is 16 seconds. ['age', basic.uint8_t], // The 8 byte EUI64 of the neighbor. ['longId', named.EmberEUI64], ]; } export class EmberRouteTableEntry extends EzspStruct { // A route table entry stores information about the next hop along the route // to the destination. static _fields = [ // The short id of the destination. A value of 0xFFFF indicates the // entry is unused. ['destination', basic.uint16_t], // The short id of the next hop to this destination. ['nextHop', basic.uint16_t], // Indicates whether this entry is active [0], being discovered [1]], // unused [3], or validating [4]. ['status', basic.uint8_t], // The number of seconds since this route entry was last used to send a // packet. ['age', basic.uint8_t], // Indicates whether this destination is a High RAM Concentrator [2], a // Low RAM Concentrator [1], or not a concentrator [0]. ['concentratorType', basic.uint8_t], // For a High RAM Concentrator, indicates whether a route record is // needed [2], has been sent [1], or is no long needed [0] because a // source routed message from the concentrator has been received. ['routeRecordState', basic.uint8_t], ]; } export class EmberInitialSecurityState extends EzspStruct { public bitmask: number; public preconfiguredKey: EmberKeyData; public networkKey: EmberKeyData; public networkKeySequenceNumber: number; public preconfiguredTrustCenterEui64: named.EmberEUI64; // The security data used to set the configuration for the stack, or the // retrieved configuration currently in use. static _fields = [ // A bitmask indicating the security state used to indicate what the // security configuration will be when the device forms or joins the // network. ['bitmask', named.EmberInitialSecurityBitmask], // The pre-configured Key data that should be used when forming or // joining the network. The security bitmask must be set with the // HAVE_PRECONFIGURED_KEY bit to indicate that the key contains valid // data. ['preconfiguredKey', EmberKeyData], // The Network Key that should be used by the Trust Center when it forms // the network, or the Network Key currently in use by a joined device. // The security bitmask must be set with HAVE_NETWORK_KEY to indicate // that the key contains valid data. ['networkKey', EmberKeyData], // The sequence number associated with the network key. This is only // valid if the HAVE_NETWORK_KEY has been set in the security bitmask. ['networkKeySequenceNumber', basic.uint8_t], // This is the long address of the trust center on the network that will // be joined. It is usually NOT set prior to joining the network and // instead it is learned during the joining message exchange. This field // is only examined if HAVE_TRUST_CENTER_EUI64 is set in the // EmberInitialSecurityState::bitmask. Most devices should clear that // bit and leave this field alone. This field must be set when using // commissioning mode. ['preconfiguredTrustCenterEui64', named.EmberEUI64], ]; } export class EmberCurrentSecurityState extends EzspStruct { // The security options and information currently used by the stack. static _fields = [ // A bitmask indicating the security options currently in use by a // device joined in the network. ['bitmask', named.EmberCurrentSecurityBitmask], // The IEEE Address of the Trust Center device. ['trustCenterLongAddress', named.EmberEUI64], ]; } export class EmberKeyStruct extends EzspStruct { // A structure containing a key and its associated data. static _fields = [ // A bitmask indicating the presence of data within the various fields // in the structure. ['bitmask', named.EmberKeyStructBitmask], // The type of the key. ['type', named.EmberKeyType], // The actual key data. ['key', EmberKeyData], // The outgoing frame counter associated with the key. ['outgoingFrameCounter', basic.uint32_t], // The frame counter of the partner device associated with the key. ['incomingFrameCounter', basic.uint32_t], // The sequence number associated with the key. ['sequenceNumber', basic.uint8_t], // The IEEE address of the partner device also in possession of the key. ['partnerEUI64', named.EmberEUI64], ]; } export class EmberNetworkInitStruct extends EzspStruct { // Network Initialization parameters. static _fields = [ // Configuration options for network init. ['bitmask', named.EmberNetworkInitBitmask], ]; } export class EmberZllSecurityAlgorithmData extends EzspStruct { // Data associated with the ZLL security algorithm. static _fields = [ // Transaction identifier. ['transactionId', basic.uint32_t], // Response identifier. ['responseId', basic.uint32_t], // Bitmask. ['bitmask', basic.uint16_t], ]; } export class EmberZllNetwork extends EzspStruct { // The parameters of a ZLL network. static _fields = [ // The parameters of a ZigBee network. ['zigbeeNetwork', EmberZigbeeNetwork], // Data associated with the ZLL security algorithm. ['securityAlgorithm', EmberZllSecurityAlgorithmData], // Associated EUI64. ['eui64', named.EmberEUI64], // The node id. ['nodeId', named.EmberNodeId], // The ZLL state. ['state', named.EmberZllState], // The node type. ['nodeType', named.EmberNodeType], // The number of sub devices. ['numberSubDevices', basic.uint8_t], // The total number of group identifiers. ['totalGroupIdentifiers', basic.uint8_t], // RSSI correction value. ['rssiCorrection', basic.uint8_t], ]; } export class EmberZllInitialSecurityState extends EzspStruct { // Describes the initial security features and requirements that will be // used when forming or joining ZLL networks. static _fields = [ // Unused bitmask; reserved for future use. ['bitmask', basic.uint32_t], // The key encryption algorithm advertised by the application. ['keyIndex', named.EmberZllKeyIndex], // The encryption key for use by algorithms that require it. ['encryptionKey', EmberKeyData], // The pre-configured link key used during classical ZigBee // commissioning. ['preconfiguredKey', EmberKeyData], ]; } export class EmberZllDeviceInfoRecord extends EzspStruct { // Information about a specific ZLL Device. static _fields = [ // EUI64 associated with the device. ['ieeeAddress', named.EmberEUI64], // Endpoint id. ['endpointId', basic.uint8_t], // Profile id. ['profileId', basic.uint16_t], // Device id. ['deviceId', basic.uint16_t], // Associated version. ['version', basic.uint8_t], // Number of relevant group ids. ['groupIdCount', basic.uint8_t], ]; } export class EmberZllAddressAssignment extends EzspStruct { // ZLL address assignment data. static _fields = [ // Relevant node id. ['nodeId', named.EmberNodeId], // Minimum free node id. ['freeNodeIdMin', named.EmberNodeId], // Maximum free node id. ['freeNodeIdMax', named.EmberNodeId], // Minimum group id. ['groupIdMin', named.EmberMulticastId], // Maximum group id. ['groupIdMax', named.EmberMulticastId], // Minimum free group id. ['freeGroupIdMin', named.EmberMulticastId], // Maximum free group id. ['freeGroupIdMax', named.EmberMulticastId], ]; } export class EmberTokTypeStackZllData extends EzspStruct { // Public API for ZLL stack data token. static _fields = [ // Token bitmask. ['bitmask', basic.uint32_t], // Minimum free node id. ['freeNodeIdMin', basic.uint16_t], // Maximum free node id. ['freeNodeIdMax', basic.uint16_t], // Local minimum group id. ['myGroupIdMin', basic.uint16_t], // Minimum free group id. ['freeGroupIdMin', basic.uint16_t], // Maximum free group id. ['freeGroupIdMax', basic.uint16_t], // RSSI correction value. ['rssiCorrection', basic.uint8_t], ]; } export class EmberTokTypeStackZllSecurity extends EzspStruct { // Public API for ZLL stack security token. static _fields = [ // Token bitmask. ['bitmask', basic.uint32_t], // Key index. ['keyIndex', basic.uint8_t], // Encryption key. ['encryptionKey', basic.fixed_list(16, basic.uint8_t)], // Preconfigured key. ['preconfiguredKey', basic.fixed_list(16, basic.uint8_t)], ]; } export class EmberRf4ceVendorInfo extends EzspStruct { // The RF4CE vendor information block. static _fields = [ // The vendor identifier field shall contain the vendor identifier of // the node. ['vendorId', basic.uint16_t], // The vendor string field shall contain the vendor string of the node. ['vendorString', basic.fixed_list(7, basic.uint8_t)], ]; } export class EmberRf4ceApplicationInfo extends EzspStruct { // The RF4CE application information block. static _fields = [ // The application capabilities field shall contain information relating // to the capabilities of the application of the node. ['capabilities', named.EmberRf4ceApplicationCapabilities], // The user string field shall contain the user specified identification // string. ['userString', basic.fixed_list(15, basic.uint8_t)], // The device type list field shall contain the list of device types // supported by the node. ['deviceTypeList', basic.fixed_list(3, basic.uint8_t)], // The profile ID list field shall contain the list of profile // identifiers disclosed as supported by the node. ['profileIdList', basic.fixed_list(7, basic.uint8_t)], ]; } export class EmberRf4cePairingTableEntry extends EzspStruct { // The internal representation of an RF4CE pairing table entry. static _fields = [ // The link key to be used to secure this pairing link. ['securityLinkKey', EmberKeyData], // The IEEE address of the destination device. ['destLongId', named.EmberEUI64], // The frame counter last received from the recipient node. ['frameCounter', basic.uint32_t], // The network address to be assumed by the source device. ['sourceNodeId', named.EmberNodeId], // The PAN identifier of the destination device. ['destPanId', named.EmberPanId], // The network address of the destination device. ['destNodeId', named.EmberNodeId], // The vendor ID of the destination device. ['destVendorId', basic.uint16_t], // The list of profiles supported by the destination device. ['destProfileIdList', basic.fixed_list(7, basic.uint8_t)], // The length of the list of supported profiles. ['destProfileIdListLength', basic.uint8_t], // Info byte. ['info', basic.uint8_t], // The expected channel of the destination device. ['channel', basic.uint8_t], // The node capabilities of the recipient node. ['capabilities', basic.uint8_t], // Last MAC sequence number seen on this pairing link. ['lastSeqn', basic.uint8_t], ]; } export class EmberGpAddress extends EzspStruct { // A GP address structure. static _fields = [ // The GPD's EUI64. ['gpdIeeeAddress', named.EmberEUI64], // The GPD's source ID. ['sourceId', basic.uint32_t], // The GPD Application ID. ['applicationId', basic.uint8_t], // The GPD endpoint. ['endpoint', basic.uint8_t], ]; } export class EmberGpSinkListEntry extends EzspStruct { // A sink list entry static _fields = [ // The sink list type. ['type', basic.uint8_t], // The EUI64 of the target sink. ['sinkEUI', named.EmberEUI64], // The short address of the target sink. ['sinkNodeId', named.EmberNodeId], ]; } export class EmberNodeDescriptor extends EzspStruct { static _fields = [ ['byte1', basic.uint8_t], ['byte2', basic.uint8_t], ['mac_capability_flags', basic.uint8_t], ['manufacturer_code', basic.uint16_t], ['maximum_buffer_size', basic.uint8_t], ['maximum_incoming_transfer_size', basic.uint16_t], ['server_mask', basic.uint16_t], ['maximum_outgoing_transfer_size', basic.uint16_t], ['descriptor_capability_field', basic.uint8_t], ]; } export class EmberSimpleDescriptor extends EzspStruct { static _fields = [ ['endpoint', basic.uint8_t], ['profileid', basic.uint16_t], ['deviceid', basic.uint16_t], ['deviceversion', basic.uint8_t], ['inclusterlist', basic.LVList(basic.uint16_t)], ['outclusterlist', basic.LVList(basic.uint16_t)], ]; } export class EmberMultiAddress extends EzspStruct { static fields3 = [ ['addrmode', basic.uint8_t], ['ieee', named.EmberEUI64], ['endpoint', basic.uint8_t], ]; static fields1 = [ ['addrmode', basic.uint8_t], ['nwk', named.EmberNodeId], ]; /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ static serialize(cls: any, obj: any): Buffer { const addrmode = obj['addrmode']; /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ const fields = (addrmode == 3) ? cls.fields3 : cls.fields1; /* eslint-disable-next-line @typescript-eslint/no-explicit-any*/ return Buffer.concat(fields.map((field: any[]) => { const value = obj[field[0]]; console.assert(field[1]); return field[1].serialize(field[1], value); })); } } export class EmberNeighbor extends EzspStruct { static _fields = [ ['extendedpanid', basic.fixed_list(8, basic.uint8_t)], ['ieee', named.EmberEUI64], ['nodeid', named.EmberNodeId], ['packed', basic.uint8_t], ['permitjoining', basic.uint8_t], ['depth', basic.uint8_t], ['lqi', basic.uint8_t], ]; } export class EmberNeighbors extends EzspStruct { static _fields = [ ['entries', basic.uint8_t], ['startindex', basic.uint8_t], ['neighbors', basic.LVList(EmberNeighbor)], ]; }
the_stack
declare namespace BABYLON { /** * Background material */ class BackgroundMaterial extends BABYLON.PushMaterial { /** * Key light Color (multiply against the R channel of the environement texture) */ protected _primaryColor: Color3; primaryColor: Color3; /** * Key light Level (allowing HDR output of the background) */ protected _primaryLevel: float; primaryLevel: float; /** * Secondary light Color (multiply against the G channel of the environement texture) */ protected _secondaryColor: Color3; secondaryColor: Color3; /** * Secondary light Level (allowing HDR output of the background) */ protected _secondaryLevel: float; secondaryLevel: float; /** * Tertiary light Color (multiply against the B channel of the environement texture) */ protected _tertiaryColor: Color3; tertiaryColor: Color3; /** * Tertiary light Level (allowing HDR output of the background) */ protected _tertiaryLevel: float; tertiaryLevel: float; /** * Reflection Texture used in the material. * Should be author in a specific way for the best result (refer to the documentation). */ protected _reflectionTexture: Nullable<BaseTexture>; reflectionTexture: Nullable<BaseTexture>; /** * Reflection Texture level of blur. * * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the * texture twice. */ protected _reflectionBlur: float; reflectionBlur: float; /** * Diffuse Texture used in the material. * Should be author in a specific way for the best result (refer to the documentation). */ protected _diffuseTexture: Nullable<BaseTexture>; diffuseTexture: Nullable<BaseTexture>; /** * Specify the list of lights casting shadow on the material. * All scene shadow lights will be included if null. */ protected _shadowLights: Nullable<IShadowLight[]>; shadowLights: Nullable<IShadowLight[]>; /** * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach * soft lighting on the background. */ protected _shadowBlurScale: int; shadowBlurScale: int; /** * Helps adjusting the shadow to a softer level if required. * 0 means black shadows and 1 means no shadows. */ protected _shadowLevel: float; shadowLevel: float; /** * In case of opacity Fresnel or reflection falloff, this is use as a scene center. * It is usually zero but might be interesting to modify according to your setup. */ protected _sceneCenter: Vector3; sceneCenter: Vector3; /** * This helps specifying that the material is falling off to the sky box at grazing angle. * This helps ensuring a nice transition when the camera goes under the ground. */ protected _opacityFresnel: boolean; opacityFresnel: boolean; /** * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle. * This helps adding a mirror texture on the ground. */ protected _reflectionFresnel: boolean; reflectionFresnel: boolean; /** * This helps specifying the falloff radius off the reflection texture from the sceneCenter. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance. */ protected _reflectionFalloffDistance: number; reflectionFalloffDistance: number; /** * This specifies the weight of the reflection against the background in case of reflection Fresnel. */ protected _reflectionAmount: number; reflectionAmount: number; /** * This specifies the weight of the reflection at grazing angle. */ protected _reflectionReflectance0: number; reflectionReflectance0: number; /** * This specifies the weight of the reflection at a perpendicular point of view. */ protected _reflectionReflectance90: number; reflectionReflectance90: number; /** * Helps to directly use the maps channels instead of their level. */ protected _useRGBColor: boolean; useRGBColor: boolean; /** * Number of Simultaneous lights allowed on the material. */ private _maxSimultaneousLights; maxSimultaneousLights: int; /** * Default configuration related to image processing available in the Background Material. */ protected _imageProcessingConfiguration: ImageProcessingConfiguration; /** * Keep track of the image processing observer to allow dispose and replace. */ private _imageProcessingObserver; /** * Attaches a new image processing configuration to the PBR Material. * @param configuration (if null the scene configuration will be use) */ protected _attachImageProcessingConfiguration(configuration: Nullable<ImageProcessingConfiguration>): void; /** * Gets the image processing configuration used either in this material. */ /** * Sets the Default image processing configuration used either in the this material. * * If sets to null, the scene one is in use. */ imageProcessingConfiguration: Nullable<ImageProcessingConfiguration>; /** * Gets wether the color curves effect is enabled. */ /** * Sets wether the color curves effect is enabled. */ cameraColorCurvesEnabled: boolean; /** * Gets wether the color grading effect is enabled. */ /** * Gets wether the color grading effect is enabled. */ cameraColorGradingEnabled: boolean; /** * Gets wether tonemapping is enabled or not. */ /** * Sets wether tonemapping is enabled or not */ cameraToneMappingEnabled: boolean; /** * The camera exposure used on this material. * This property is here and not in the camera to allow controlling exposure without full screen post process. * This corresponds to a photographic exposure. */ /** * The camera exposure used on this material. * This property is here and not in the camera to allow controlling exposure without full screen post process. * This corresponds to a photographic exposure. */ cameraExposure: float; /** * Gets The camera contrast used on this material. */ /** * Sets The camera contrast used on this material. */ cameraContrast: float; /** * Gets the Color Grading 2D Lookup Texture. */ /** * Sets the Color Grading 2D Lookup Texture. */ cameraColorGradingTexture: Nullable<BaseTexture>; /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ /** * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT). * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image; * corresponding to low luminance, medium luminance, and high luminance areas respectively. */ cameraColorCurves: Nullable<ColorCurves>; private _renderTargets; private _reflectionControls; /** * constructor * @param name The name of the material * @param scene The scene to add the material to */ constructor(name: string, scene: BABYLON.Scene); /** * The entire material has been created in order to prevent overdraw. * @returns false */ needAlphaTesting(): boolean; /** * The entire material has been created in order to prevent overdraw. * @returns true if blending is enable */ needAlphaBlending(): boolean; /** * Checks wether the material is ready to be rendered for a given mesh. * @param mesh The mesh to render * @param subMesh The submesh to check against * @param useInstances Specify wether or not the material is used with instances */ isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean; /** * Build the uniform buffer used in the material. */ buildUniformLayout(): void; /** * Unbind the material. */ unbind(): void; /** * Bind only the world matrix to the material. * @param world The world matrix to bind. */ bindOnlyWorldMatrix(world: Matrix): void; /** * Bind the material for a dedicated submeh (every used meshes will be considered opaque). * @param world The world matrix to bind. * @param subMesh The submesh to bind for. */ bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void; /** * Dispose the material. * @forceDisposeEffect Force disposal of the associated effect. * @forceDisposeTextures Force disposal of the associated textures. */ dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean): void; /** * Clones the material. * @name The cloned name. * @returns The cloned material. */ clone(name: string): BackgroundMaterial; /** * Serializes the current material to its JSON representation. * @returns The JSON representation. */ serialize(): any; /** * Gets the class name of the material * @returns "BackgroundMaterial" */ getClassName(): string; /** * Parse a JSON input to create back a background material. * @param source * @param scene * @param rootUrl * @returns the instantiated BackgroundMaterial. */ static Parse(source: any, scene: Scene, rootUrl: string): BackgroundMaterial; } }
the_stack
import * as fs from "fs"; import * as path from "path"; import * as fse from "fs-extra"; import * as handlebars from "handlebars"; import * as prettier from "prettier"; import { IBlueprintWriterSession } from "@bluelibs/terminal-bundle"; import { mergeTypeDefs, printTypeNode, printWithComments, } from "@graphql-tools/merge"; import { XSession } from "./XSession"; const TPL_EXTENSION = ".tpl"; const TEMPLATES_DIR = __dirname + "/../../templates"; export type SessionCopyOptions = { ignoreIfExists?: boolean; ignoreIfContains?: string; }; export const SessionCopyOptionsDefaults = { ignoreIfExists: false, ignoreIfContains: null, }; /** * The purpose of this class is to perform FS operations on a Session for a given model that is passed to templates. */ export class FSOperator { constructor(public readonly session: XSession, public readonly model: any) {} isTemplate(content: string) { return Boolean(content.match("{{(.*)}}")); } add(paths: string | string[], fn) { this.session.addOperation({ type: "custom", paths: Array.isArray(paths) ? paths : [paths], value: fn, }); } getTemplatePath(templatePath: string) { return path.join(TEMPLATES_DIR, templatePath); } getTemplatePathCreator(prefix: string) { return (templatePath: string = "") => { return this.getTemplatePath( path.join(prefix, ...templatePath.split("/")) ); }; } getContents(fullPath: string) { return fs.readFileSync(fullPath).toString(); } /** * Appends content only if it doesn't exist * @param filePath * @param content */ sessionAppendFile(filePath, content) { this.add([filePath], () => { fse.ensureFileSync(filePath); let fileContent = this.getContents(filePath); content = this.renderTemplate(content, filePath); if (fileContent.indexOf(content) === -1) { fileContent = fileContent + content; this.writeFileSmartly(filePath, fileContent); } }); } /** * Prepends content only if it does not exist * @param filePath * @param content */ sessionPrependFile(filePath, content) { this.add([filePath], () => { fse.ensureFileSync(filePath); let fileContent = fs.readFileSync(filePath).toString(); content = this.renderTemplate(content, filePath); if (fileContent.indexOf(content) === -1) { fileContent = content + fileContent; this.writeFileSmartly(filePath, fileContent); } }); } sessionMergeTypeDefs(sourcePath, targetPath: string) { this.add([targetPath], () => { const mother = this.getContents(targetPath); const extension = this.renderTemplate( this.getContents(sourcePath), sourcePath ); const contents = mother !== "" ? printWithComments(mergeTypeDefs([mother, extension])) : extension; this.writeFileSmartly(targetPath, contents); }); } sessionWrite(filePath, content) { this.add([filePath], () => { fse.ensureFileSync(filePath); this.writeFileSmartly(filePath, content); }); } /** * This method creates an operation which allows us to have dynamic folder names * And handlebars template files * * @param src * @param dest * @param model */ sessionCopy( src, dest, options: SessionCopyOptions = SessionCopyOptionsDefaults ) { let paths; const isSourceADirectory = fs.lstatSync(src).isDirectory(); if (isSourceADirectory) { paths = this.extractFiles(src, { includeFolders: true }).map((p) => this.transformFilePath(p.replace(src, dest)) ); } else { paths = [this.transformFilePath(dest)]; } this.add(paths, () => { let allFilePaths = isSourceADirectory ? this.extractFiles(src) : [src]; fse.copySync(src, dest, { filter: (src, dest) => { const shouldOverride = this.shouldOverrideFileBasedOnOptions( dest, options ); if (!shouldOverride) { allFilePaths = allFilePaths.filter((path) => path !== src); } return shouldOverride; }, }); // Process Templating allFilePaths.forEach((filePath) => { filePath = filePath.replace(src, dest); const content = this.getContents(filePath); this.writeFileSmartly( filePath, this.isTemplate(content) ? this.renderTemplate(content, filePath) : content, false ); }); // Rename Folders if (fs.lstatSync(dest).isDirectory()) { this.renameFiles(dest); } else { this.renameFile(dest); } }); } /** * Renders the template for the current model */ renderTemplate(content: string, filePath?: string, silent?: boolean): string { try { return handlebars.compile(content, { noEscape: true, })(this.model, { allowProtoMethodsByDefault: true, allowProtoPropertiesByDefault: true, }); } catch (e) { console.error(`Error copying template over: `, { filePath }, e); throw e; } } /** * Writes the file prettier aware * @param filePath * @param content */ writeFileSmartly(filePath, content, shouldRenderContent = true) { if (shouldRenderContent) content = this.renderTemplate(content, filePath); const prettierParserType = this.getPrettierParser(filePath); if (prettierParserType) { try { content = prettier.format(content, { trailingComma: "es5", tabWidth: 2, singleQuote: false, // @ts-ignore parser: prettierParserType, }); } catch (e) { console.warn( `File ${filePath} could not be prettier formatted because it has an error` ); console.warn(e); } } fs.writeFileSync(filePath, content); } /** * This ensures that the file path is transformed properly including renaming ___VARIABLE___ stuff * This does not do anything to the session * @param filePath * @param model */ transformFilePath(filePath): string { if (path.extname(filePath) === TPL_EXTENSION) { filePath = filePath.slice(0, filePath.length - TPL_EXTENSION.length); } const extractions = filePath.match(/___([^_]+)___/g); if (extractions) { extractions.forEach((extraction) => { const variable = extraction.slice(3, extraction.length - 3); let value = this.model[variable]; if (!value) { value = `VALUE_FOR_${variable}_NOT_FOUND`; } filePath = filePath.replace(extraction, value, "g"); }); } return filePath; } /** * Performs operations to file system */ renameFiles(src) { const files = fs.readdirSync(src); files.forEach((file) => { if (file === "node_modules") { return; } const filePath = path.join(src, file); let stat = fs.lstatSync(filePath); if (stat.isFile()) { this.renameFile(filePath); } else { this.renameFiles(filePath); } }); } renameFile(filePath) { const newFilePath = this.transformFilePath(filePath); if (filePath !== newFilePath) { fse.renameSync(filePath, newFilePath); } } /** * Extracts all the files and optionally folders from a path * @param src * @param options */ extractFiles(src, options = { includeFolders: false }) { const filesArray = []; const files = fs.readdirSync(src); files.forEach((file) => { const filePath = path.join(src, file); const stat = fs.lstatSync(filePath); if (stat.isFile()) { filesArray.push(filePath); } else if (stat.isDirectory()) { if (options.includeFolders) { filesArray.push(filePath + "/"); } filesArray.push(...this.extractFiles(filePath)); } }); return filesArray; } /** * Returns the correct parser for the file so it can be prettified. * @param filePath */ getPrettierParser(filePath): string { const newFilePath = this.transformFilePath(filePath); const extName = path.extname(newFilePath); if (extName === ".ts") { return "babel-ts"; } switch (extName) { case ".ts": case ".tsx": return "babel-ts"; case ".gql": case ".graphql": return "graphql"; case ".html": return "html"; case ".json": return "json"; case ".mdx": case ".md": return "markdown"; case ".scss": return "scss"; case ".css": return "css"; case ".less": return "less"; } } /** * Returns the nearest microservice * @param type * @param starting */ getNearest(type: "microservice" | "project", starting = process.cwd()) { if (starting === "/") { throw new Error("Could not find a parent folder for type: " + type); } const filePath = path.join(starting, "package.json"); if (fs.existsSync(filePath)) { const packageJson = fse.readJSONSync(filePath); if (packageJson.x && packageJson.x.type === type) { return path.dirname(filePath); } } return this.getNearest(type, path.join(starting, "..")); } /** * Here we check whether or not to override the file. * If the file exists and `options.ignoreIfExists` it will return false * If the file exists and contains `options.ignoreIfContains` it will return false * @param dest * @param options * @returns */ protected shouldOverrideFileBasedOnOptions( dest, options: SessionCopyOptions ): boolean { if (this.session.isOverrideMode) { return true; } const filePath = this.transformFilePath(dest); if (!fs.existsSync(filePath)) { return true; } const isFile = !fs.lstatSync(filePath).isDirectory(); if (isFile) { const exists = fs.existsSync(filePath); if (options.ignoreIfExists) { if (exists) { this.session.afterCommit(() => { const relativePath = path.relative(process.cwd(), filePath); console.log( `➤ File "${relativePath}" was not copied over because of it already exists.` ); }); } return !exists; } if (exists && options.ignoreIfContains) { const containsContent = fs .readFileSync(filePath) .toString() .indexOf(options.ignoreIfContains) !== -1; if (containsContent) { this.session.afterCommit(() => { const relativePath = path.relative(process.cwd(), filePath); console.log( `➤ File "${relativePath}" was not copied over because of its contents.` ); }); return false; } } } return true; } }
the_stack
import { action, computed, observable, runInAction } from 'mobx'; import { ActionProps, createActionBindings } from '../../lib/ActionBinding'; import Reaction, { createReactions } from '../../lib/mobx/Reaction'; import { Store } from '../../lib/Store'; import { isDefined } from '../../lib/types'; import { paymentAddressDetailTransformer, stakeAddressDetailTransformer, } from '../address/api/transformers'; import { ADDRESS_SEARCH_RESULT_PATH } from '../address/config'; import { IAddressSummary, IPaymentAddressSummary, IStakeAddressSummary, } from '../address/types'; import { blockDetailsTransformer } from '../blocks/api/transformers'; import { BLOCK_SEARCH_RESULT_PATH } from '../blocks/config'; import { IBlockDetailed } from '../blocks/types'; import { epochOverviewTransformer } from '../epochs/api/transformers'; import { EPOCH_SEARCH_RESULT_PATH } from '../epochs/config'; import { IEpochOverview } from '../epochs/types'; import { transactionDetailsTransformer } from '../transactions/api/transformers'; import { TRANSACTION_SEARCH_RESULT_PATH } from '../transactions/config'; import { ITransactionDetails } from '../transactions/types'; import { SearchApi } from './api'; import { NO_SEARCH_RESULTS_PATH } from './config'; import { INavigationFeatureDependency, INetworkInfoFeatureDependency, SearchActions, } from './index'; export enum SearchType { address = 'Address', id = 'ID', number = 'Number', unknown = 'Unknown', } export class SearchStore extends Store { @observable public blockSearchResult: IBlockDetailed | null = null; @observable public epochSearchResult: IEpochOverview | null = null; @observable public paymentAddressSearchResult: IPaymentAddressSummary | null = null; @observable public stakeAddressSearchResult: IStakeAddressSummary | null = null; @observable public transactionSearchResult: ITransactionDetails | null = null; private readonly searchApi: SearchApi; private readonly searchActions: SearchActions; private readonly navigation: INavigationFeatureDependency; private readonly networkInfo: INetworkInfoFeatureDependency; private readonly watchEpochReaction: Reaction[]; @observable private watchedEpochNumber: number | null = null; constructor( searchActions: SearchActions, searchApi: SearchApi, navigation: INavigationFeatureDependency, networkInfo: INetworkInfoFeatureDependency ) { super(); this.searchApi = searchApi; this.searchActions = searchActions; this.navigation = navigation; this.networkInfo = networkInfo; this.registerActions( createActionBindings([ [ this.searchActions.addressSearchRequested, this.onAddressSearchRequested, ], [ this.searchActions.blockNumberSearchRequested, this.onSearchByBlockNumberRequested, ], [this.searchActions.idSearchRequested, this.onIdSearchRequested], [ this.searchActions.epochNumberSearchRequested, this.onSearchByEpochNumberRequested, ], [this.searchActions.searchById, this.searchById], [ this.searchActions.searchForPaymentAddress, this.searchForPaymentAddress, ], [this.searchActions.searchForStakeAddress, this.searchForStakeAddress], [ this.searchActions.searchForBlockByNumber, this.searchForBlockByNumber, ], [ this.searchActions.searchForBlockBySlotNumber, this.searchForBlockBySlotNumber, ], [ this.searchActions.searchForEpochByNumber, this.searchForEpochByNumber, ], [ this.searchActions.slotNumberSearchRequested, this.onSearchBySlotNumberRequested, ], [ this.searchActions.unknownSearchRequested, this.onUnknownSearchRequested, ], [this.searchActions.subscribeToEpoch, this.subscribeToEpochByNumber], [ this.searchActions.unsubscribeFromEpoch, this.unsubscribeFromEpochByNumber, ], ]) ); this.watchEpochReaction = createReactions([ this.fetchWatchedEpochOnBlockHeightChange, ]); } @computed get isSearching() { return ( this.searchApi.searchByIdQuery.isExecuting || this.searchApi.searchForBlockByNumberQuery.isExecuting || this.searchApi.searchForEpochByNumberQuery.isExecuting || this.searchApi.searchForPaymentAddressQuery.isExecuting || this.searchApi.searchForStakeAddressQuery.isExecuting ); } // ========= PRIVATE ACTION HANDLERS ========== private onAddressSearchRequested = async ({ address, }: { address: string; }) => { this.navigation.actions.push.trigger({ path: ADDRESS_SEARCH_RESULT_PATH, query: { address }, }); }; /** * Executes query for entities by ID, determining the intent from the result * * Redirects to the corresponding search result or "no result" page. * * @param id */ private onIdSearchRequested = async ({ id }: { id: string }) => { const result = await this.searchApi.searchByIdQuery.execute({ id, }); if (result && result?.blocks.length > 0) { const blockData = result.blocks[0]; if (isDefined(blockData)) { runInAction(() => { this.blockSearchResult = blockDetailsTransformer(blockData); }); this.navigation.actions.push.trigger({ path: BLOCK_SEARCH_RESULT_PATH, query: { id }, }); } } else if (result && result?.transactions.length > 0) { const txSearchResult = result.transactions[0]; if (isDefined(txSearchResult)) { runInAction(() => { this.transactionSearchResult = transactionDetailsTransformer( txSearchResult ); }); this.navigation.actions.push.trigger({ path: TRANSACTION_SEARCH_RESULT_PATH, query: { id }, }); } } else { return this.onUnknownSearchRequested({ query: id }); } }; @action private onSearchByBlockNumberRequested = async (params: { number: number; }) => { await this.searchForBlockByNumber({ number: params.number }); if (this.blockSearchResult?.id) { this.navigation.actions.push.trigger({ path: BLOCK_SEARCH_RESULT_PATH, query: { id: this.blockSearchResult?.id }, }); } }; @action private onSearchBySlotNumberRequested = async (params: { slotNo: number; }) => { await this.searchForBlockBySlotNumber({ slotNo: params.slotNo }); if (this.blockSearchResult?.id) { this.navigation.actions.push.trigger({ path: BLOCK_SEARCH_RESULT_PATH, query: { id: this.blockSearchResult?.id }, }); } }; private onSearchByEpochNumberRequested = async (params: { number: number; }) => { this.navigation.actions.push.trigger({ path: EPOCH_SEARCH_RESULT_PATH, query: { number: params.number, }, }); }; private onUnknownSearchRequested = async (params: { query: string }) => { this.navigation.actions.push.trigger({ path: NO_SEARCH_RESULTS_PATH, query: params, }); }; @action private searchForPaymentAddress = async ({ address, }: { address: string; }) => { // Do not execute queries more than necessary! if ( this.searchApi.searchForPaymentAddressQuery.isExecuting || this.paymentAddressSearchResult?.address === address ) { return; } this.paymentAddressSearchResult = null; this.stakeAddressSearchResult = null; const result = await this.searchApi.searchForPaymentAddressQuery.execute({ address, }); if (isDefined(result)) { if ( result.transactions_aggregate.aggregate?.count === '0' && result.paymentAddresses![0]?.summary!.assetBalances?.length === 0 ) { return this.searchActions.unknownSearchRequested.trigger({ query: address, }); } runInAction(() => { this.paymentAddressSearchResult = paymentAddressDetailTransformer( address, result ); }); } }; @action private searchForStakeAddress = async ({ address, }: { address: string; }) => { // Do not execute queries more than necessary! if ( this.searchApi.searchForStakeAddressQuery.isExecuting || this.stakeAddressSearchResult?.address === address ) { return; } this.stakeAddressSearchResult = null; this.paymentAddressSearchResult = null; const result = await this.searchApi.searchForStakeAddressQuery.execute({ address, }); if (isDefined(result)) { if (result.withdrawals_aggregate?.aggregate?.count === '0') { return this.searchActions.unknownSearchRequested.trigger({ query: address, }); } runInAction(() => { this.stakeAddressSearchResult = stakeAddressDetailTransformer( address, result ); }); } }; @action private searchById = async ({ id }: { id: string }) => { // Do not execute queries more than necessary! if ( this.searchApi.searchByIdQuery.isExecuting || this.blockSearchResult?.id === id || this.transactionSearchResult?.id === id ) { return; } this.blockSearchResult = null; this.transactionSearchResult = null; return this.onIdSearchRequested({ id }); }; @action private searchForBlockByNumber = async (params: { number: number; }) => { // Do not trigger another search if we already have the requested data! if ( this.searchApi.searchForBlockByNumberQuery.isExecuting || this.blockSearchResult?.number === params.number ) { return; } this.blockSearchResult = null; const result = await this.searchApi.searchForBlockByNumberQuery.execute( params ); if (result) { const blockData = result.blocks[0]; if (isDefined(blockData)) { runInAction(() => { this.blockSearchResult = blockDetailsTransformer(blockData); }); } } }; @action private searchForBlockBySlotNumber = async (params: { slotNo: number; }) => { // Do not trigger another search if we already have the requested data! if ( this.searchApi.searchForBlockByNumberQuery.isExecuting || this.blockSearchResult?.slotNo === params.slotNo ) { return; } this.blockSearchResult = null; const result = await this.searchApi.searchForBlockBySlotNumberQuery.execute( params ); if (result) { const blockData = result.blocks[0]; if (isDefined(blockData)) { runInAction(() => { this.blockSearchResult = blockDetailsTransformer(blockData); }); } } }; @action private searchForEpochByNumber = async (params: { number: number; }) => { // Do not trigger another search if we already have the requested data! if (this.searchApi.searchForEpochByNumberQuery.isExecuting) { return; } const result = await this.searchApi.searchForEpochByNumberQuery.execute( params ); if (result) { const epochData = result.epochs[0]; if (isDefined(epochData)) { runInAction(() => { this.epochSearchResult = epochOverviewTransformer( epochData, this.networkInfo.store ); }); } } }; @action private subscribeToEpochByNumber = async ( params: ActionProps<typeof SearchActions.prototype.subscribeToEpoch> ) => { this.watchedEpochNumber = params.number; this.startReactions(this.watchEpochReaction); }; @action private unsubscribeFromEpochByNumber = async () => { this.watchedEpochNumber = null; this.stopReactions(this.watchEpochReaction); }; // ============ REACTIONS ============= /** * Re-fetches watched epoch whenever the network block height changes. */ private fetchWatchedEpochOnBlockHeightChange = () => { const { blockHeight } = this.networkInfo.store; if (this.watchedEpochNumber == null) { return; } this.searchForEpochByNumber({ number: this.watchedEpochNumber }); }; }
the_stack
const TARGET_RELATIVE_MARGIN_OF_ERROR = 0.02; const DEFAULT_MAX_TIME = 30; const INITIAL_ITERATION_COUNT = 1; const TARGET_CYCLE_TIME = DEFAULT_MAX_TIME / 10; const INCLUDE_INITIAL_SETUP_IN_MAX_TIME = false; // makes million-docs-tests feasable export interface BenchmarkConfig { readonly name: string; readonly isSync?: boolean; readonly fn: () => Promise<any>|any; readonly before?: (info: {count: number}) => Promise<any>; readonly beforeAll?: () => Promise<any>; readonly maxTime?: number; readonly initialCount?: number; } export type BenchmarkFactories = Array<() => BenchmarkConfig>; export interface Timings { readonly sampleCount: number; readonly meanTime: number; readonly relativeMarginOfError: number; } interface BenchmarkState { readonly timings: Timings; readonly cycles: number; readonly iterationCount: number; readonly elapsedTime: number; readonly elapsedNetTime: number; readonly elapsedTimeForInitialSetUp: number; readonly config: BenchmarkConfig; } interface BenchmarkAction { readonly shouldContinue: boolean; readonly nextIterationCount?: number; } export class BenchmarkCycleDetails { /** * The zero-based index of this cycyle */ public readonly index: number; /** * The number of iterations executed in this cycle */ public readonly iterationCount: number; /** * The total time spent so far */ public readonly elapsedTime: number; /** * The time, in seconds, spent on non-iteration tasks so far */ public readonly setUpTime: number; /** * The statistics collected up to this point */ public readonly timingsSoFar: Timings; constructor(config: {index: number, iterationCount: number, elapsedTime: number, setUpTime: number, timingsSoFar: Timings}) { this.index = config.index; this.iterationCount = config.iterationCount; this.elapsedTime = config.elapsedTime; this.setUpTime = config.setUpTime; this.timingsSoFar = config.timingsSoFar; } } export interface BenchmarkResultConfig { readonly cycles: number; readonly iterationCount: number; readonly meanTime: number; readonly relativeMarginOfError: number; readonly elapsedTime: number; readonly setUpTime: number; readonly cycleDetails: BenchmarkCycleDetails[]; } export class BenchmarkResult { /** * The number of cycles */ public readonly cycles: number; /** * Detailed information about each cycle */ public readonly cycleDetails: BenchmarkCycleDetails[]; /** * The mean time, in seconds, per iteration */ public readonly meanTime: number; /** * The relative margin of error of the meanTime */ public readonly relativeMarginOfError: number; /** * The total time, in seconds, the whole benchmark took */ public readonly elapsedTime: number; /** * The total time spent on non-iteration tasks */ public readonly setUpTime: number; /** * The total number of iterations */ public readonly iterationCount: number; constructor(config: BenchmarkResultConfig) { this.cycles = config.cycles; this.meanTime = config.meanTime; this.relativeMarginOfError = config.relativeMarginOfError; this.elapsedTime = config.elapsedTime; this.setUpTime = config.setUpTime; this.cycleDetails = config.cycleDetails; this.iterationCount = config.iterationCount; } toString() { return `${(this.meanTime * 1000).toFixed(3)} ms per iteration (±${(this.relativeMarginOfError * 100).toFixed(2)}%)`; } } export interface BenchmarkExecutionCallbacks { readonly onCycleDone?: (cycleDetails: BenchmarkCycleDetails) => void; } const stats = require("stats-lite"); export async function benchmark(config: BenchmarkConfig, callbacks?: BenchmarkExecutionCallbacks): Promise<BenchmarkResult> { async function cycle(count: number): Promise<{times: number[], netTime: number}> { if (config.before) { await config.before({count}); } const timeBefore = time(); for (let i = 0; i < count; i++) { await config.fn(); } const timeAfter = time(); return { times: [ (timeAfter - timeBefore) / count ], netTime: timeAfter - timeBefore }; } async function cycleSync(count: number): Promise<{times: number[], netTime: number}> { if (config.before) { await config.before({count}); } const timeBefore = time(); for (let i = 0; i < count; i++) { config.fn(); } const timeAfter = time(); return { times: [ (timeAfter - timeBefore) / count ], netTime: timeAfter - timeBefore }; } async function cycleDetailed(count: number): Promise<{times: number[], netTime: number}> { if (config.before) { await config.before({count}); } const times = Array(count); for (let i = 0; i < count; i++) { const timeBefore = time(); await config.fn(); const timeAfter = time(); times[i] = timeAfter - timeBefore; } return { times, netTime: stats.sum(times) }; } const startTime = time(); if (config.beforeAll) { await config.beforeAll(); } const elapsedTimeForInitialSetUp = time() - startTime; const times: number[] = []; const cycleDetails: BenchmarkCycleDetails[] = []; let state: BenchmarkState = { elapsedTime: 0, elapsedNetTime: 0, elapsedTimeForInitialSetUp, cycles: 0, iterationCount: 0, config: config, timings: getTimings(times) }; while (true) { // Preparation const iterationCount = nextIterationCount(state); const cycleFn = config.isSync ? cycleSync : iterationCount > 10000 ? cycle : cycleDetailed; if (!iterationCount) { break; } // Run cycle const {netTime, times: cycleTimes} = await cycleFn(iterationCount); // Calculate next state times.push(...cycleTimes); state = { timings: getTimings(times), config: state.config, cycles: state.cycles + 1, iterationCount: state.iterationCount + iterationCount, elapsedTime: time() - startTime, elapsedNetTime: state.elapsedNetTime + netTime, elapsedTimeForInitialSetUp: state.elapsedTimeForInitialSetUp }; // Report status cycleDetails.push(new BenchmarkCycleDetails({ index: state.cycles - 1, elapsedTime: state.elapsedTime, setUpTime: state.elapsedTime - state.elapsedNetTime, iterationCount, timingsSoFar: state.timings })); if (callbacks && callbacks.onCycleDone) { callbacks.onCycleDone(cycleDetails[cycleDetails.length - 1]); } } return new BenchmarkResult({ meanTime: state.timings.meanTime, relativeMarginOfError: state.timings.relativeMarginOfError, cycles: cycleDetails.length, iterationCount: state.iterationCount, elapsedTime: state.elapsedTime, setUpTime: state.elapsedTime - state.elapsedNetTime, cycleDetails }); } function nextIterationCount(state: BenchmarkState): number { const maxTime = state.config.maxTime || DEFAULT_MAX_TIME; let remainingTime = maxTime - state.elapsedTime; if (!INCLUDE_INITIAL_SETUP_IN_MAX_TIME) { // this time is included in elapsedTime, so give it back remainingTime += state.elapsedTimeForInitialSetUp; } // Always do at least one cycle if (state.cycles == 0) { return state.config.initialCount || INITIAL_ITERATION_COUNT; } // Already out of time? if (remainingTime <= 0) { return 0; } // We're accurate enough if (state.timings.relativeMarginOfError < TARGET_RELATIVE_MARGIN_OF_ERROR) { return 0; } // be very careful, but do not abort test just because we have no confidence const errorFactor = Math.min(state.timings.relativeMarginOfError + 1, 10); // Do we still have time for setup? const meanSetUpTime = (state.elapsedTime - state.elapsedNetTime - state.elapsedTimeForInitialSetUp) / state.cycles; if (remainingTime < meanSetUpTime) { return 0; } // try to get to the target cycle time const remainingNetTime = remainingTime - meanSetUpTime; // we don't include the errorFactor in meanTime because it does not matter if a iteration is too long as long as we // don't overshoot the remaining time const remainingNetTimeWithSafetyMargin = remainingNetTime / errorFactor; const targetNetTime = Math.min(remainingNetTimeWithSafetyMargin, TARGET_CYCLE_TIME); return Math.round(targetNetTime / state.timings.meanTime); } export function time() { const hrTime = process.hrtime(); return hrTime[0] + hrTime[1] / 1000000000; } /** * T-Distribution two-tailed critical values for 95% confidence. * For more info see http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm. */ const tTable: {[key: string]: number} = { '1': 12.706, '2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.447, '7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.179, '13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.101, '19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.064, '25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042, 'infinity': 1.96 }; function getTimings(times: number[]): Timings { const mean: number = stats.mean(times); // Compute the sample standard deviation (estimate of the population standard deviation). const sd = stats.stdev(times); // Compute the standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean). const sem = sd / Math.sqrt(times.length); // Compute the degrees of freedom. const df = times.length - 1; // Compute the critical value. const critical = tTable[Math.round(df) || 1] || tTable['infinity']; // Compute the margin of error. const moe = sem * critical; // Compute the relative margin of error. const rme = (moe / mean) || Infinity; return { relativeMarginOfError: rme, meanTime: mean, sampleCount: times.length } }
the_stack
/// <reference path="../metricsPlugin.ts"/> /// <reference path="../../../includes.ts"/> /// <reference path="../services/errorsManager.ts"/> module HawkularMetrics { export interface IAlertDefinitionCondition { triggerId: string; type: string; dataId: any; operator: string; context: any; data2Multiplier?: number; data2Id?: string; period?: string; threshold?: number; } export interface IAlertProperties { to: string; cc: string; description: string; ccResolved: string; } export interface IAlertAction { tenantId: string; actionPlugin: string; actionId: string; states: string; calendar: string; properties?: IAlertProperties; } export interface IAlertDefinitionDampening { triggerId: string; evalTimeSetting: number; triggerMode: string; type: string; } export interface IAlertDefinition { trigger: IAlertTrigger; dampenings: IAlertDefinitionDampening[]; conditions: IAlertDefinitionCondition[]; } export class AlertDefinitionConditionBuilder { private _triggerId: string; private _type: string; private _dataId: string; private _operator: string; private _context: any; private _data2Id: string; private _data2Multiplier: number; private _threshold: number; constructor(type?: string) { this._type = type; } public withTriggerId(value: string) { this._triggerId = value; return this; } public withType(value: string) { this._type = value; return this; } public withDataId(value: string) { this._dataId = value; return this; } public withOperator(value: string) { this._operator = value; return this; } public withContext(value: any) { this._context = value; return this; } public withData2Id(value: string) { this._data2Id = value; return this; } public withData2Multiplier(value: number) { this._data2Multiplier = value; return this; } public withThreshold(value: number) { this._threshold = value; return this; } public build(): IAlertDefinitionCondition { return new AlertDefinitionCondition( this._triggerId, this._dataId, this._data2Id, this._operator, this._context, this._data2Multiplier, this._threshold, this._type ); } } export class AlertDefinitionDampeningBuilder { private _triggerId: string; private _evalTimeSetting: number; private _triggerMode: string; private _type: string; public withTriggerId(value: string) { this._triggerId = value; return this; } public withEvalTimeSetting(value: number) { this._evalTimeSetting = value; return this; } public withTriggerMode(value: string) { this._triggerMode = value; return this; } public withType(value: string) { this._type = value; return this; } public build(): AlertDefinitionDampening { return new AlertDefinitionDampening(this._triggerId, this._triggerMode, this._type, this._evalTimeSetting); } } export class AlertDefinitionCondition implements IAlertDefinitionCondition { public static DEFAULT_COMPARE_TYPE = 'COMPARE'; public static DEFAULT_TRESHOLD_TYPE = 'THRESHOLD'; constructor(public triggerId: string, public dataId: string, public data2Id: string, public operator: string, public context: any, public data2Multiplier: number, public threshold: number, public type: string) { } } export class AlertActionsPropertiesBuilder { private _to: string; private _cc: string; private _description: string; private _ccResolved: string; public withTo(value: string) { this._to = value; return this; } public withCc(value: string) { this._cc = value; return this; } public withDescription(value: string) { this._description = value; return this; } public withCcResolved(value: string) { this._ccResolved = value; return this; } public build(): IAlertProperties { return new AlertProperties(this._ccResolved, this._to, this._cc, this._description); } } export class AlertActionsBuilder { private _tenantId: string; private _actionPlugin: string; private _actionId: string; private _states: string; private _calendar: string; private _properties: any; public withTenantId(value: string) { this._tenantId = value; return this; } public withActionPlugin(value: string) { this._actionPlugin = value; return this; } public withActionId(value: string) { this._actionId = value; return this; } public withStates(value: string) { this._states = value; return this; } public withCalendar(value: string) { this._calendar = value; return this; } public withProperties(value: any) { this._properties = value; return this; } public build(): IAlertAction { return new AlertAction( this._tenantId, this._actionPlugin, this._actionId, this._states, this._calendar, this._properties ); } } export class AlertDefinitionTriggerBuilder { private _name: string; private _id: string; private _description: string; private _autoDisable: boolean; private _autoEnable: boolean; private _autoResolve: boolean; private _actions: any; private _tags: any; private _firingMatch: string; private _context: HawkularMetrics.ITriggerContext; public withName(value: string) { this._name = value; return this; } public withId(value: string) { this._id = value; return this; } public withDescription(value: string) { this._description = value; return this; } public withAutoDisable(value: boolean) { this._autoDisable = value; return this; } public withAutoEnable(value: boolean) { this._autoEnable = value; return this; } public withAutoResolve(value: boolean) { this._autoResolve = value; return this; } public withActions(value: any) { this._actions = value; return this; } public withTags(value: any) { this._tags = value; return this; } public withFiringMatch(value: string) { this._firingMatch = value; return this; } public withContext(value: HawkularMetrics.ITriggerContext) { this._context = value; return this; } public build(): AlertDefinitionTrigger { return new AlertDefinitionTrigger( this._id, this._name, this._description, this._tags, this._context, this._actions, this._firingMatch, this._autoDisable, this._autoEnable, this._autoResolve ); } } export class AlertDefinitionContextBuilder { private _alertType: string; private _resourceType: string; private _resourcePath: string; private _triggerType: string; private _resourceName: string; private _triggerTypeProperty1: string; private _triggerTypeProperty2: string; constructor(triggerType?: string) { this._triggerType = triggerType; } public withAlertType(value: string) { this._alertType = value; return this; } public withResourceType(value: string) { this._resourceType = value; return this; } public withResourcePath(value: string) { this._resourcePath = value; return this; } public withTriggerType(value: string) { this._triggerType = value; return this; } public withResourceName(value: string) { this._resourceName = value; return this; } public withTriggerTypeProperty1(value: string) { this._triggerTypeProperty1 = value; return this; } public withTriggerTypeProperty2(value: string) { this._triggerTypeProperty2 = value; return this; } public build(): HawkularMetrics.ITriggerContext { return new AlertDefinitionContext( this._alertType, this._resourcePath, this._triggerType, this._resourceName, this._triggerTypeProperty1, this._triggerTypeProperty2, this._resourceType ); } } export class AlertDefinitionDampening implements IAlertDefinitionDampening { public static DEFAULT_TIME_EVAL = 7 * 60000; public static DEFAULT_TYPE = 'STRICT_TIME'; public static DEFAULT_TRIGGER_MODE = 'FIRING'; constructor(public triggerId: string, public triggerMode?: string, public type?: string, public evalTimeSetting?: number) { this.triggerMode = triggerMode || AlertDefinitionDampening.DEFAULT_TRIGGER_MODE; this.type = type || AlertDefinitionDampening.DEFAULT_TYPE; this.evalTimeSetting = evalTimeSetting || AlertDefinitionDampening.DEFAULT_TIME_EVAL; } } export class AlertDefinitionTrigger implements IAlertTrigger { public autoResolveAlerts: boolean; public autoResolveMatch: string; public enabled: boolean; public type: string; public severity: string; public tenantId: HawkularMetrics.TenantId; public triggerId: HawkularMetrics.TriggerId; public static DEFAULT_FIRING_MATCH = 'ANY'; constructor(public id: string, public name: string, public description: string, public tags: any, public context: HawkularMetrics.ITriggerContext, public actions: any, public firingMatch?: string, public autoDisable?: boolean, public autoEnable?: boolean, public autoResolve?: boolean) { this.autoDisable = (typeof autoDisable !== 'undefined') ? autoDisable : true; this.autoEnable = (typeof autoEnable !== 'undefined') ? autoEnable : true; this.autoResolve = (typeof autoResolve !== 'undefined') ? autoResolve : false; this.firingMatch = firingMatch || AlertDefinitionTrigger.DEFAULT_FIRING_MATCH; } } export class AlertDefinitionContext implements ITriggerContext { public static RANGE_PERCENT_TRIGGER_TYPE = 'RangeByPercent'; public static TRESHOLD_TRIGGER_TYPE = 'Threshold'; constructor(public alertType: string, public resourcePath: string, public triggerType: string, public resourceName: string, public triggerTypeProperty1: string, public triggerTypeProperty2: string, public resourceType: string) { } } export class AlertDefinition implements IAlertDefinition { constructor(public trigger: HawkularMetrics.IAlertTrigger, public dampenings: HawkularMetrics.IAlertDefinitionDampening[], public conditions: HawkularMetrics.IAlertDefinitionCondition[]) { } } export class AlertAction implements IAlertAction { constructor(public tenantId: string, public actionPlugin: string, public actionId: string, public states: string, public calendar: string, public properties?: IAlertProperties) {}; } export class AlertProperties implements IAlertProperties { constructor(public ccResolved: string, public to: string, public cc: string, public description: string) { } } }
the_stack
import {StateSaveMonitor, StateService} from '../state'; import {Container} from 'esp-js-di'; import {SystemContainerConfiguration, SystemContainerConst} from '../dependencyInjection'; import {EspModuleDecoratorUtils} from './moduleDecorator'; import {RegionBase, RegionManager, RegionState} from '../regions/models'; import {AppDefaultStateProvider, AppState, NoopAppDefaultStateProvider} from './appState'; import {IdFactory} from '../idFactory'; import * as Rx from 'rxjs'; import {AggregateModuleLoadResult, ModuleLoadResult, ModuleLoadStage} from './moduleLoadResult'; import {DisposableBase, Guard, Router, Logger} from 'esp-js'; import {Module, ModuleConstructor} from './module'; import {ViewFactoryBase, ViewRegistryModel} from '../viewFactory'; import {DefaultSingleModuleLoader} from './singleModuleLoader'; import {ModuleProvider} from './moduleProvider'; import {ModelBase} from '../modelBase'; import {SerialDisposable} from 'esp-js-rx'; import {merge, Observable} from 'rxjs'; const _log: Logger = Logger.create('Shell'); export abstract class Shell extends DisposableBase implements ModuleProvider { public static readonly ShellModuleKey = 'shell-module'; private _container: Container; private _stateSaveMonitor: StateSaveMonitor; private _moduleLoaders: DefaultSingleModuleLoader[] = []; private _shellLoaderModelId = IdFactory.createId('module-loader'); private _connected = false; private _regionsLoaded = false; private _loadStreamSubscription = new SerialDisposable(); private _moduleLoadResultsSubject = new Rx.ReplaySubject<AggregateModuleLoadResult>(1); private _aggregateModuleLoadResult = AggregateModuleLoadResult.EMPTY; private _stateSaveMonitorDisposable = new SerialDisposable(); private _regionManager: RegionManager; private _viewRegistryModel: ViewRegistryModel; private _router: Router; private _stateService: StateService; public constructor(container: Container = new Container()) { super(); this._container = container; this.addDisposable(this._stateSaveMonitorDisposable); } public get container(): Container { return this._container; } /** * if true automatic state saving for all the modules models using the provided StateService will apply */ public get stateSavingEnabled(): boolean { return false; } /** * The interval at which state will be saved */ public get stateSaveIntervalMs(): number { return 60_000; } public getDefaultStateProvider(): AppDefaultStateProvider { return NoopAppDefaultStateProvider; } public get appStateKey(): string { return 'esp-app-state'; } public get moduleLoadResults(): Rx.Observable<AggregateModuleLoadResult> { return this._moduleLoadResultsSubject.asObservable(); } protected configureContainer() { SystemContainerConfiguration.configureContainer(this._container); this._container.registerInstance(SystemContainerConst.app_shell, this); this._container.registerInstance(SystemContainerConst.module_provider, this); } public getModule(moduleKey: string): Module { const moduleLoader = this._moduleLoaders.find(ml => ml.moduleMetadata.moduleKey === moduleKey); return moduleLoader ? moduleLoader.module : null; } public start() { _log.verbose(`'Starting`); this.configureContainer(); this._router = this._container.resolve<Router>(SystemContainerConst.router); this._router.addModel(this._shellLoaderModelId, {}); this._regionManager = this._container.resolve<RegionManager>(SystemContainerConst.region_manager); this._viewRegistryModel = this._container.resolve<ViewRegistryModel>(SystemContainerConst.views_registry_model); this._stateService = this._container.resolve<StateService>(SystemContainerConst.state_service); this._registerShellViewFactories(); } /** * takes an array of modules class that will be new-ed up, i.e. constructor functions */ public load(...moduleConstructors: Array<ModuleConstructor>): void { if (!this._connected) { _log.verbose(`'Loading all modules`); // Using a subject and handling the 'publish/connect' manually here as we can't create the stream at ctor time and need to expose something via .loadResults, hence the subject. this._connected = true; this._aggregateModuleLoadResult = new AggregateModuleLoadResult(moduleConstructors.length); if (moduleConstructors.length === 0) { this._moduleLoadResultsSubject.next(this._aggregateModuleLoadResult); this._onModuleLoadComplete(); return; } const stream = this._createLoadStream(...moduleConstructors); this._loadStreamSubscription.setDisposable(stream.subscribe( r => { this._aggregateModuleLoadResult = this._aggregateModuleLoadResult.addModuleLoadResult(r); if (!this._regionsLoaded && this._aggregateModuleLoadResult.allModulesAtOrLaterThanStage(ModuleLoadStage.Registered)) { this._onModuleLoadComplete(); } this._moduleLoadResultsSubject.next(this._aggregateModuleLoadResult); }, exception => { _log.error(`Error on module load stream`, exception); } )); } } private _registerShellViewFactories() { _log.verbose('Registering Shell ViewFactories'); let viewFactories: Array<ViewFactoryBase<any, any>> = this.getViewFactories(); viewFactories.forEach(viewFactory => { this._viewRegistryModel.registerViewFactory(Shell.ShellModuleKey, 'Shell', viewFactory, this.container, false); this.addDisposable(() => { this._viewRegistryModel.unregisterViewFactory(viewFactory); }); }); } getViewFactories(): Array<ViewFactoryBase<ModelBase, any>> { return []; } private _onModuleLoadComplete() { this._router.runAction(this._shellLoaderModelId, () => { if (!this._regionsLoaded) { this._loadRegions(); this._trySetStateSaveMonitor(); } }); } // TODO tests to ensure a shell can be loaded and unloaded and everything is started/disposed correctly // TODO reentrancy check public unloadModules(): void { _log.verbose(`'Unloading all modules`); this.trySaveAllComponentState(); this._unloadRegions(); this._moduleLoaders.forEach(moduleLoader => { _log.verbose(`'Unloading module ${moduleLoader.moduleMetadata.moduleKey} with name ${moduleLoader.moduleMetadata.moduleName}`); moduleLoader.disposeModule(); }); this._stateSaveMonitorDisposable.setDisposable(null); this._loadStreamSubscription.setDisposable(null); this._moduleLoaders.length = 0; this._connected = false; this._regionsLoaded = false; this._aggregateModuleLoadResult = AggregateModuleLoadResult.EMPTY; this._moduleLoadResultsSubject.next(this._aggregateModuleLoadResult); } /** * While state saving happens automatically based on stateSavingEnabled & stateSaveIntervalMs, you can also force it via this function. */ public trySaveAllComponentState = () => { if (!this.stateSavingEnabled) { return; } if (!this._regionsLoaded) { return; } let appState: AppState = { regionState: [] }; this._regionManager.getRegions().forEach((region: RegionBase<any>) => { if (!region.stateSavingEnabled) { return; } let regionState: RegionState = region.getRegionState(); if (regionState) { appState.regionState.push(regionState); } }); if (appState.regionState.length > 0) { this._stateService.saveState(this.appStateKey, appState); } else { this._stateService.clearState(this.appStateKey); } }; private _loadRegions() { Guard.isTruthy(this._connected, `_loadRegions but we're not connected`); _log.verbose(`Loading Regions`); if (this._regionsLoaded) { _log.verbose(`First unloading existing views`); this._unloadRegions(); } this._regionsLoaded = true; let applicationState: AppState = this._stateService.getState<AppState>(this.appStateKey); if (!applicationState) { applicationState = this.getDefaultStateProvider().getDefaultAppState(); } if (applicationState && applicationState.regionState.length > 0) { applicationState.regionState.forEach(regionState => { this._regionManager.loadRegion(regionState); }); } } private _unloadRegions() { this._regionManager.getRegions().forEach((region: RegionBase<any>) => { region.unload(); }); } private _createLoadStream(...moduleConstructors: Array<ModuleConstructor>): Rx.Observable<ModuleLoadResult> { return Rx.Observable.create((obs: Rx.Subscriber<ModuleLoadResult>) => { _log.verbose(`Loading shell and ${moduleConstructors.length} additional modules`); return merge(...moduleConstructors.map(moduleCtor => this._loadModule(moduleCtor))).subscribe(obs); }); } private _loadModule(moduleConstructor: ModuleConstructor): Rx.Observable<ModuleLoadResult> { return new Observable((obs: Rx.Subscriber<ModuleLoadResult>) => { let moduleMetadata = EspModuleDecoratorUtils.getMetadataFromModuleClass(moduleConstructor); _log.verbose(`Creating module loader for ${moduleMetadata.moduleKey}`); let moduleLoader = new DefaultSingleModuleLoader( this._container, this._viewRegistryModel, moduleMetadata, moduleConstructor, ); this._moduleLoaders.push(moduleLoader); let subscription = moduleLoader.loadResults.subscribe(obs); moduleLoader.load(); return subscription; }); } private _trySetStateSaveMonitor() { if (this.stateSavingEnabled && this.stateSaveIntervalMs > 0) { let stateSaveMonitor = new StateSaveMonitor(this.stateSaveIntervalMs, this.trySaveAllComponentState); this._stateSaveMonitor = stateSaveMonitor; this._stateSaveMonitorDisposable.setDisposable(this._stateSaveMonitor); stateSaveMonitor.start(); } } }
the_stack
import React from 'react' import { render, cleanup, fireEvent } from '@testing-library/react' // import '@babel/polyfill' // TODO: not ideal find the way to move it globally, webpack import { FILMS } from '../../../__mocks__/data' import Table from './Table' const DATA_KEYS = [ 'title', 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ] describe('<Table>', () => { afterEach(cleanup) it('default', () => { const { container } = render( <Table displayData={FILMS} dataKeys={DATA_KEYS} log={() => {}} />, ) expect(container.firstChild).toMatchSnapshot() // per page expect( container.querySelector('tbody')?.querySelectorAll('tr'), ).toBeTruthy() expect( container.querySelector('tbody')?.querySelectorAll('tr').length, ).toBe(FILMS.length) // number of columns expect(container.querySelector('thead')?.querySelector('tr')).toBeTruthy() expect( container ?.querySelector('thead') ?.querySelector('tr') ?.querySelectorAll('th').length, ).toBe(DATA_KEYS.length) // label formated correctly expect( container.querySelector('thead')?.querySelector('tr')?.firstChild ?.textContent, ).toBe('Title') }) it('onRowClick', () => { console.log = jest.fn() const { container } = render( <Table displayData={FILMS} dataKeys={DATA_KEYS} onRowClick={(data) => console.log(data)} log={() => {}} />, ) expect(container.firstChild).toMatchSnapshot() expect(container.querySelector('tbody')?.firstChild).toBeTruthy() fireEvent.click(container.querySelector('tbody').firstChild) expect(console.log).toHaveBeenCalledTimes(1) expect(console.log).toHaveBeenCalledWith({ title: 'A New Hope', episodeID: 4, openingCrawl: "It is a period of civil war.\r\nRebel spaceships, striking\r\nfrom a hidden base, have won\r\ntheir first victory against\r\nthe evil Galactic Empire.\r\n\r\nDuring the battle, Rebel\r\nspies managed to steal secret\r\nplans to the Empire's\r\nultimate weapon, the DEATH\r\nSTAR, an armored space\r\nstation with enough power\r\nto destroy an entire planet.\r\n\r\nPursued by the Empire's\r\nsinister agents, Princess\r\nLeia races home aboard her\r\nstarship, custodian of the\r\nstolen plans that can save her\r\npeople and restore\r\nfreedom to the galaxy....", director: 'George Lucas', producer: 'Gary Kurtz, Rick McCallum', releaseDate: '1977-05-25', }) console.log.mockRestore() }) it('columns label', () => { const titleLabel = 'Movie Title' const { container, queryByText } = render( <Table displayData={FILMS} dataKeys={[ { id: 'title', label: titleLabel }, 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ]} log={() => {}} />, ) expect(container.firstChild).toMatchSnapshot() const firstLabel = container .querySelector('thead') ?.querySelector('tr')?.firstChild expect(firstLabel).toBeTruthy() expect(firstLabel).toBe(queryByText(titleLabel)) expect(firstLabel?.textContent).toBe(queryByText(titleLabel)?.textContent) }) it('columns component data formating', () => { const { container, queryByText } = render( <Table displayData={FILMS} dataKeys={[ { id: 'title', component: (data) => data.toUpperCase() }, 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ]} log={() => {}} />, ) expect(container.firstChild).toMatchSnapshot() expect( container.querySelector('tbody')?.querySelector('tr')?.firstChild ?.textContent, ).toBe(FILMS[0].title.toUpperCase()) }) it('columns component data formating', () => { const buttonLabel = 'Click Me' const Button = () => <button>{buttonLabel}</button> const { container, queryByText } = render( <Table displayData={FILMS} dataKeys={[ { id: 'title', component: () => <Button /> }, 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ]} log={() => {}} />, ) expect(container.firstChild).toMatchSnapshot() expect( container.querySelector('tbody')?.querySelector('tr')?.firstChild ?.firstChild?.textContent, ).toBe(buttonLabel) }) it('columns custom column', () => { const buttonLabel = 'Click Me' const Button = () => <button>{buttonLabel}</button> const { container } = render( <Table displayData={FILMS} dataKeys={[ { id: 'custom', customColumn: true, component: () => <Button /> }, ...DATA_KEYS, ]} log={() => {}} />, ) expect(container.firstChild).toMatchSnapshot() expect( container.querySelector('tbody')?.querySelector('tr')?.firstChild ?.firstChild?.textContent, ).toBe(buttonLabel) // number of columns expect(container.querySelector('thead')?.querySelector('tr')).toBeTruthy() expect( container .querySelector('thead') ?.querySelector('tr') ?.querySelectorAll('th').length, ).toBe(DATA_KEYS.length + 1) // custom column label formated correctly expect( container.querySelector('thead')?.querySelector('tr')?.firstChild ?.textContent, ).toBe('Custom') }) it('columns custom column error component required', () => { console.error = jest.fn() expect(() => { render( <Table displayData={FILMS} dataKeys={[{ id: 'custom', customColumn: true }, ...DATA_KEYS]} log={() => {}} />, ) }).toThrowError( new Error('When customColumn true, component property must be provided!'), ) expect(console.error).toHaveBeenCalled() console.error.mockRestore() }) it('custom column style', () => { const customClass = 'test-class' const { container } = render( <Table displayData={FILMS} dataKeys={[ { id: 'title', nodeStyle: customClass }, 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ]} log={() => {}} />, ) expect(container.firstChild).toMatchSnapshot() expect( container .querySelector('tbody') ?.querySelector('tr') ?.firstChild?.classList?.contains(customClass), ).toBeTruthy() expect( container .querySelector('tbody') ?.querySelector('tr') ?.lastChild?.classList.contains(customClass), ).toBeFalsy() }) it('selective custom column cell style', () => { const customClass = 'test-class' const { container } = render( <Table displayData={FILMS} dataKeys={[ { id: 'title', nodeStyle: (data) => { if (data.title <= FILMS[0].title) return customClass }, }, 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ]} log={() => {}} />, ) expect(container.firstChild).toMatchSnapshot() // select first row and first cell expect( container .querySelector('tbody') ?.querySelector('tr') ?.firstChild?.classList.contains(customClass), ).toBeTruthy() // selects last row and first column expect( container .querySelector('tbody') ?.lastChild?.firstChild?.classList.contains(customClass), ).toBeFalsy() }) it('sort', () => { console.log = jest.fn() const { container } = render( <Table displayData={FILMS} dataKeys={[ 'title', 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ]} log={() => {}} sort onSort={(column) => { console.log(column) }} />, ) const headerLabel = container.querySelector('thead')?.firstChild?.firstChild if (headerLabel) fireEvent.click(headerLabel) expect(container.firstChild).toMatchSnapshot() expect( headerLabel?.classList.contains('TableQL-thead-th-sort'), ).toBeTruthy() expect(console.log).toHaveBeenCalledTimes(1) console.log.mockRestore() }) it('sort through column', () => { console.log = jest.fn() const { container } = render( <Table displayData={FILMS} dataKeys={[ { id: 'title', sort: true }, 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ]} log={() => {}} onSort={(column) => { console.log(column) }} />, ) const headerLabel = container.querySelector('thead')?.firstChild?.firstChild if (headerLabel) fireEvent.click(headerLabel) expect(container.firstChild).toMatchSnapshot() expect( headerLabel?.classList.contains('TableQL-thead-th-sort'), ).toBeTruthy() expect(console.log).toHaveBeenCalledTimes(1) console.log.mockRestore() }) it('sort through column', () => { console.log = jest.fn() const { container } = render( <Table displayData={FILMS} dataKeys={[ 'title', 'episodeID', 'openingCrawl', 'director', 'producer', 'releaseDate', ]} log={() => {}} />, ) const headerLabel = container.querySelector('thead')?.firstChild?.firstChild if (headerLabel) fireEvent.click(headerLabel) expect(container.firstChild).toMatchSnapshot() expect(headerLabel?.classList.contains('TableQL-thead-th-sort')).toBeFalsy() expect(console.log).toHaveBeenCalledTimes(0) console.log.mockRestore() }) })
the_stack
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ATN } from "antlr4ts/atn/ATN"; import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer"; import { CharStream } from "antlr4ts/CharStream"; import { Lexer } from "antlr4ts/Lexer"; import { LexerATNSimulator } from "antlr4ts/atn/LexerATNSimulator"; import { NotNull } from "antlr4ts/Decorators"; import { Override } from "antlr4ts/Decorators"; import { RuleContext } from "antlr4ts/RuleContext"; import { Vocabulary } from "antlr4ts/Vocabulary"; import { VocabularyImpl } from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; export class LGTemplateLexer extends Lexer { public static readonly WS = 1; public static readonly NEWLINE = 2; public static readonly COMMENTS = 3; public static readonly DASH = 4; public static readonly LEFT_SQUARE_BRACKET = 5; public static readonly INVALID_TOKEN = 6; public static readonly WS_IN_BODY = 7; public static readonly MULTILINE_PREFIX = 8; public static readonly NEWLINE_IN_BODY = 9; public static readonly IF = 10; public static readonly ELSEIF = 11; public static readonly ELSE = 12; public static readonly SWITCH = 13; public static readonly CASE = 14; public static readonly DEFAULT = 15; public static readonly ESCAPE_CHARACTER = 16; public static readonly EXPRESSION = 17; public static readonly TEXT = 18; public static readonly MULTILINE_SUFFIX = 19; public static readonly WS_IN_STRUCTURE_NAME = 20; public static readonly NEWLINE_IN_STRUCTURE_NAME = 21; public static readonly STRUCTURE_NAME = 22; public static readonly TEXT_IN_STRUCTURE_NAME = 23; public static readonly STRUCTURED_COMMENTS = 24; public static readonly WS_IN_STRUCTURE_BODY = 25; public static readonly STRUCTURED_NEWLINE = 26; public static readonly STRUCTURED_BODY_END = 27; public static readonly STRUCTURE_IDENTIFIER = 28; public static readonly STRUCTURE_EQUALS = 29; public static readonly STRUCTURE_OR_MARK = 30; public static readonly ESCAPE_CHARACTER_IN_STRUCTURE_BODY = 31; public static readonly EXPRESSION_IN_STRUCTURE_BODY = 32; public static readonly TEXT_IN_STRUCTURE_BODY = 33; public static readonly NORMAL_TEMPLATE_BODY_MODE = 1; public static readonly MULTILINE_MODE = 2; public static readonly STRUCTURE_NAME_MODE = 3; public static readonly STRUCTURE_BODY_MODE = 4; // tslint:disable:no-trailing-whitespace public static readonly channelNames: string[] = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN", ]; // tslint:disable:no-trailing-whitespace public static readonly modeNames: string[] = [ "DEFAULT_MODE", "NORMAL_TEMPLATE_BODY_MODE", "MULTILINE_MODE", "STRUCTURE_NAME_MODE", "STRUCTURE_BODY_MODE", ]; public static readonly ruleNames: string[] = [ "A", "C", "D", "E", "F", "H", "I", "L", "S", "T", "U", "W", "LETTER", "NUMBER", "WHITESPACE", "STRING_LITERAL", "STRING_INTERPOLATION", "ESCAPE_CHARACTER_FRAGMENT", "IDENTIFIER", "OBJECT_DEFINITION", "EXPRESSION_FRAGMENT", "NEWLINE_FRAGMENT", "WS", "NEWLINE", "COMMENTS", "DASH", "LEFT_SQUARE_BRACKET", "INVALID_TOKEN", "WS_IN_BODY", "MULTILINE_PREFIX", "NEWLINE_IN_BODY", "IF", "ELSEIF", "ELSE", "SWITCH", "CASE", "DEFAULT", "ESCAPE_CHARACTER", "EXPRESSION", "TEXT", "MULTILINE_SUFFIX", "MULTILINE_ESCAPE_CHARACTER", "MULTILINE_EXPRESSION", "MULTILINE_TEXT", "WS_IN_STRUCTURE_NAME", "NEWLINE_IN_STRUCTURE_NAME", "STRUCTURE_NAME", "TEXT_IN_STRUCTURE_NAME", "STRUCTURED_COMMENTS", "WS_IN_STRUCTURE_BODY", "STRUCTURED_NEWLINE", "STRUCTURED_BODY_END", "STRUCTURE_IDENTIFIER", "STRUCTURE_EQUALS", "STRUCTURE_OR_MARK", "ESCAPE_CHARACTER_IN_STRUCTURE_BODY", "EXPRESSION_IN_STRUCTURE_BODY", "TEXT_IN_STRUCTURE_BODY", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "'|'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, "WS", "NEWLINE", "COMMENTS", "DASH", "LEFT_SQUARE_BRACKET", "INVALID_TOKEN", "WS_IN_BODY", "MULTILINE_PREFIX", "NEWLINE_IN_BODY", "IF", "ELSEIF", "ELSE", "SWITCH", "CASE", "DEFAULT", "ESCAPE_CHARACTER", "EXPRESSION", "TEXT", "MULTILINE_SUFFIX", "WS_IN_STRUCTURE_NAME", "NEWLINE_IN_STRUCTURE_NAME", "STRUCTURE_NAME", "TEXT_IN_STRUCTURE_NAME", "STRUCTURED_COMMENTS", "WS_IN_STRUCTURE_BODY", "STRUCTURED_NEWLINE", "STRUCTURED_BODY_END", "STRUCTURE_IDENTIFIER", "STRUCTURE_EQUALS", "STRUCTURE_OR_MARK", "ESCAPE_CHARACTER_IN_STRUCTURE_BODY", "EXPRESSION_IN_STRUCTURE_BODY", "TEXT_IN_STRUCTURE_BODY", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(LGTemplateLexer._LITERAL_NAMES, LGTemplateLexer._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return LGTemplateLexer.VOCABULARY; } // tslint:enable:no-trailing-whitespace ignoreWS = true; // usually we ignore whitespace, but inside template, whitespace is significant beginOfTemplateBody = true; // whether we are at the begining of template body inMultiline = false; // whether we are in multiline beginOfTemplateLine = false;// weather we are at the begining of template string inStructuredValue = false; // weather we are in the structure value beginOfStructureProperty = false; // weather we are at the begining of structure property constructor(input: CharStream) { super(input); this._interp = new LexerATNSimulator(LGTemplateLexer._ATN, this); } // @Override public get grammarFileName(): string { return "LGTemplateLexer.g4"; } // @Override public get ruleNames(): string[] { return LGTemplateLexer.ruleNames; } // @Override public get serializedATN(): string { return LGTemplateLexer._serializedATN; } // @Override public get channelNames(): string[] { return LGTemplateLexer.channelNames; } // @Override public get modeNames(): string[] { return LGTemplateLexer.modeNames; } // @Override public action(_localctx: RuleContext, ruleIndex: number, actionIndex: number): void { switch (ruleIndex) { case 25: this.DASH_action(_localctx, actionIndex); break; case 26: this.LEFT_SQUARE_BRACKET_action(_localctx, actionIndex); break; case 27: this.INVALID_TOKEN_action(_localctx, actionIndex); break; case 29: this.MULTILINE_PREFIX_action(_localctx, actionIndex); break; case 30: this.NEWLINE_IN_BODY_action(_localctx, actionIndex); break; case 31: this.IF_action(_localctx, actionIndex); break; case 32: this.ELSEIF_action(_localctx, actionIndex); break; case 33: this.ELSE_action(_localctx, actionIndex); break; case 34: this.SWITCH_action(_localctx, actionIndex); break; case 35: this.CASE_action(_localctx, actionIndex); break; case 36: this.DEFAULT_action(_localctx, actionIndex); break; case 37: this.ESCAPE_CHARACTER_action(_localctx, actionIndex); break; case 38: this.EXPRESSION_action(_localctx, actionIndex); break; case 39: this.TEXT_action(_localctx, actionIndex); break; case 40: this.MULTILINE_SUFFIX_action(_localctx, actionIndex); break; case 45: this.NEWLINE_IN_STRUCTURE_NAME_action(_localctx, actionIndex); break; case 50: this.STRUCTURED_NEWLINE_action(_localctx, actionIndex); break; case 52: this.STRUCTURE_IDENTIFIER_action(_localctx, actionIndex); break; case 53: this.STRUCTURE_EQUALS_action(_localctx, actionIndex); break; case 54: this.STRUCTURE_OR_MARK_action(_localctx, actionIndex); break; case 55: this.ESCAPE_CHARACTER_IN_STRUCTURE_BODY_action(_localctx, actionIndex); break; case 56: this.EXPRESSION_IN_STRUCTURE_BODY_action(_localctx, actionIndex); break; case 57: this.TEXT_IN_STRUCTURE_BODY_action(_localctx, actionIndex); break; } } private DASH_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 0: this.beginOfTemplateLine = true; this.beginOfTemplateBody = false; break; } } private LEFT_SQUARE_BRACKET_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 1: this.beginOfTemplateBody = false; break; } } private INVALID_TOKEN_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 2: this.beginOfTemplateBody = false; break; } } private MULTILINE_PREFIX_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 3: this.inMultiline = true; this.beginOfTemplateLine = false; break; } } private NEWLINE_IN_BODY_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 4: this.ignoreWS = true; break; } } private IF_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 5: this.ignoreWS = true; this.beginOfTemplateLine = false; break; } } private ELSEIF_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 6: this.ignoreWS = true; this.beginOfTemplateLine = false; break; } } private ELSE_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 7: this.ignoreWS = true; this.beginOfTemplateLine = false; break; } } private SWITCH_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 8: this.ignoreWS = true; this.beginOfTemplateLine = false; break; } } private CASE_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 9: this.ignoreWS = true; this.beginOfTemplateLine = false; break; } } private DEFAULT_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 10: this.ignoreWS = true; this.beginOfTemplateLine = false; break; } } private ESCAPE_CHARACTER_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 11: this.ignoreWS = false; this.beginOfTemplateLine = false; break; } } private EXPRESSION_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 12: this.ignoreWS = false; this.beginOfTemplateLine = false; break; } } private TEXT_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 13: this.ignoreWS = false; this.beginOfTemplateLine = false; break; } } private MULTILINE_SUFFIX_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 14: this.inMultiline = false; break; } } private NEWLINE_IN_STRUCTURE_NAME_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 15: this.ignoreWS = true; break; case 16: this.beginOfStructureProperty = true; break; } } private STRUCTURED_NEWLINE_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 17: this.ignoreWS = true; this.inStructuredValue = false; this.beginOfStructureProperty = true; break; } } private STRUCTURE_IDENTIFIER_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 18: this.beginOfStructureProperty = false; break; } } private STRUCTURE_EQUALS_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 19: this.inStructuredValue = true; break; } } private STRUCTURE_OR_MARK_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 20: this.ignoreWS = true; break; } } private ESCAPE_CHARACTER_IN_STRUCTURE_BODY_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 21: this.ignoreWS = false; break; } } private EXPRESSION_IN_STRUCTURE_BODY_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 22: this.ignoreWS = false; break; } } private TEXT_IN_STRUCTURE_BODY_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 23: this.ignoreWS = false; this.beginOfStructureProperty = false; break; } } // @Override public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean { switch (ruleIndex) { case 26: return this.LEFT_SQUARE_BRACKET_sempred(_localctx, predIndex); case 28: return this.WS_IN_BODY_sempred(_localctx, predIndex); case 29: return this.MULTILINE_PREFIX_sempred(_localctx, predIndex); case 31: return this.IF_sempred(_localctx, predIndex); case 32: return this.ELSEIF_sempred(_localctx, predIndex); case 33: return this.ELSE_sempred(_localctx, predIndex); case 34: return this.SWITCH_sempred(_localctx, predIndex); case 35: return this.CASE_sempred(_localctx, predIndex); case 36: return this.DEFAULT_sempred(_localctx, predIndex); case 48: return this.STRUCTURED_COMMENTS_sempred(_localctx, predIndex); case 49: return this.WS_IN_STRUCTURE_BODY_sempred(_localctx, predIndex); case 51: return this.STRUCTURED_BODY_END_sempred(_localctx, predIndex); case 52: return this.STRUCTURE_IDENTIFIER_sempred(_localctx, predIndex); case 53: return this.STRUCTURE_EQUALS_sempred(_localctx, predIndex); } return true; } private LEFT_SQUARE_BRACKET_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 0: return this.beginOfTemplateBody ; } return true; } private WS_IN_BODY_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 1: return this.ignoreWS; } return true; } private MULTILINE_PREFIX_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 2: return !this.inMultiline && this.beginOfTemplateLine ; } return true; } private IF_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 3: return this.beginOfTemplateLine; } return true; } private ELSEIF_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 4: return this.beginOfTemplateLine; } return true; } private ELSE_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 5: return this.beginOfTemplateLine; } return true; } private SWITCH_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 6: return this.beginOfTemplateLine; } return true; } private CASE_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 7: return this.beginOfTemplateLine; } return true; } private DEFAULT_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 8: return this.beginOfTemplateLine; } return true; } private STRUCTURED_COMMENTS_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 9: return !this.inStructuredValue && this.beginOfStructureProperty; } return true; } private WS_IN_STRUCTURE_BODY_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 10: return this.ignoreWS; } return true; } private STRUCTURED_BODY_END_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 11: return !this.inStructuredValue; } return true; } private STRUCTURE_IDENTIFIER_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 12: return !this.inStructuredValue && this.beginOfStructureProperty; } return true; } private STRUCTURE_EQUALS_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 13: return !this.inStructuredValue; } return true; } public static readonly _serializedATN: string = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02#\u020B\b\x01" + "\b\x01\b\x01\b\x01\b\x01\x04\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04" + "\x05\t\x05\x04\x06\t\x06\x04\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04" + "\v\t\v\x04\f\t\f\x04\r\t\r\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04" + "\x11\t\x11\x04\x12\t\x12\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04" + "\x16\t\x16\x04\x17\t\x17\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04" + "\x1B\t\x1B\x04\x1C\t\x1C\x04\x1D\t\x1D\x04\x1E\t\x1E\x04\x1F\t\x1F\x04" + " \t \x04!\t!\x04\"\t\"\x04#\t#\x04$\t$\x04%\t%\x04&\t&\x04\'\t\'\x04(" + "\t(\x04)\t)\x04*\t*\x04+\t+\x04,\t,\x04-\t-\x04.\t.\x04/\t/\x040\t0\x04" + "1\t1\x042\t2\x043\t3\x044\t4\x045\t5\x046\t6\x047\t7\x048\t8\x049\t9\x04" + ":\t:\x04;\t;\x03\x02\x03\x02\x03\x03\x03\x03\x03\x04\x03\x04\x03\x05\x03" + "\x05\x03\x06\x03\x06\x03\x07\x03\x07\x03\b\x03\b\x03\t\x03\t\x03\n\x03" + "\n\x03\v\x03\v\x03\f\x03\f\x03\r\x03\r\x03\x0E\x03\x0E\x03\x0F\x03\x0F" + "\x03\x10\x03\x10\x03\x11\x03\x11\x03\x11\x03\x11\x07\x11\x9E\n\x11\f\x11" + "\x0E\x11\xA1\v\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x11\x07\x11\xA8" + "\n\x11\f\x11\x0E\x11\xAB\v\x11\x03\x11\x05\x11\xAE\n\x11\x03\x12\x03\x12" + "\x03\x12\x03\x12\x07\x12\xB4\n\x12\f\x12\x0E\x12\xB7\v\x12\x03\x12\x03" + "\x12\x03\x13\x03\x13\x05\x13\xBD\n\x13\x03\x14\x03\x14\x03\x14\x05\x14" + "\xC2\n\x14\x03\x14\x03\x14\x03\x14\x07\x14\xC7\n\x14\f\x14\x0E\x14\xCA" + "\v\x14\x03\x15\x03\x15\x03\x15\x03\x15\x03\x15\x07\x15\xD1\n\x15\f\x15" + "\x0E\x15\xD4\v\x15\x03\x15\x03\x15\x03\x16\x03\x16\x03\x16\x03\x16\x03" + "\x16\x03\x16\x06\x16\xDE\n\x16\r\x16\x0E\x16\xDF\x03\x16\x05\x16\xE3\n" + "\x16\x03\x17\x05\x17\xE6\n\x17\x03\x17\x03\x17\x03\x18\x06\x18\xEB\n\x18" + "\r\x18\x0E\x18\xEC\x03\x18\x03\x18\x03\x19\x03\x19\x03\x19\x03\x19\x03" + "\x1A\x03\x1A\x07\x1A\xF7\n\x1A\f\x1A\x0E\x1A\xFA\v\x1A\x03\x1A\x03\x1A" + "\x03\x1B\x03\x1B\x03\x1B\x03\x1B\x03\x1B\x03\x1C\x03\x1C\x03\x1C\x03\x1C" + "\x03\x1C\x03\x1C\x03\x1D\x03\x1D\x03\x1D\x03\x1E\x03\x1E\x03\x1E\x07\x1E" + "\u010F\n\x1E\f\x1E\x0E\x1E\u0112\v\x1E\x03\x1E\x03\x1E\x03\x1F\x03\x1F" + "\x03\x1F\x03\x1F\x03\x1F\x03\x1F\x03\x1F\x03\x1F\x03\x1F\x03 \x03 \x03" + " \x03 \x03 \x03 \x03!\x03!\x03!\x07!\u0128\n!\f!\x0E!\u012B\v!\x03!\x03" + "!\x03!\x03!\x03\"\x03\"\x03\"\x03\"\x03\"\x07\"\u0136\n\"\f\"\x0E\"\u0139" + "\v\"\x03\"\x03\"\x03\"\x07\"\u013E\n\"\f\"\x0E\"\u0141\v\"\x03\"\x03\"" + "\x03\"\x03\"\x03#\x03#\x03#\x03#\x03#\x07#\u014C\n#\f#\x0E#\u014F\v#\x03" + "#\x03#\x03#\x03#\x03$\x03$\x03$\x03$\x03$\x03$\x03$\x07$\u015C\n$\f$\x0E" + "$\u015F\v$\x03$\x03$\x03$\x03$\x03%\x03%\x03%\x03%\x03%\x07%\u016A\n%" + "\f%\x0E%\u016D\v%\x03%\x03%\x03%\x03%\x03&\x03&\x03&\x03&\x03&\x03&\x03" + "&\x03&\x07&\u017B\n&\f&\x0E&\u017E\v&\x03&\x03&\x03&\x03&\x03\'\x03\'" + "\x03\'\x03(\x03(\x03(\x03)\x06)\u018B\n)\r)\x0E)\u018C\x03)\x03)\x03*" + "\x03*\x03*\x03*\x03*\x03*\x03*\x03*\x03+\x03+\x03+\x03+\x03,\x03,\x03" + ",\x03,\x03-\x03-\x06-\u01A3\n-\r-\x0E-\u01A4\x03-\x03-\x03.\x06.\u01AA" + "\n.\r.\x0E.\u01AB\x03.\x03.\x03/\x03/\x03/\x03/\x03/\x03/\x03/\x030\x03" + "0\x030\x050\u01BA\n0\x030\x030\x030\x070\u01BF\n0\f0\x0E0\u01C2\v0\x03" + "1\x061\u01C5\n1\r1\x0E1\u01C6\x032\x032\x072\u01CB\n2\f2\x0E2\u01CE\v" + "2\x032\x032\x032\x032\x032\x033\x033\x033\x073\u01D8\n3\f3\x0E3\u01DB" + "\v3\x033\x033\x034\x034\x034\x035\x035\x035\x035\x035\x035\x036\x036\x03" + "6\x056\u01EB\n6\x036\x036\x036\x076\u01F0\n6\f6\x0E6\u01F3\v6\x036\x03" + "6\x036\x037\x037\x037\x037\x038\x038\x038\x039\x039\x039\x03:\x03:\x03" + ":\x03;\x06;\u0206\n;\r;\x0E;\u0207\x03;\x03;\t\x9F\xA9\xB5\u018C\u01A4" + "\u01C6\u0207\x02\x02<\x07\x02\x02\t\x02\x02\v\x02\x02\r\x02\x02\x0F\x02" + "\x02\x11\x02\x02\x13\x02\x02\x15\x02\x02\x17\x02\x02\x19\x02\x02\x1B\x02" + "\x02\x1D\x02\x02\x1F\x02\x02!\x02\x02#\x02\x02%\x02\x02\'\x02\x02)\x02" + "\x02+\x02\x02-\x02\x02/\x02\x021\x02\x023\x02\x035\x02\x047\x02\x059\x02" + "\x06;\x02\x07=\x02\b?\x02\tA\x02\nC\x02\vE\x02\fG\x02\rI\x02\x0EK\x02" + "\x0FM\x02\x10O\x02\x11Q\x02\x12S\x02\x13U\x02\x14W\x02\x15Y\x02\x02[\x02" + "\x02]\x02\x02_\x02\x16a\x02\x17c\x02\x18e\x02\x19g\x02\x1Ai\x02\x1Bk\x02" + "\x1Cm\x02\x1Do\x02\x1Eq\x02\x1Fs\x02 u\x02!w\x02\"y\x02#\x07\x02\x03\x04" + "\x05\x06\x19\x04\x02CCcc\x04\x02EEee\x04\x02FFff\x04\x02GGgg\x04\x02H" + "Hhh\x04\x02JJjj\x04\x02KKkk\x04\x02NNnn\x04\x02UUuu\x04\x02VVvv\x04\x02" + "WWww\x04\x02YYyy\x04\x02C\\c|\x06\x02\v\v\"\"\xA2\xA2\uFF01\uFF01\x04" + "\x02))^^\x03\x02))\x04\x02$$^^\x03\x02$$\x04\x02^^bb\x03\x02bb\x04\x02" + "\f\f\x0F\x0F\x06\x02$$))bb\x7F\x7F\x04\x02/0aa\x02\u0223\x023\x03\x02" + "\x02\x02\x025\x03\x02\x02\x02\x027\x03\x02\x02\x02\x029\x03\x02\x02\x02" + "\x02;\x03\x02\x02\x02\x02=\x03\x02\x02\x02\x03?\x03\x02\x02\x02\x03A\x03" + "\x02\x02\x02\x03C\x03\x02\x02\x02\x03E\x03\x02\x02\x02\x03G\x03\x02\x02" + "\x02\x03I\x03\x02\x02\x02\x03K\x03\x02\x02\x02\x03M\x03\x02\x02\x02\x03" + "O\x03\x02\x02\x02\x03Q\x03\x02\x02\x02\x03S\x03\x02\x02\x02\x03U\x03\x02" + "\x02\x02\x04W\x03\x02\x02\x02\x04Y\x03\x02\x02\x02\x04[\x03\x02\x02\x02" + "\x04]\x03\x02\x02\x02\x05_\x03\x02\x02\x02\x05a\x03\x02\x02\x02\x05c\x03" + "\x02\x02\x02\x05e\x03\x02\x02\x02\x06g\x03\x02\x02\x02\x06i\x03\x02\x02" + "\x02\x06k\x03\x02\x02\x02\x06m\x03\x02\x02\x02\x06o\x03\x02\x02\x02\x06" + "q\x03\x02\x02\x02\x06s\x03\x02\x02\x02\x06u\x03\x02\x02\x02\x06w\x03\x02" + "\x02\x02\x06y\x03\x02\x02\x02\x07{\x03\x02\x02\x02\t}\x03\x02\x02\x02" + "\v\x7F\x03\x02\x02\x02\r\x81\x03\x02\x02\x02\x0F\x83\x03\x02\x02\x02\x11" + "\x85\x03\x02\x02\x02\x13\x87\x03\x02\x02\x02\x15\x89\x03\x02\x02\x02\x17" + "\x8B\x03\x02\x02\x02\x19\x8D\x03\x02\x02\x02\x1B\x8F\x03\x02\x02\x02\x1D" + "\x91\x03\x02\x02\x02\x1F\x93\x03\x02\x02\x02!\x95\x03\x02\x02\x02#\x97" + "\x03\x02\x02\x02%\xAD\x03\x02\x02\x02\'\xAF\x03\x02\x02\x02)\xBA\x03\x02" + "\x02\x02+\xC1\x03\x02\x02\x02-\xCB\x03\x02\x02\x02/\xD7\x03\x02\x02\x02" + "1\xE5\x03\x02\x02\x023\xEA\x03\x02\x02\x025\xF0\x03\x02\x02\x027\xF4\x03" + "\x02\x02\x029\xFD\x03\x02\x02\x02;\u0102\x03\x02\x02\x02=\u0108\x03\x02" + "\x02\x02?\u010B\x03\x02\x02\x02A\u0115\x03\x02\x02\x02C\u011E\x03\x02" + "\x02\x02E\u0124\x03\x02\x02\x02G\u0130\x03\x02\x02\x02I\u0146\x03\x02" + "\x02\x02K\u0154\x03\x02\x02\x02M\u0164\x03\x02\x02\x02O\u0172\x03\x02" + "\x02\x02Q\u0183\x03\x02\x02\x02S\u0186\x03\x02\x02\x02U\u018A\x03\x02" + "\x02\x02W\u0190\x03\x02\x02\x02Y\u0198\x03\x02\x02\x02[\u019C\x03\x02" + "\x02\x02]\u01A2\x03\x02\x02\x02_\u01A9\x03\x02\x02\x02a\u01AF\x03\x02" + "\x02\x02c\u01B9\x03\x02\x02\x02e\u01C4\x03\x02\x02\x02g\u01C8\x03\x02" + "\x02\x02i\u01D4\x03\x02\x02\x02k\u01DE\x03\x02\x02\x02m\u01E1\x03\x02" + "\x02\x02o\u01EA\x03\x02\x02\x02q\u01F7\x03\x02\x02\x02s\u01FB\x03\x02" + "\x02\x02u\u01FE\x03\x02\x02\x02w\u0201\x03\x02\x02\x02y\u0205\x03\x02" + "\x02\x02{|\t\x02\x02\x02|\b\x03\x02\x02\x02}~\t\x03\x02\x02~\n\x03\x02" + "\x02\x02\x7F\x80\t\x04\x02\x02\x80\f\x03\x02\x02\x02\x81\x82\t\x05\x02" + "\x02\x82\x0E\x03\x02\x02\x02\x83\x84\t\x06\x02\x02\x84\x10\x03\x02\x02" + "\x02\x85\x86\t\x07\x02\x02\x86\x12\x03\x02\x02\x02\x87\x88\t\b\x02\x02" + "\x88\x14\x03\x02\x02\x02\x89\x8A\t\t\x02\x02\x8A\x16\x03\x02\x02\x02\x8B" + "\x8C\t\n\x02\x02\x8C\x18\x03\x02\x02\x02\x8D\x8E\t\v\x02\x02\x8E\x1A\x03" + "\x02\x02\x02\x8F\x90\t\f\x02\x02\x90\x1C\x03\x02\x02\x02\x91\x92\t\r\x02" + "\x02\x92\x1E\x03\x02\x02\x02\x93\x94\t\x0E\x02\x02\x94 \x03\x02\x02\x02" + "\x95\x96\x042;\x02\x96\"\x03\x02\x02\x02\x97\x98\t\x0F\x02\x02\x98$\x03" + "\x02\x02\x02\x99\x9F\x07)\x02\x02\x9A\x9B\x07^\x02\x02\x9B\x9E\t\x10\x02" + "\x02\x9C\x9E\n\x11\x02\x02\x9D\x9A\x03\x02\x02\x02\x9D\x9C\x03\x02\x02" + "\x02\x9E\xA1\x03\x02\x02\x02\x9F\xA0\x03\x02\x02\x02\x9F\x9D\x03\x02\x02" + "\x02\xA0\xA2\x03\x02\x02\x02\xA1\x9F\x03\x02\x02\x02\xA2\xAE\x07)\x02" + "\x02\xA3\xA9\x07$\x02\x02\xA4\xA5\x07^\x02\x02\xA5\xA8\t\x12\x02\x02\xA6" + "\xA8\n\x13\x02\x02\xA7\xA4\x03\x02\x02\x02\xA7\xA6\x03\x02\x02\x02\xA8" + "\xAB\x03\x02\x02\x02\xA9\xAA\x03\x02\x02\x02\xA9\xA7\x03\x02\x02\x02\xAA" + "\xAC\x03\x02\x02\x02\xAB\xA9\x03\x02\x02\x02\xAC\xAE\x07$\x02\x02\xAD" + "\x99\x03\x02\x02\x02\xAD\xA3\x03\x02\x02\x02\xAE&\x03\x02\x02\x02\xAF" + "\xB5\x07b\x02\x02\xB0\xB1\x07^\x02\x02\xB1\xB4\t\x14\x02\x02\xB2\xB4\n" + "\x15\x02\x02\xB3\xB0\x03\x02\x02\x02\xB3\xB2\x03\x02\x02\x02\xB4\xB7\x03" + "\x02\x02\x02\xB5\xB6\x03\x02\x02\x02\xB5\xB3\x03\x02\x02\x02\xB6\xB8\x03" + "\x02\x02\x02\xB7\xB5\x03\x02\x02\x02\xB8\xB9\x07b\x02\x02\xB9(\x03\x02" + "\x02\x02\xBA\xBC\x07^\x02\x02\xBB\xBD\n\x16\x02\x02\xBC\xBB\x03\x02\x02" + "\x02\xBC\xBD\x03\x02\x02\x02\xBD*\x03\x02\x02\x02\xBE\xC2\x05\x1F\x0E" + "\x02\xBF\xC2\x05!\x0F\x02\xC0\xC2\x07a\x02\x02\xC1\xBE\x03\x02\x02\x02" + "\xC1\xBF\x03\x02\x02\x02\xC1\xC0\x03\x02\x02\x02\xC2\xC8\x03\x02\x02\x02" + "\xC3\xC7\x05\x1F\x0E\x02\xC4\xC7\x05!\x0F\x02\xC5\xC7\x07a\x02\x02\xC6" + "\xC3\x03\x02\x02\x02\xC6\xC4\x03\x02\x02\x02\xC6\xC5\x03\x02\x02\x02\xC7" + "\xCA\x03\x02\x02\x02\xC8\xC6\x03\x02\x02\x02\xC8\xC9\x03\x02\x02\x02\xC9" + ",\x03\x02\x02\x02\xCA\xC8\x03\x02\x02\x02\xCB\xD2\x07}\x02\x02\xCC\xD1" + "\x05-\x15\x02\xCD\xD1\x05%\x11\x02\xCE\xD1\x05\'\x12\x02\xCF\xD1\n\x17" + "\x02\x02\xD0\xCC\x03\x02\x02\x02\xD0\xCD\x03\x02\x02\x02\xD0\xCE\x03\x02" + "\x02\x02\xD0\xCF\x03\x02\x02\x02\xD1\xD4\x03\x02\x02\x02\xD2\xD0\x03\x02" + "\x02\x02\xD2\xD3\x03\x02\x02\x02\xD3\xD5\x03\x02\x02\x02\xD4\xD2\x03\x02" + "\x02\x02\xD5\xD6\x07\x7F\x02\x02\xD6.\x03\x02\x02\x02\xD7\xD8\x07&\x02" + "\x02\xD8\xDD\x07}\x02\x02\xD9\xDE\x05%\x11\x02\xDA\xDE\x05\'\x12\x02\xDB" + "\xDE\x05-\x15\x02\xDC\xDE\n\x17\x02\x02\xDD\xD9\x03\x02\x02\x02\xDD\xDA" + "\x03\x02\x02\x02\xDD\xDB\x03\x02\x02\x02\xDD\xDC\x03\x02\x02\x02\xDE\xDF" + "\x03\x02\x02\x02\xDF\xDD\x03\x02\x02\x02\xDF\xE0\x03\x02\x02\x02\xE0\xE2" + "\x03\x02\x02\x02\xE1\xE3\x07\x7F\x02\x02\xE2\xE1\x03\x02\x02\x02\xE2\xE3" + "\x03\x02\x02\x02\xE30\x03\x02\x02\x02\xE4\xE6\x07\x0F\x02\x02\xE5\xE4" + "\x03\x02\x02\x02\xE5\xE6\x03\x02\x02\x02\xE6\xE7\x03\x02\x02\x02\xE7\xE8" + "\x07\f\x02\x02\xE82\x03\x02\x02\x02\xE9\xEB\x05#\x10\x02\xEA\xE9\x03\x02" + "\x02\x02\xEB\xEC\x03\x02\x02\x02\xEC\xEA\x03\x02\x02\x02\xEC\xED\x03\x02" + "\x02\x02\xED\xEE\x03\x02\x02\x02\xEE\xEF\b\x18\x02\x02\xEF4\x03\x02\x02" + "\x02\xF0\xF1\x051\x17\x02\xF1\xF2\x03\x02\x02\x02\xF2\xF3\b\x19\x02\x02" + "\xF36\x03\x02\x02\x02\xF4\xF8\x07@\x02\x02\xF5\xF7\n\x16\x02\x02\xF6\xF5" + "\x03\x02\x02\x02\xF7\xFA\x03\x02\x02\x02\xF8\xF6\x03\x02\x02\x02\xF8\xF9" + "\x03\x02\x02\x02\xF9\xFB\x03\x02\x02\x02\xFA\xF8\x03\x02\x02\x02\xFB\xFC" + "\b\x1A\x02\x02\xFC8\x03\x02\x02\x02\xFD\xFE\x07/\x02\x02\xFE\xFF\b\x1B" + "\x03\x02\xFF\u0100\x03\x02\x02\x02\u0100\u0101\b\x1B\x04\x02\u0101:\x03" + "\x02\x02\x02\u0102\u0103\x07]\x02\x02\u0103\u0104\x06\x1C\x02\x02\u0104" + "\u0105\b\x1C\x05\x02\u0105\u0106\x03\x02\x02\x02\u0106\u0107\b\x1C\x06" + "\x02\u0107<\x03\x02\x02\x02\u0108\u0109\v\x02\x02\x02\u0109\u010A\b\x1D" + "\x07\x02\u010A>\x03\x02\x02\x02\u010B\u010C\x05#\x10\x02\u010C\u0110\x06" + "\x1E\x03\x02\u010D\u010F\x05#\x10\x02\u010E\u010D\x03\x02\x02\x02\u010F" + "\u0112\x03\x02\x02\x02\u0110\u010E\x03\x02\x02\x02\u0110\u0111\x03\x02" + "\x02\x02\u0111\u0113\x03\x02\x02\x02\u0112\u0110\x03\x02\x02\x02\u0113" + "\u0114\b\x1E\x02\x02\u0114@\x03\x02\x02\x02\u0115\u0116\x07b\x02\x02\u0116" + "\u0117\x07b\x02\x02\u0117\u0118\x07b\x02\x02\u0118\u0119\x03\x02\x02\x02" + "\u0119\u011A\x06\x1F\x04\x02\u011A\u011B\b\x1F\b\x02\u011B\u011C\x03\x02" + "\x02\x02\u011C\u011D\b\x1F\t\x02\u011DB\x03\x02\x02\x02\u011E\u011F\x05" + "1\x17\x02\u011F\u0120\b \n\x02\u0120\u0121\x03\x02\x02\x02\u0121\u0122" + "\b \x02\x02\u0122\u0123\b \v\x02\u0123D\x03\x02\x02\x02\u0124\u0125\x05" + "\x13\b\x02\u0125\u0129\x05\x0F\x06\x02\u0126\u0128\x05#\x10\x02\u0127" + "\u0126\x03\x02\x02\x02\u0128\u012B\x03\x02\x02\x02\u0129\u0127\x03\x02" + "\x02\x02\u0129\u012A\x03\x02\x02\x02\u012A\u012C\x03\x02\x02\x02\u012B" + "\u0129\x03\x02\x02\x02\u012C\u012D\x07<\x02\x02\u012D\u012E\x06!\x05\x02" + "\u012E\u012F\b!\f\x02\u012FF\x03\x02\x02\x02\u0130\u0131\x05\r\x05\x02" + "\u0131\u0132\x05\x15\t\x02\u0132\u0133\x05\x17\n\x02\u0133\u0137\x05\r" + "\x05\x02\u0134\u0136\x05#\x10\x02\u0135\u0134\x03\x02\x02\x02\u0136\u0139" + "\x03\x02\x02\x02\u0137\u0135\x03\x02\x02\x02\u0137\u0138\x03\x02\x02\x02" + "\u0138\u013A\x03\x02\x02\x02\u0139\u0137\x03\x02\x02\x02\u013A\u013B\x05" + "\x13\b\x02\u013B\u013F\x05\x0F\x06\x02\u013C\u013E\x05#\x10\x02\u013D" + "\u013C\x03\x02\x02\x02\u013E\u0141\x03\x02\x02\x02\u013F\u013D\x03\x02" + "\x02\x02\u013F\u0140\x03\x02\x02\x02\u0140\u0142\x03\x02\x02\x02\u0141" + "\u013F\x03\x02\x02\x02\u0142\u0143\x07<\x02\x02\u0143\u0144\x06\"\x06" + "\x02\u0144\u0145\b\"\r\x02\u0145H\x03\x02\x02\x02\u0146\u0147\x05\r\x05" + "\x02\u0147\u0148\x05\x15\t\x02\u0148\u0149\x05\x17\n\x02\u0149\u014D\x05" + "\r\x05\x02\u014A\u014C\x05#\x10\x02\u014B\u014A\x03\x02\x02\x02\u014C" + "\u014F\x03\x02\x02\x02\u014D\u014B\x03\x02\x02\x02\u014D\u014E\x03\x02" + "\x02\x02\u014E\u0150\x03\x02\x02\x02\u014F\u014D\x03\x02\x02\x02\u0150" + "\u0151\x07<\x02\x02\u0151\u0152\x06#\x07\x02\u0152\u0153\b#\x0E\x02\u0153" + "J\x03\x02\x02\x02\u0154\u0155\x05\x17\n\x02\u0155\u0156\x05\x1D\r\x02" + "\u0156\u0157\x05\x13\b\x02\u0157\u0158\x05\x19\v\x02\u0158\u0159\x05\t" + "\x03\x02\u0159\u015D\x05\x11\x07\x02\u015A\u015C\x05#\x10\x02\u015B\u015A" + "\x03\x02\x02\x02\u015C\u015F\x03\x02\x02\x02\u015D\u015B\x03\x02\x02\x02" + "\u015D\u015E\x03\x02\x02\x02\u015E\u0160\x03\x02\x02\x02\u015F\u015D\x03" + "\x02\x02\x02\u0160\u0161\x07<\x02\x02\u0161\u0162\x06$\b\x02\u0162\u0163" + "\b$\x0F\x02\u0163L\x03\x02\x02\x02\u0164\u0165\x05\t\x03\x02\u0165\u0166" + "\x05\x07\x02\x02\u0166\u0167\x05\x17\n\x02\u0167\u016B\x05\r\x05\x02\u0168" + "\u016A\x05#\x10\x02\u0169\u0168\x03\x02\x02\x02\u016A\u016D\x03\x02\x02" + "\x02\u016B\u0169\x03\x02\x02\x02\u016B\u016C\x03\x02\x02\x02\u016C\u016E" + "\x03\x02\x02\x02\u016D\u016B\x03\x02\x02\x02\u016E\u016F\x07<\x02\x02" + "\u016F\u0170\x06%\t\x02\u0170\u0171\b%\x10\x02\u0171N\x03\x02\x02\x02" + "\u0172\u0173\x05\v\x04\x02\u0173\u0174\x05\r\x05\x02\u0174\u0175\x05\x0F" + "\x06\x02\u0175\u0176\x05\x07\x02\x02\u0176\u0177\x05\x1B\f\x02\u0177\u0178" + "\x05\x15\t\x02\u0178\u017C\x05\x19\v\x02\u0179\u017B\x05#\x10\x02\u017A" + "\u0179\x03\x02\x02\x02\u017B\u017E\x03\x02\x02\x02\u017C\u017A\x03\x02" + "\x02\x02\u017C\u017D\x03\x02\x02\x02\u017D\u017F\x03\x02\x02\x02\u017E" + "\u017C\x03\x02\x02\x02\u017F\u0180\x07<\x02\x02\u0180\u0181\x06&\n\x02" + "\u0181\u0182\b&\x11\x02\u0182P\x03\x02\x02\x02\u0183\u0184\x05)\x13\x02" + "\u0184\u0185\b\'\x12\x02\u0185R\x03\x02\x02\x02\u0186\u0187\x05/\x16\x02" + "\u0187\u0188\b(\x13\x02\u0188T\x03\x02\x02\x02\u0189\u018B\n\x16\x02\x02" + "\u018A\u0189\x03\x02\x02\x02\u018B\u018C\x03\x02\x02\x02\u018C\u018D\x03" + "\x02\x02\x02\u018C\u018A\x03\x02\x02\x02\u018D\u018E\x03\x02\x02\x02\u018E" + "\u018F\b)\x14\x02\u018FV\x03\x02\x02\x02\u0190\u0191\x07b\x02\x02\u0191" + "\u0192\x07b\x02\x02\u0192\u0193\x07b\x02\x02\u0193\u0194\x03\x02\x02\x02" + "\u0194\u0195\b*\x15\x02\u0195\u0196\x03\x02\x02\x02\u0196\u0197\b*\v\x02" + "\u0197X\x03\x02\x02\x02\u0198\u0199\x05)\x13\x02\u0199\u019A\x03\x02\x02" + "\x02\u019A\u019B\b+\x16\x02\u019BZ\x03\x02\x02\x02\u019C\u019D\x05/\x16" + "\x02\u019D\u019E\x03\x02\x02\x02\u019E\u019F\b,\x17\x02\u019F\\\x03\x02" + "\x02\x02\u01A0\u01A3\x051\x17\x02\u01A1\u01A3\n\x16\x02\x02\u01A2\u01A0" + "\x03\x02\x02\x02\u01A2\u01A1\x03\x02\x02\x02\u01A3\u01A4\x03\x02\x02\x02" + "\u01A4\u01A5\x03\x02\x02\x02\u01A4\u01A2\x03\x02\x02\x02\u01A5\u01A6\x03" + "\x02\x02\x02\u01A6\u01A7\b-\x18\x02\u01A7^\x03\x02\x02\x02\u01A8\u01AA" + "\x05#\x10\x02\u01A9\u01A8\x03\x02\x02\x02\u01AA\u01AB\x03\x02\x02\x02" + "\u01AB\u01A9\x03\x02\x02\x02\u01AB\u01AC\x03\x02\x02\x02\u01AC\u01AD\x03" + "\x02\x02\x02\u01AD\u01AE\b.\x02\x02\u01AE`\x03\x02\x02\x02\u01AF\u01B0" + "\x051\x17\x02\u01B0\u01B1\b/\x19\x02\u01B1\u01B2\b/\x1A\x02\u01B2\u01B3" + "\x03\x02\x02\x02\u01B3\u01B4\b/\x02\x02\u01B4\u01B5\b/\x1B\x02\u01B5b" + "\x03\x02\x02\x02\u01B6\u01BA\x05\x1F\x0E\x02\u01B7\u01BA\x05!\x0F\x02" + "\u01B8\u01BA\x07a\x02\x02\u01B9\u01B6\x03\x02\x02\x02\u01B9\u01B7\x03" + "\x02\x02\x02\u01B9\u01B8\x03\x02\x02\x02\u01BA\u01C0\x03\x02\x02\x02\u01BB" + "\u01BF\x05\x1F\x0E\x02\u01BC\u01BF\x05!\x0F\x02\u01BD\u01BF\t\x18\x02" + "\x02\u01BE\u01BB\x03\x02\x02\x02\u01BE\u01BC\x03\x02\x02\x02\u01BE\u01BD" + "\x03\x02\x02\x02\u01BF\u01C2\x03\x02\x02\x02\u01C0\u01BE\x03\x02\x02\x02" + "\u01C0\u01C1\x03\x02\x02\x02\u01C1d\x03\x02\x02\x02\u01C2\u01C0\x03\x02" + "\x02\x02\u01C3\u01C5\n\x16\x02\x02\u01C4\u01C3\x03\x02\x02\x02\u01C5\u01C6" + "\x03\x02\x02\x02\u01C6\u01C7\x03\x02\x02\x02\u01C6\u01C4\x03\x02\x02\x02" + "\u01C7f\x03\x02\x02\x02\u01C8\u01CC\x07@\x02\x02\u01C9\u01CB\n\x16\x02" + "\x02\u01CA\u01C9\x03\x02\x02\x02\u01CB\u01CE\x03\x02\x02\x02\u01CC\u01CA" + "\x03\x02\x02\x02\u01CC\u01CD\x03\x02\x02\x02\u01CD\u01CF\x03\x02\x02\x02" + "\u01CE\u01CC\x03\x02\x02\x02\u01CF\u01D0\x051\x17\x02\u01D0\u01D1\x06" + "2\v\x02\u01D1\u01D2\x03\x02\x02\x02\u01D2\u01D3\b2\x02\x02\u01D3h\x03" + "\x02\x02\x02\u01D4\u01D5\x05#\x10\x02\u01D5\u01D9\x063\f\x02\u01D6\u01D8" + "\x05#\x10\x02\u01D7\u01D6\x03\x02\x02\x02\u01D8\u01DB\x03\x02\x02\x02" + "\u01D9\u01D7\x03\x02\x02\x02\u01D9\u01DA\x03\x02\x02\x02\u01DA\u01DC\x03" + "\x02\x02\x02\u01DB\u01D9\x03\x02\x02\x02\u01DC\u01DD\b3\x02\x02\u01DD" + "j\x03\x02\x02\x02\u01DE\u01DF\x051\x17\x02\u01DF\u01E0\b4\x1C\x02\u01E0" + "l\x03\x02\x02\x02\u01E1\u01E2\x07_\x02\x02\u01E2\u01E3\x065\r\x02\u01E3" + "\u01E4\x03\x02\x02\x02\u01E4\u01E5\b5\v\x02\u01E5\u01E6\b5\v\x02\u01E6" + "n\x03\x02\x02\x02\u01E7\u01EB\x05\x1F\x0E\x02\u01E8\u01EB\x05!\x0F\x02" + "\u01E9\u01EB\x07a\x02\x02\u01EA\u01E7\x03\x02\x02\x02\u01EA\u01E8\x03" + "\x02\x02\x02\u01EA\u01E9\x03\x02\x02\x02\u01EB\u01F1\x03\x02\x02\x02\u01EC" + "\u01F0\x05\x1F\x0E\x02\u01ED\u01F0\x05!\x0F\x02\u01EE\u01F0\t\x18\x02" + "\x02\u01EF\u01EC\x03\x02\x02\x02\u01EF\u01ED\x03\x02\x02\x02\u01EF\u01EE" + "\x03\x02\x02\x02\u01F0\u01F3\x03\x02\x02\x02\u01F1\u01EF\x03\x02\x02\x02" + "\u01F1\u01F2\x03\x02\x02\x02\u01F2\u01F4\x03\x02\x02\x02\u01F3\u01F1\x03" + "\x02\x02\x02\u01F4\u01F5\x066\x0E\x02\u01F5\u01F6\b6\x1D\x02\u01F6p\x03" + "\x02\x02\x02\u01F7\u01F8\x07?\x02\x02\u01F8\u01F9\x067\x0F\x02\u01F9\u01FA" + "\b7\x1E\x02\u01FAr\x03\x02\x02\x02\u01FB\u01FC\x07~\x02\x02\u01FC\u01FD" + "\b8\x1F\x02\u01FDt\x03\x02\x02\x02\u01FE\u01FF\x05)\x13\x02\u01FF\u0200" + "\b9 \x02\u0200v\x03\x02\x02\x02\u0201\u0202\x05/\x16\x02\u0202\u0203\b" + ":!\x02\u0203x\x03\x02\x02\x02\u0204\u0206\n\x16\x02\x02\u0205\u0204\x03" + "\x02\x02\x02\u0206\u0207\x03\x02\x02\x02\u0207\u0208\x03\x02\x02\x02\u0207" + "\u0205\x03\x02\x02\x02\u0208\u0209\x03\x02\x02\x02\u0209\u020A\b;\"\x02" + "\u020Az\x03\x02\x02\x020\x02\x03\x04\x05\x06\x9D\x9F\xA7\xA9\xAD\xB3\xB5" + "\xBC\xC1\xC6\xC8\xD0\xD2\xDD\xDF\xE2\xE5\xEC\xF8\u0110\u0129\u0137\u013F" + "\u014D\u015D\u016B\u017C\u018C\u01A2\u01A4\u01AB\u01B9\u01BE\u01C0\u01C6" + "\u01CC\u01D9\u01EA\u01EF\u01F1\u0207#\b\x02\x02\x03\x1B\x02\x07\x03\x02" + "\x03\x1C\x03\x07\x05\x02\x03\x1D\x04\x03\x1F\x05\x07\x04\x02\x03 \x06" + "\x06\x02\x02\x03!\x07\x03\"\b\x03#\t\x03$\n\x03%\v\x03&\f\x03\'\r\x03" + "(\x0E\x03)\x0F\x03*\x10\t\x12\x02\t\x13\x02\t\x14\x02\x03/\x11\x03/\x12" + "\x07\x06\x02\x034\x13\x036\x14\x037\x15\x038\x16\x039\x17\x03:\x18\x03" + ";\x19"; public static __ATN: ATN; public static get _ATN(): ATN { if (!LGTemplateLexer.__ATN) { LGTemplateLexer.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(LGTemplateLexer._serializedATN)); } return LGTemplateLexer.__ATN; } }
the_stack
module BABYLON { export module Playground { var b = ace.require("ace/ext/beautify"); var n = '\n'; var jsEditorPosition: AceAjax.Position; // Helper to format string var format = (formatted: string, args: any[]) => { for (var i = 0; i < args.length; i++) { var regexp = new RegExp('\\{' + i + '\\}', 'gi'); formatted = formatted.replace(regexp, args[i]); } return formatted; }; export class Param { name: string; description: string; isRequired: boolean; isType: string; value: any; group: number; } export class Api { name: string; params: Param[]; methods: Method[]; script: string; } export class Method { name: string; params: Param[]; script: string; constructor(name?: string) { this.name = name; this.params = new Array<Param>(); } } export class Js { jsEditor: AceAjax.Editor; jsEditorJson: AceAjax.Editor; apis: Array<Playground.Api>; currentMethod: Playground.Method; currentApi: Playground.Api; cacheValue: Array<string>; jsonResponse: any; modal: JQuery; private log(data: any) { data = (data == null || data == undefined) ? [null] : data; this.jsonResponse = data; jsEditorPosition = this.jsEditor.getCursorPosition(); this.modal.modal(); } private error(error: any) { js.showMessage(error, true); var b = <JQuery>$('#btnGetResponse'); b.button('reset'); return; } constructor(callback) { this.initialize(callback); } private initialize(callback) { console.log = (e) => { this.log(e) }; console.error = (e) => this.error(e); this.jsEditor = ace.edit('editor'); this.jsEditor.setTheme("ace/theme/idle_fingers"); this.jsEditor.getSession().setMode("ace/mode/javascript"); this.jsEditor.setShowPrintMargin(false); this.jsEditor.setDisplayIndentGuides(false); this.jsEditorJson = ace.edit('editorJson'); this.jsEditorJson.setTheme("ace/theme/kuroir"); this.jsEditorJson.getSession().setMode("ace/mode/JSON"); this.jsEditorJson.getSession().setTabSize(2); this.jsEditorJson.getSession().setUseWrapMode(true); this.jsEditorJson.setShowPrintMargin(false); this.jsEditorJson.setDisplayIndentGuides(false); this.cacheValue = new Array<string>(); this.modal = <JQuery>$("#myModal"); this.modal.on('shown.bs.modal', (e) => { if (this.jsonResponse == null) this.modal.hide(); var str = JSON.stringify(this.jsonResponse, null, '\t'); var jsEditorJson = ace.edit('editorJson'); jsEditorJson.setValue(str); jsEditorJson.clearSelection(); jsEditorJson.gotoLine(1); jsEditorJson.focus(); var b = <any>$('#btnGetResponse'); b.button('reset'); }) this.modal.on('hidden.bs.modal', (e) => { var jsEditor = ace.edit('editor'); jsEditor.focus(); jsEditor.moveCursorToPosition(jsEditorPosition); }) this.initializeScripts(callback); } private getApplicationUrl() { var t = <HTMLInputElement>document.getElementById('s_applicationUrl'); return t.value;; } private getApplicationKey() { var t = <HTMLInputElement>document.getElementById('s_applicationKey'); return t.value; } private initializeScripts(callback) { //this.methods = new Array<Playground.Api>(); var jqxhr = $.getJSON("Scripts/playground/Apis.txt", (json: any) => { this.apis = <Array<Playground.Api>>json; this.apis.sort((a, b) => a.name.localeCompare(b.name)); for (var i = 0; i < this.apis.length; i++) { this.apis[i].methods.sort((a, b) => a.name.localeCompare(b.name)); } callback(); return; }); } public loadApis() { var sApiName = <HTMLSelectElement>document.getElementById("sApiName"); for (var index = 0; index < this.apis.length; index++) { var api = this.apis[index]; var opt = <HTMLOptionElement>document.createElement("option"); opt.id = index.toString() + "_" + api.name; opt.value = index.toString(); opt.innerText = api.name; sApiName.add(opt); } // set first api as the current Api this.currentApi = this.apis[0]; } public loadMethods() { var sApiMethodName = <HTMLSelectElement>document.getElementById("sApiMethodName"); while (sApiMethodName.options.length > 0) { sApiMethodName.remove(0); } for (var index = 0; index < this.currentApi.methods.length; index++) { var method = this.currentApi.methods[index]; var opt = <HTMLOptionElement>document.createElement("option"); opt.id = index.toString() + "_" + method.name; opt.value = index.toString(); opt.innerText = method.name; sApiMethodName.add(opt); } // set the first method as current method this.currentMethod = this.currentApi.methods[0]; } public requestJavascript() { this.closeMessage(); if (this.currentMethod == null) return; // before changing currentMethod, saving values filled by user this.saveCurrentVariables(); var scriptClient = this.currentApi.script; var apiParams = []; apiParams.push(JSON.stringify(this.getApplicationUrl())); apiParams.push(JSON.stringify(this.getApplicationKey())); if (this.currentApi.params != null) { for (var i = 0; i < this.currentApi.params.length; i++) { var p = this.currentApi.params[i]; var id = (p.group != null && p.group != undefined) ? p.group + '_' + p.name : '0_' + p.name; var elem = <HTMLInputElement>document.getElementById(id); if (p.isRequired && (!elem.value || elem.value == "")) { elem.parentElement.classList.add('has-error'); continue; } elem.parentElement.classList.remove('has-error'); var v = elem.value; if (p.isType == "text" || p.isType == "longtext") { v = JSON.stringify(v); } apiParams.push(v); } } var text = format(scriptClient, apiParams); text += n; text += n; // all grouped parameters (such as order, where, fields where I want {order:{xxx}, where:{zzz}, fields:'x,y,z'} var groups = []; // arrays containing params without group (literal inline ) // and params with group (object structure) var finalParamsWithGroup = [] var finalParamsWithoutGroup = []; // fill an array with params and values from HTML DOM if (this.currentMethod.params != null) { for (var i = 0; i < this.currentMethod.params.length; i++) { // get the definition of the parameter var p = this.currentMethod.params[i]; var id = (p.group != null && p.group != undefined) ? p.group + '_' + p.name : '0_' + p.name; // get the HTML element var elem = <HTMLInputElement>document.getElementById(id); if (!elem) continue; // check if value is required if (p.isRequired && (!elem.value || elem.value == "")) { elem.parentElement.classList.add('has-error'); continue; } elem.parentElement.classList.remove('has-error'); // get the value and if not null, add to my tab of 'params with values' if (elem.value != null && elem.value != "") { p.value = elem.value; } // if a group is available, add it to my if (p.group != undefined && elem.value != null && elem.value != "") { if (groups[p.group] == undefined) groups[p.group] = []; groups[p.group][p.name] = p.value; } // a param not assiocated with a group is a simple value if (p.group == undefined && elem.value != null && elem.value != "") { finalParamsWithoutGroup.push(JSON.stringify(p.value)); } } } // foreach group if (groups.length > 0) { for (var i in groups) { var strGroup = "{\n"; var g = <Array<string>>groups[i]; for (var j in g) { var ps = g[j]; if (ps.indexOf("{") == 0) strGroup += ' ' + j + ": " + ps; else strGroup += ' ' + j + ": " + JSON.stringify(ps); strGroup += "\n,"; } if (strGroup.lastIndexOf(",") == strGroup.length - 1) strGroup = strGroup.substring(0, strGroup.length - 1); strGroup += "}"; finalParamsWithGroup[i] = strGroup; } } //format all parameters wihtout any group if (finalParamsWithoutGroup.length > 0) { text += format(this.currentMethod.script, finalParamsWithoutGroup); } else { text += this.currentMethod.script; } // format for all parameters in groups for (var i in finalParamsWithGroup) { text = text.replace('{' + i.toString() + '}', finalParamsWithGroup[i]); } // bug to correct. Pacth mode engaged ! // You know "barbare mode" ? No ...fo sure, it's a french engaged mode. for (var i = 0; i <= 4; i++) { if (text.indexOf(', {' + i + '}') >= 0) text = text.replace(', {' + i + '}', ''); if (text.indexOf(',{' + i + '}') >= 0) text = text.replace(',{' + i + '}', ''); } for (var i = 0; i <= 4; i++) { if (text.indexOf('{' + i + '} ,') >= 0) text = text.replace('{' + i + '} ,', ''); if (text.indexOf('{' + i + '},') >= 0) text = text.replace('{' + i + '},', ''); } this.jsEditor.setValue(text, text.length); b.beautify(this.jsEditor.getSession()); } public saveCurrentVariables() { if (this.currentMethod == null) return; var divPanelBody = <HTMLDivElement>document.getElementById("divPanelBody"); var inputApiName = <HTMLInputElement>document.getElementById("inputApiName"); // All parameters for the current Api for (var i = 0; i < divPanelBody.children.length; i++) { var elem = divPanelBody.children[i]; if (elem instanceof HTMLDivElement) { for (var j = 0; j < (<HTMLInputElement>elem).children.length; j++) { var inputElem = (<HTMLInputElement>elem).children[j]; if (inputElem instanceof HTMLInputElement) { var input = <HTMLInputElement>inputElem; var id = input.id; if (id == null || id == "") continue; var value = input.value; this.cacheValue[id] = value; } } } } } public changeApi(value: number) { // before changing currentMethod, saving values filled by user this.saveCurrentVariables(); this.currentApi = this.apis[value]; this.loadMethods(); this.changeMethod(0); } public changeMethod(value: number) { // before changing currentMethod, saving values filled by user this.saveCurrentVariables(); this.currentMethod = this.currentApi.methods[value]; var divMethodName = <HTMLDivElement>document.getElementById("divMethodName"); var divPanelBody = <HTMLDivElement>document.getElementById("divPanelBody"); divPanelBody.innerHTML = ""; divMethodName.innerHTML = "<strong>Method :</strong> " + this.currentMethod.name; if (this.currentApi.params != null) { for (var index = 0; index < this.currentApi.params.length; index++) { var p = this.currentApi.params[index]; divPanelBody.innerHTML += this.getParamForm(p); } } if (this.currentMethod.params != null) { for (var index = 0; index < this.currentMethod.params.length; index++) { var p = this.currentMethod.params[index]; divPanelBody.innerHTML += this.getParamForm(p); } } } public getParamForm(p: Param) { var val = ""; var id = (p.group != null && p.group != undefined) ? p.group + '_' + p.name : '0_' + p.name; for (var k in this.cacheValue) { if (this.cacheValue.hasOwnProperty(k) && k == id) { val = this.cacheValue[k]; } } var req = ""; //p.isRequired ? "<span class='text-danger'>*</span>" : ""; var div = '<div class="input-group"> ' + ' <label class="input-group-addon" style="min-width:200px;" for= "' + id + '">' + p.description + '</label> ' + req + ' <input type="text" value="' + val + '" class="form-control" id = "' + id + '" placeholder = "' + p.name + '" > ' + ' </input> ' + '</div>'; if (p.isType && p.isType == "file") { div = '<div class="input-group"> ' + ' <label class="input-group-addon" for= "' + id + '">' + p.description + '</label> ' + req + '<span class="btn btn-default btn-block btn-file pull-right" > ' + 'Browse <input type="file" id="sfile" /></span> ' + '</div>'; } if (p.isType && p.isType == "longtext") { div = '<div class="form-group" > ' + ' <label class="control-label" for= "' + id + '">' + p.description + '</label> ' + req + ' <textarea rows="5" value="' + val + '" class="form-control" id = "' + id + '" ></textarea> ' + '</div> '; } return div; } public closeMessage() { var alertZone = <any>document.getElementById("alertZone"); (<JQuery>$(".alert")).alert('close') } public showMessage(message: string, isError?: boolean) { var classM = isError ? 'alert-danger' : 'alert-info'; var errorContent = '<div class="alert ' + classM + ' fade in" role="alert">' + '<button type="button" class="close" data-dismiss="alert">' + '<span aria-hidden="true">&times;</span>' + '<span class="sr-only">Close</span>' + '</button> ' + '<h4>An error occured !</h4> ' + '<p>' + message + '</p>' + '</div>'; var divError = <HTMLDivElement>document.getElementById("alertZone"); if (divError != null) divError.innerHTML = errorContent; } public compileAndRun() { try { var b = <any>$('#btnGetResponse'); b.button('loading'); // close message if open this.closeMessage(); var code = this.jsEditor.getValue(); eval(code); } catch (e) { console.error(e); } } public compress(s: any) { //// Compressed byte array can be converted into base64 to sumbit to server side to do something. //var b = Iuppiter.Base64.encode(s, true); //var bb = Iuppiter.toByteArray(b); //var db = Iuppiter.decompress(Iuppiter.Base64.decode(bb, true)); } }; } } var js = new BABYLON.Playground.Js(() => { // loading apis js.loadApis(); // loading methods js.loadMethods(); // loading params js.changeMethod(0); }); $("#btnScript").click(() => { js.requestJavascript(); var b = <any>$('#btnGetResponse'); b.button('reset'); }); $("#btnGetResponse").click(() => { js.compileAndRun(); }); $("#sApiName").on("change", () => { var selector = <HTMLSelectElement>document.getElementById("sApiName"); js.changeApi(+selector.value); }); $("#sApiMethodName").on("change", () => { var selector = <HTMLSelectElement>document.getElementById("sApiMethodName"); js.changeMethod(+selector.value); });
the_stack
import { Component, Renderer2, EventEmitter, Input, Output, ContentChildren, ContentChild, HostListener, AfterContentInit, ElementRef, AfterViewInit, QueryList, } from '@angular/core'; import { SprkInputDirective } from '../../directives/inputs/sprk-input/sprk-input.directive'; import { SprkAutocompleteResultsDirective } from './directives/sprk-autocomplete-results/sprk-autocomplete-results.directive'; import { SprkAutocompleteResultDirective } from './directives/sprk-autocomplete-result/sprk-autocomplete-result.directive'; import { SprkAutocompleteInputContainerDirective } from './directives/sprk-autocomplete-input-container/sprk-autocomplete-input-container.directive'; import { isDownPressed, isEnterPressed, isEscapePressed, isUpPressed, } from '../../utilities/keypress/keypress'; @Component({ selector: 'sprk-autocomplete', template: `<ng-content></ng-content>`, }) export class SprkAutocompleteComponent implements AfterContentInit, AfterViewInit { constructor(private ref: ElementRef, private renderer: Renderer2) {} /** * This component expects a child element * with the `sprkInput` directive. */ @ContentChild(SprkInputDirective, { static: false }) input: SprkInputDirective; /** * This component expects a child element * with the `sprkAutocompleteInputContainer` attribute. */ @ContentChild(SprkAutocompleteInputContainerDirective, { static: false }) inputContainer: SprkAutocompleteInputContainerDirective; /** * This component expects a child element * with the `sprkAutocompleteResults` directive. */ @ContentChild(SprkAutocompleteResultsDirective, { static: false, read: ElementRef, }) results: ElementRef; /** * This component expects the `sprkAutocompleteResults` child * to contain elements with the `sprkAutocompleteResult` directive. */ @ContentChildren(SprkAutocompleteResultDirective, { descendants: true }) resultItems: QueryList<SprkAutocompleteResultDirective>; /** * If `true`, the Autocomplete results will be visible when the component loads. */ @Input() isOpen = false; /** * This event will be emitted after the Autocomplete results are opened. */ @Output() openedEvent = new EventEmitter<any>(); /** * This event will be emitted after the Autocomplete results are closed. */ @Output() closedEvent = new EventEmitter<any>(); /** * This event will be emitted when an Autocomplete result is selected with * a click event or with the Enter key. The event contains the id of the * selected item. */ @Output() itemSelectedEvent = new EventEmitter<any>(); /** * @ignore */ @HostListener('document:keydown', ['$event']) onKeydown($event) { if (isEscapePressed($event) && this.isOpen) { this.hideResults(); } if (isUpPressed($event) && this.isOpen) { this.retreatHighlightedItem(); } if (isDownPressed($event) && this.isOpen) { this.advanceHighlightedItem(); } // Only select the list item if the list is open // and an item is highlighted if (isEnterPressed($event) && this.isOpen && this.highlightedIndex !== -1) { this.selectHighlightedListItem(); } } /** * @ignore */ @HostListener('document:click', ['$event']) onDocumentClick(event): void { if ( this.ref.nativeElement && !this.ref.nativeElement.contains(event.target) && this.isOpen ) { this.hideResults(); } } /** * @ignore */ @HostListener('window:resize', ['$event']) onResize(event): void { this.calculateResultsWidth(); } /** * @ignore * Highlight the previous item in the Autocomplete results. * Used for arrow key functionality. */ retreatHighlightedItem(): void { this.removeAllHighlights(); if (this.highlightedIndex < 0 || this.highlightedIndex - 1 === -1) { this.highlightedIndex = this.resultItems.length - 1; } else { this.highlightedIndex = this.highlightedIndex - 1; } this.highlightListItem(this.resultItems.toArray()[this.highlightedIndex]); } /** * @ignore * Highlight the next item in the Autocomplete results. * Used for arrow key functionality. */ advanceHighlightedItem(): void { this.removeAllHighlights(); if (this.highlightedIndex < 0) { this.highlightedIndex = 0; } else if (this.highlightedIndex + 1 <= this.resultItems.length - 1) { this.highlightedIndex = this.highlightedIndex + 1; } else { this.highlightedIndex = 0; } this.highlightListItem(this.resultItems.toArray()[this.highlightedIndex]); } /** * @ignore * Remove the highlight from all Autocomplete result items. */ removeAllHighlights(): void { this.resultItems.forEach((element, index) => { element.isSelected = false; }); } /** * Highlight a specific element in the Autocomplete results. If the Enter * key is pressed, the itemSelectedEvent will be emitted with this * element's id. * @param listItemElement The element to highlight. */ highlightListItem(listItemElement): void { if (listItemElement) { listItemElement.isSelected = true; // set aria-activedescendant on the input to the id of the // highlighted item if (this.input) { this.renderer.setAttribute( this.input.ref.nativeElement, 'aria-activedescendant', listItemElement.ref.nativeElement.id, ); } } } /** * Emit the itemSelectedEvent with the currently-highlighted Autocomplete * result item. */ selectHighlightedListItem(): void { let selectedElement = this.resultItems.filter( (element) => element.isSelected, )[0]; let selectedId = selectedElement.ref.nativeElement.id; this.itemSelectedEvent.emit(selectedId); } /** * Hide the Autocomplete results list. */ hideResults(): void { if (!this.results) { return; } // Add the hidden style this.renderer.addClass( this.results.nativeElement, 'sprk-c-Autocomplete__results--is-hidden', ); if (this.input) { // Set aria-expanded on the input's parent this.renderer.setAttribute( this.inputContainer.ref.nativeElement, 'aria-expanded', 'false', ); // Remove aria-activedescendant from the input this.renderer.removeAttribute( this.input.ref.nativeElement, 'aria-activedescendant', ); } // remove aria-selected and highlight class from all list items this.removeAllHighlights(); this.closedEvent.emit(); this.isOpen = false; } /** * Show the Autocomplete results list. */ showResults(): void { if (!this.results) { return; } this.renderer.removeClass( this.results.nativeElement, 'sprk-c-Autocomplete__results--is-hidden', ); if (this.input) { // Set aria-expanded on the input's parent this.renderer.setAttribute( this.inputContainer.ref.nativeElement, 'aria-expanded', 'true', ); } this.openedEvent.emit(); this.isOpen = true; } /** * If itemSelectedEvent is specified, also set that as the click event on each result. * This should be called automatically whenever the results list is changed. */ bindClickEvents(): void { if (this.itemSelectedEvent) { // bind the click event on each individual result item. this.resultItems.forEach((autocompleteResultDirective) => { autocompleteResultDirective.clickedEvent = this.itemSelectedEvent; }); } } /** * @ignore * Track the index of the currently-highlighted Autocomplete result item. */ highlightedIndex = -1; /** * @ignore */ ngAfterContentInit(): void { if (this.results) { if (this.isOpen) { this.showResults(); } else { this.hideResults(); } } // If there are any result items in the component when it initializes, // set up their click events. this.bindClickEvents(); // If the result items change at runtime (by a filter, etc), // redo the click events. this.resultItems.changes.subscribe((_) => { this.bindClickEvents(); }); } /** * @ignore * This logic needs to happen in this event so that the correct DOM * attributes will have been set. */ ngAfterViewInit(): void { if (!this.input || !this.results) { return; } this.calculateResultsWidth(); // set aria-controls on the input to the id of the results this.generateAriaControls(this.input.ref, this.results); // set aria-owns on the input's parent to the id of the results this.generateAriaOwns(this.inputContainer.ref, this.results); } /** * @ignore * Set the max-width on the Autocomplete results equal to the current * width of the input element. */ calculateResultsWidth() { if (!this.input || !this.results) { return; } const currentInputWidth = this.input.ref.nativeElement.offsetWidth; this.renderer.setAttribute( this.results.nativeElement, 'style', 'max-width:' + currentInputWidth + 'px', ); } /** * Copy the value of the id attribute on contentElement * into the aria-controls attribute on triggerElement. * @param triggerElement The element that will receive the aria-controls attribute. * @param contentElement The element that will receive an id if needed. */ generateAriaControls = ( triggerElement: ElementRef, contentElement: ElementRef, ) => { const triggerAriaControls = triggerElement.nativeElement.getAttribute( 'aria-controls', ); let contentId = contentElement.nativeElement.getAttribute('id'); // Do nothing if aria-controls exists but the id does not if (triggerAriaControls && !contentId) { return; } // Do nothing if aria-controls and id both exist but don't match if (contentId && triggerAriaControls && contentId !== triggerAriaControls) { return; } // set the value of aria-controls this.renderer.setAttribute( triggerElement.nativeElement, 'aria-controls', contentId, ); }; /** * Copy the value of the id attribute on contentElement * into the aria-owns attribute on ownerElement. * @param ownerElement The element that will receive the aria-owns attribute. * @param contentElement The element that will receive an id if needed. */ generateAriaOwns = (ownerElement: ElementRef, contentElement: ElementRef) => { const ownerAriaOwns = ownerElement.nativeElement.getAttribute('aria-owns'); let contentId = contentElement.nativeElement.getAttribute('id'); // Do nothing if aria-owns exists but the id does not if (ownerAriaOwns && !contentId) { return; } // Do nothing if aria-owns and id both exist but don't match if (contentId && ownerAriaOwns && contentId !== ownerAriaOwns) { return; } // set the value of aria-owns this.renderer.setAttribute( ownerElement.nativeElement, 'aria-owns', contentId, ); }; }
the_stack
import {BackgroundGraphicsModeRestriction, CrButtonElement, CrCheckboxElement, NativeInitialSettings, NativeLayerImpl, PluginProxyImpl, PolicyObjectEntry, PrintPreviewAppElement, PrintPreviewPluralStringProxyImpl, SerializedSettings} from 'chrome://print/print_preview.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {ColorModeRestriction, DuplexMode, DuplexModeRestriction, PinModeRestriction} from 'chrome://print/print_preview.js'; // </if> import {assert} from 'chrome://resources/js/assert.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertEquals, assertFalse} from 'chrome://webui-test/chai_assert.js'; import {TestPluralStringProxy} from 'chrome://webui-test/test_plural_string_proxy.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {setNativeLayerCrosInstance} from './native_layer_cros_stub.js'; // </if> import {NativeLayerStub} from './native_layer_stub.js'; import {getDefaultInitialSettings} from './print_preview_test_utils.js'; import {TestPluginProxy} from './test_plugin_proxy.js'; const policy_tests = { suiteName: 'PolicyTest', TestNames: { HeaderFooterPolicy: 'header/footer policy', CssBackgroundPolicy: 'css background policy', MediaSizePolicy: 'media size policy', SheetsPolicy: 'sheets policy', ColorPolicy: 'color policy', DuplexPolicy: 'duplex policy', PinPolicy: 'pin policy', PrintPdfAsImageAvailability: 'print as image available for PDF policy', PrintPdfAsImageDefault: 'print as image option default for PDF policy' }, }; Object.assign(window, {policy_tests: policy_tests}); type AllowedDefaultModePolicySetup = { settingName: string, serializedSettingName?: string, allowedMode: any, defaultMode: any, }; class PolicyTestPluralStringProxy extends TestPluralStringProxy { text: string = ''; getPluralString(messageName: string, itemCount: number) { if (messageName === 'sheetsLimitErrorMessage') { this.methodCalled('getPluralString', {messageName, itemCount}); } return Promise.resolve(this.text); } } suite(policy_tests.suiteName, function() { let page: PrintPreviewAppElement; /** * @return A Promise that resolves once initial settings are done * loading. */ function loadInitialSettings(initialSettings: NativeInitialSettings): Promise<void> { document.body.innerHTML = ''; const nativeLayer = new NativeLayerStub(); nativeLayer.setInitialSettings(initialSettings); nativeLayer.setLocalDestinations( [{deviceName: initialSettings.printerName, printerName: 'FooName'}]); nativeLayer.setPageCount(3); NativeLayerImpl.setInstance(nativeLayer); // <if expr="chromeos_ash or chromeos_lacros"> setNativeLayerCrosInstance(); // </if> const pluginProxy = new TestPluginProxy(); PluginProxyImpl.setInstance(pluginProxy); page = document.createElement('print-preview-app'); document.body.appendChild(page); // Wait for initialization to complete. return Promise .all([ nativeLayer.whenCalled('getInitialSettings'), nativeLayer.whenCalled('getPrinterCapabilities') ]) .then(function() { flush(); }); } /** * Sets up the Print Preview app, and loads initial settings with the given * policy. * @param policies Policies to set up. * @param isPdf If settings are for previewing a PDF. * @return A Promise that resolves once initial settings are done loading. */ function doAllowedDefaultModePoliciesSetup( policies: AllowedDefaultModePolicySetup[], isPdf: boolean = false): Promise<void> { const initialSettings = getDefaultInitialSettings(isPdf); const appState: SerializedSettings = {version: 2}; let setSerializedAppState = false; initialSettings.policies = {}; policies.forEach(setup => { if (setup.allowedMode !== undefined || setup.defaultMode !== undefined) { const policy: PolicyObjectEntry = {}; if (setup.allowedMode !== undefined) { policy.allowedMode = setup.allowedMode; } if (setup.defaultMode !== undefined) { policy.defaultMode = setup.defaultMode; } (initialSettings.policies as {[key: string]: any})[setup.settingName] = policy; } if (setup.defaultMode !== undefined && setup.serializedSettingName !== undefined) { // We want to make sure sticky settings get overridden. (appState as {[key: string]: any})[setup.serializedSettingName] = !setup.defaultMode; setSerializedAppState = true; } }); if (setSerializedAppState) { initialSettings.serializedAppStateStr = JSON.stringify(appState); } return loadInitialSettings(initialSettings); } /** * Sets up the Print Preview app, and loads initial settings with the * given policy. * @param settingName Name of the setting to set up. * @param value The value to set for the policy. * @return A Promise that resolves once initial settings are done loading. */ function doValuePolicySetup(settingName: string, value: any): Promise<void> { const initialSettings = getDefaultInitialSettings(); if (value !== undefined) { const policy: PolicyObjectEntry = {value: value}; initialSettings.policies = {[settingName]: policy}; } return loadInitialSettings(initialSettings); } function toggleMoreSettings() { const moreSettingsElement = page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot! .querySelector('print-preview-more-settings')!; moreSettingsElement.$.label.click(); } function getCheckbox(settingName: string): CrCheckboxElement { return page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot! .querySelector('print-preview-other-options-settings')!.shadowRoot! .querySelector<CrCheckboxElement>(`#${settingName}`)!; } // Tests different scenarios of applying header/footer policy. test(assert(policy_tests.TestNames.HeaderFooterPolicy), async () => { const tests = [ { // No policies. allowedMode: undefined, defaultMode: undefined, expectedDisabled: false, expectedChecked: true, }, { // Restrict header/footer to be enabled. allowedMode: true, defaultMode: undefined, expectedDisabled: true, expectedChecked: true, }, { // Restrict header/footer to be disabled. allowedMode: false, defaultMode: undefined, expectedDisabled: true, expectedChecked: false, }, { // Check header/footer checkbox. allowedMode: undefined, defaultMode: true, expectedDisabled: false, expectedChecked: true, }, { // Uncheck header/footer checkbox. allowedMode: undefined, defaultMode: false, expectedDisabled: false, expectedChecked: false, } ]; for (const subtestParams of tests) { await doAllowedDefaultModePoliciesSetup([{ settingName: 'headerFooter', serializedSettingName: 'isHeaderFooterEnabled', allowedMode: subtestParams.allowedMode, defaultMode: subtestParams.defaultMode }]); toggleMoreSettings(); const checkbox = getCheckbox('headerFooter'); assertEquals(subtestParams.expectedDisabled, checkbox.disabled); assertEquals(subtestParams.expectedChecked, checkbox.checked); } }); // Tests different scenarios of applying background graphics policy. test(assert(policy_tests.TestNames.CssBackgroundPolicy), async () => { const tests = [ { // No policies. allowedMode: undefined, defaultMode: undefined, expectedDisabled: false, expectedChecked: false, }, { // Restrict background graphics to be enabled. // Check that checkbox value default mode is not applied if it // contradicts allowed mode. allowedMode: BackgroundGraphicsModeRestriction.ENABLED, defaultMode: BackgroundGraphicsModeRestriction.DISABLED, expectedDisabled: true, expectedChecked: true, }, { // Restrict background graphics to be disabled. allowedMode: BackgroundGraphicsModeRestriction.DISABLED, defaultMode: undefined, expectedDisabled: true, expectedChecked: false, }, { // Check background graphics checkbox. allowedMode: undefined, defaultMode: BackgroundGraphicsModeRestriction.ENABLED, expectedDisabled: false, expectedChecked: true, }, { // Uncheck background graphics checkbox. allowedMode: BackgroundGraphicsModeRestriction.UNSET, defaultMode: BackgroundGraphicsModeRestriction.DISABLED, expectedDisabled: false, expectedChecked: false, } ]; for (const subtestParams of tests) { await doAllowedDefaultModePoliciesSetup([{ settingName: 'cssBackground', serializedSettingName: 'isCssBackgroundEnabled', allowedMode: subtestParams.allowedMode, defaultMode: subtestParams.defaultMode }]); toggleMoreSettings(); const checkbox = getCheckbox('cssBackground'); assertEquals(subtestParams.expectedDisabled, checkbox.disabled); assertEquals(subtestParams.expectedChecked, checkbox.checked); } }); // Tests different scenarios of applying default paper policy. test(assert(policy_tests.TestNames.MediaSizePolicy), async () => { const tests = [ { // No policies. defaultMode: undefined, expectedName: 'NA_LETTER', }, { // Not available option shouldn't change actual paper size setting. defaultMode: {width: 200000, height: 200000}, expectedName: 'NA_LETTER', }, { // Change default paper size setting. defaultMode: {width: 215900, height: 215900}, expectedName: 'CUSTOM', } ]; for (const subtestParams of tests) { await doAllowedDefaultModePoliciesSetup([{ settingName: 'mediaSize', serializedSettingName: undefined, allowedMode: undefined, defaultMode: subtestParams.defaultMode }]); toggleMoreSettings(); const mediaSettingsSelect = page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot! .querySelector('print-preview-media-size-settings')!.shadowRoot! .querySelector('print-preview-settings-select')!.shadowRoot! .querySelector('select')!; assertEquals( subtestParams.expectedName, JSON.parse(mediaSettingsSelect.value).name); } }); test(assert(policy_tests.TestNames.SheetsPolicy), async () => { const pluralString = new PolicyTestPluralStringProxy(); PrintPreviewPluralStringProxyImpl.setInstance(pluralString); pluralString.text = 'Exceeds limit of 1 sheet of paper'; const tests = [ { // No policy. maxSheets: 0, pages: [1, 2, 3], expectedDisabled: false, expectedHidden: true, expectedNonEmptyErrorMessage: false, }, { // Policy is set, actual pages are not calculated yet. maxSheets: 3, pages: [], expectedDisabled: true, expectedHidden: true, expectedNonEmptyErrorMessage: false, }, { // Policy is set, but the limit is not hit. maxSheets: 3, pages: [1, 2], expectedDisabled: false, expectedHidden: true, expectedNonEmptyErrorMessage: false, }, { // Policy is set, the limit is hit, singular form is used. maxSheets: 1, pages: [1, 2], expectedDisabled: true, expectedHidden: false, expectedNonEmptyErrorMessage: true, }, { // Policy is set, the limit is hit, plural form is used. maxSheets: 2, pages: [1, 2, 3, 4], expectedDisabled: true, expectedHidden: false, expectedNonEmptyErrorMessage: true, } ]; for (const subtestParams of tests) { await doValuePolicySetup('sheets', subtestParams.maxSheets); pluralString.resetResolver('getPluralString'); page.setSetting('pages', subtestParams.pages); if (subtestParams.expectedNonEmptyErrorMessage) { const pluralStringArgs = await pluralString.whenCalled('getPluralString'); assertEquals(subtestParams.maxSheets, pluralStringArgs.itemCount); } const printButton = page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot! .querySelector('print-preview-button-strip')!.shadowRoot! .querySelector<CrButtonElement>('cr-button.action-button')!; const errorMessage = page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot! .querySelector('print-preview-button-strip')!.shadowRoot! .querySelector<HTMLElement>('div.error-message')!; assertEquals(subtestParams.expectedDisabled, printButton.disabled); assertEquals(subtestParams.expectedHidden, errorMessage.hidden); assertEquals( subtestParams.expectedNonEmptyErrorMessage, !errorMessage.hidden && !!errorMessage.innerText); } }); // <if expr="chromeos_ash or chromeos_lacros"> // Tests different scenarios of color printing policy. test(assert(policy_tests.TestNames.ColorPolicy), async () => { const tests = [ { // No policies. allowedMode: undefined, defaultMode: undefined, expectedDisabled: false, expectedValue: 'color', }, { // Print in color by default. allowedMode: undefined, defaultMode: ColorModeRestriction.COLOR, expectedDisabled: false, expectedValue: 'color', }, { // Print in black and white by default. allowedMode: undefined, defaultMode: ColorModeRestriction.MONOCHROME, expectedDisabled: false, expectedValue: 'bw', }, { // Allowed and default policies unset. allowedMode: ColorModeRestriction.UNSET, defaultMode: ColorModeRestriction.UNSET, expectedDisabled: false, expectedValue: 'bw', }, { // Allowed unset, default set to color printing. allowedMode: ColorModeRestriction.UNSET, defaultMode: ColorModeRestriction.COLOR, expectedDisabled: false, expectedValue: 'color', }, { // Enforce color printing. allowedMode: ColorModeRestriction.COLOR, defaultMode: ColorModeRestriction.UNSET, expectedDisabled: true, expectedValue: 'color', }, { // Enforce black and white printing. allowedMode: ColorModeRestriction.MONOCHROME, defaultMode: undefined, expectedDisabled: true, expectedValue: 'bw', }, { // Enforce color printing, default is ignored. allowedMode: ColorModeRestriction.COLOR, defaultMode: ColorModeRestriction.MONOCHROME, expectedDisabled: true, expectedValue: 'color', }, ]; for (const subtestParams of tests) { await doAllowedDefaultModePoliciesSetup([{ settingName: 'color', serializedSettingName: 'isColorEnabled', allowedMode: subtestParams.allowedMode, defaultMode: subtestParams.defaultMode }]); const colorSettingsSelect = page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot! .querySelector('print-preview-color-settings')!.shadowRoot! .querySelector('select')!; assertEquals( subtestParams.expectedDisabled, colorSettingsSelect.disabled); assertEquals(subtestParams.expectedValue, colorSettingsSelect.value); } }); // Tests different scenarios of duplex printing policy. test(assert(policy_tests.TestNames.DuplexPolicy), async () => { const tests = [ { // No policies. allowedMode: undefined, defaultMode: undefined, expectedChecked: false, expectedOpened: false, expectedDisabled: false, expectedValue: DuplexMode.LONG_EDGE, }, { // No restriction, default set to SIMPLEX. allowedMode: undefined, defaultMode: DuplexModeRestriction.SIMPLEX, expectedChecked: false, expectedOpened: false, expectedDisabled: false, expectedValue: DuplexMode.LONG_EDGE, }, { // No restriction, default set to UNSET. allowedMode: undefined, defaultMode: DuplexModeRestriction.UNSET, expectedChecked: true, expectedOpened: true, expectedDisabled: false, expectedValue: DuplexMode.LONG_EDGE, }, { // Allowed mode set to UNSET. allowedMode: DuplexModeRestriction.UNSET, defaultMode: undefined, expectedChecked: false, expectedOpened: false, expectedDisabled: false, expectedValue: DuplexMode.LONG_EDGE, }, { // No restriction, default set to LONG_EDGE. allowedMode: undefined, defaultMode: DuplexModeRestriction.LONG_EDGE, expectedChecked: true, expectedOpened: true, expectedDisabled: false, expectedValue: DuplexMode.LONG_EDGE, }, { // No restriction, default set to SHORT_EDGE. allowedMode: undefined, defaultMode: DuplexModeRestriction.SHORT_EDGE, expectedChecked: true, expectedOpened: true, expectedDisabled: false, expectedValue: DuplexMode.SHORT_EDGE, }, { // No restriction, default set to DUPLEX. allowedMode: undefined, defaultMode: DuplexModeRestriction.DUPLEX, expectedChecked: true, expectedOpened: true, expectedDisabled: false, expectedValue: DuplexMode.LONG_EDGE, }, { // No restriction, default set to SHORT_EDGE. allowedMode: DuplexModeRestriction.SIMPLEX, defaultMode: undefined, expectedChecked: false, expectedOpened: false, expectedDisabled: false, expectedValue: DuplexMode.LONG_EDGE, }, { // Restricted to LONG_EDGE. allowedMode: DuplexModeRestriction.LONG_EDGE, defaultMode: undefined, expectedChecked: true, expectedOpened: true, expectedDisabled: true, expectedValue: DuplexMode.LONG_EDGE, }, { // Restricted to SHORT_EDGE. allowedMode: DuplexModeRestriction.SHORT_EDGE, defaultMode: undefined, expectedChecked: true, expectedOpened: true, expectedDisabled: true, expectedValue: DuplexMode.SHORT_EDGE, }, { // Restricted to DUPLEX. allowedMode: DuplexModeRestriction.DUPLEX, defaultMode: undefined, expectedChecked: true, expectedOpened: true, expectedDisabled: false, expectedValue: DuplexMode.LONG_EDGE, }, { // Restricted to SHORT_EDGE, default is ignored. allowedMode: DuplexModeRestriction.SHORT_EDGE, defaultMode: DuplexModeRestriction.LONG_EDGE, expectedChecked: true, expectedOpened: true, expectedDisabled: true, expectedValue: DuplexMode.SHORT_EDGE, }, ]; for (const subtestParams of tests) { await doAllowedDefaultModePoliciesSetup([{ settingName: 'duplex', serializedSettingName: 'isDuplexEnabled', allowedMode: subtestParams.allowedMode, defaultMode: subtestParams.defaultMode }]); toggleMoreSettings(); const duplexSettingsSection = page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot! .querySelector('print-preview-duplex-settings')!; const checkbox = duplexSettingsSection.shadowRoot!.querySelector('cr-checkbox')!; const collapse = duplexSettingsSection.shadowRoot!.querySelector('iron-collapse')!; const select = duplexSettingsSection.shadowRoot!.querySelector('select')!; const expectedValue = subtestParams.expectedValue.toString(); assertEquals(subtestParams.expectedChecked, checkbox.checked); assertEquals(subtestParams.expectedOpened, collapse.opened); assertEquals(subtestParams.expectedDisabled, select.disabled); assertEquals(expectedValue, select.value); } }); // Tests different scenarios of pin printing policy. test(assert(policy_tests.TestNames.PinPolicy), async () => { const tests = [ { // No policies. allowedMode: undefined, defaultMode: undefined, expectedCheckboxDisabled: false, expectedChecked: false, expectedOpened: false, expectedInputDisabled: true, }, { // No restriction, default set to UNSET. allowedMode: undefined, defaultMode: PinModeRestriction.UNSET, expectedCheckboxDisabled: false, expectedChecked: false, expectedOpened: false, expectedInputDisabled: true, }, { // No restriction, default set to PIN. allowedMode: undefined, defaultMode: PinModeRestriction.PIN, expectedCheckboxDisabled: false, expectedChecked: true, expectedOpened: true, expectedInputDisabled: false, }, { // No restriction, default set to NO_PIN. allowedMode: undefined, defaultMode: PinModeRestriction.NO_PIN, expectedCheckboxDisabled: false, expectedChecked: false, expectedOpened: false, expectedInputDisabled: true, }, { // Restriction se to UNSET. allowedMode: PinModeRestriction.UNSET, defaultMode: undefined, expectedCheckboxDisabled: false, expectedChecked: false, expectedOpened: false, expectedInputDisabled: true, }, { // Restriction set to PIN. allowedMode: PinModeRestriction.PIN, defaultMode: undefined, expectedCheckboxDisabled: true, expectedChecked: true, expectedOpened: true, expectedInputDisabled: false, }, { // Restriction set to NO_PIN. allowedMode: PinModeRestriction.NO_PIN, defaultMode: undefined, expectedCheckboxDisabled: true, expectedChecked: false, expectedOpened: false, expectedInputDisabled: true, }, { // Restriction set to PIN, default is ignored. allowedMode: PinModeRestriction.NO_PIN, defaultMode: PinModeRestriction.PIN, expectedCheckboxDisabled: true, expectedChecked: false, expectedOpened: false, expectedInputDisabled: true, }, ]; for (const subtestParams of tests) { const initialSettings = getDefaultInitialSettings(); if (subtestParams.allowedMode !== undefined || subtestParams.defaultMode !== undefined) { const policy: PolicyObjectEntry = {}; if (subtestParams.allowedMode !== undefined) { policy.allowedMode = subtestParams.allowedMode; } if (subtestParams.defaultMode !== undefined) { policy.defaultMode = subtestParams.defaultMode; } initialSettings.policies = {'pin': policy}; } const appState: SerializedSettings = {version: 2, 'pinValue': '0000'}; if (subtestParams.defaultMode !== undefined) { appState.isPinEnabled = !subtestParams.defaultMode; } initialSettings.serializedAppStateStr = JSON.stringify(appState); await loadInitialSettings(initialSettings); const pinSettingsSection = page.shadowRoot!.querySelector('print-preview-sidebar')!.shadowRoot! .querySelector('print-preview-pin-settings')!; const checkbox = pinSettingsSection.shadowRoot!.querySelector('cr-checkbox')!; const collapse = pinSettingsSection.shadowRoot!.querySelector('iron-collapse')!; const input = pinSettingsSection.shadowRoot!.querySelector('cr-input')!; assertEquals(subtestParams.expectedCheckboxDisabled, checkbox.disabled); assertEquals(subtestParams.expectedChecked, checkbox.checked); assertEquals(subtestParams.expectedOpened, collapse.opened); assertEquals(subtestParams.expectedInputDisabled, input.disabled); } }); // </if> // <if expr="is_win or is_macosx"> // Tests different scenarios of PDF print as image option policy. // Should be available only for PDF when the policy explicitly allows print // as image, and hidden the rest of the cases. test(assert(policy_tests.TestNames.PrintPdfAsImageAvailability), async () => { const tests = [ { // No policies with modifiable content. allowedMode: undefined, isPdf: false, expectedHidden: true, }, { // No policies with PDF content. allowedMode: undefined, isPdf: true, expectedHidden: true, }, { // Explicitly restrict "Print as image" option for modifiable content. allowedMode: false, isPdf: false, expectedHidden: true, }, { // Explicitly restrict "Print as image" option for PDF content. allowedMode: false, isPdf: true, expectedHidden: true, }, { // Explicitly enable "Print as image" option for modifiable content. allowedMode: true, isPdf: false, expectedHidden: true, }, { // Explicitly enable "Print as image" option for PDF content. allowedMode: true, isPdf: true, expectedHidden: false, }, ]; for (const subtestParams of tests) { await doAllowedDefaultModePoliciesSetup( [{ settingName: 'printPdfAsImageAvailability', serializedSettingName: 'isRasterizeEnabled', allowedMode: subtestParams.allowedMode, defaultMode: undefined }], /*isPdf=*/ subtestParams.isPdf); toggleMoreSettings(); const checkbox = getCheckbox('rasterize'); assertEquals( subtestParams.expectedHidden, (checkbox.parentNode!.parentNode! as HTMLElement).hidden); } }); // </if> // Tests different scenarios of PDF "Print as image" option default policy. // Default only has an effect when the "Print as image" option is available. // The policy controls if it defaults to set.Test behavior varies by platform // since the option's availability is policy controlled for Windows and macOS // but is always available for Linux and ChromeOS. test(assert(policy_tests.TestNames.PrintPdfAsImageDefault), async () => { const tests = [ // <if expr="is_linux or chromeos"> { // `availableAllowedMode` is irrelevant, option is always present. // No policy for default of "Print as image" option. availableAllowedMode: undefined, selectedDefaultMode: undefined, expectedChecked: false, }, { // `availableAllowedMode` is irrelevant, option is always present. // Explicitly default "Print as image" to unset for PDF content. availableAllowedMode: undefined, selectedDefaultMode: false, expectedChecked: false, }, { // `availableAllowedMode` is irrelevant, option is always present. // Explicitly default "Print as image" to set for PDF content. availableAllowedMode: undefined, selectedDefaultMode: true, expectedChecked: true, }, // </if> { // Explicitly enable "Print as image" option for PDF content. // No policy for default of "Print as image" option. availableAllowedMode: true, selectedDefaultMode: undefined, expectedChecked: false, }, { // Explicitly enable "Print as image" option for PDF content. // Explicitly default "Print as image" to unset. availableAllowedMode: true, selectedDefaultMode: false, expectedChecked: false, }, { // Explicitly enable "Print as image" option for PDF content. // Explicitly default "Print as image" to set. availableAllowedMode: true, selectedDefaultMode: true, expectedChecked: true, }, ]; for (const subtestParams of tests) { await doAllowedDefaultModePoliciesSetup( [ { settingName: 'printPdfAsImageAvailability', serializedSettingName: 'isRasterizeEnabled', allowedMode: subtestParams.availableAllowedMode, defaultMode: undefined, }, { settingName: 'printPdfAsImage', serializedSettingName: undefined, allowedMode: undefined, defaultMode: subtestParams.selectedDefaultMode, } ], /*isPdf=*/ true); toggleMoreSettings(); const checkbox = getCheckbox('rasterize'); assertFalse((checkbox.parentNode!.parentNode! as HTMLElement).hidden); assertEquals(subtestParams.expectedChecked, checkbox.checked); } }); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { ApiManagementService } 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 { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { ApiManagementServiceResource, ApiManagementServiceListByResourceGroupNextOptionalParams, ApiManagementServiceListByResourceGroupOptionalParams, ApiManagementServiceListNextOptionalParams, ApiManagementServiceListOptionalParams, ApiManagementServiceBackupRestoreParameters, ApiManagementServiceRestoreOptionalParams, ApiManagementServiceRestoreResponse, ApiManagementServiceBackupOptionalParams, ApiManagementServiceBackupResponse, ApiManagementServiceCreateOrUpdateOptionalParams, ApiManagementServiceCreateOrUpdateResponse, ApiManagementServiceUpdateParameters, ApiManagementServiceUpdateOptionalParams, ApiManagementServiceUpdateResponse, ApiManagementServiceGetOptionalParams, ApiManagementServiceGetResponse, ApiManagementServiceDeleteOptionalParams, ApiManagementServiceListByResourceGroupResponse, ApiManagementServiceListResponse, ApiManagementServiceGetSsoTokenOptionalParams, ApiManagementServiceGetSsoTokenResponse, ApiManagementServiceCheckNameAvailabilityParameters, ApiManagementServiceCheckNameAvailabilityOptionalParams, ApiManagementServiceCheckNameAvailabilityResponse, ApiManagementServiceGetDomainOwnershipIdentifierOptionalParams, ApiManagementServiceGetDomainOwnershipIdentifierResponse, ApiManagementServiceApplyNetworkConfigurationUpdatesOptionalParams, ApiManagementServiceApplyNetworkConfigurationUpdatesResponse, ApiManagementServiceListByResourceGroupNextResponse, ApiManagementServiceListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing ApiManagementService operations. */ export class ApiManagementServiceImpl implements ApiManagementService { private readonly client: ApiManagementClient; /** * Initialize a new instance of the class ApiManagementService class. * @param client Reference to the service client */ constructor(client: ApiManagementClient) { this.client = client; } /** * List all API Management services within a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: ApiManagementServiceListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<ApiManagementServiceResource> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: ApiManagementServiceListByResourceGroupOptionalParams ): AsyncIterableIterator<ApiManagementServiceResource[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: ApiManagementServiceListByResourceGroupOptionalParams ): AsyncIterableIterator<ApiManagementServiceResource> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Lists all API Management services within an Azure subscription. * @param options The options parameters. */ public list( options?: ApiManagementServiceListOptionalParams ): PagedAsyncIterableIterator<ApiManagementServiceResource> { const iter = this.listPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(options); } }; } private async *listPagingPage( options?: ApiManagementServiceListOptionalParams ): AsyncIterableIterator<ApiManagementServiceResource[]> { let result = await this._list(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( options?: ApiManagementServiceListOptionalParams ): AsyncIterableIterator<ApiManagementServiceResource> { for await (const page of this.listPagingPage(options)) { yield* page; } } /** * Restores a backup of an API Management service created using the ApiManagementService_Backup * operation on the current service. This is a long running operation and could take several minutes to * complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the Restore API Management service from backup operation. * @param options The options parameters. */ async beginRestore( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceBackupRestoreParameters, options?: ApiManagementServiceRestoreOptionalParams ): Promise< PollerLike< PollOperationState<ApiManagementServiceRestoreResponse>, ApiManagementServiceRestoreResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ApiManagementServiceRestoreResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, parameters, options }, restoreOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Restores a backup of an API Management service created using the ApiManagementService_Backup * operation on the current service. This is a long running operation and could take several minutes to * complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the Restore API Management service from backup operation. * @param options The options parameters. */ async beginRestoreAndWait( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceBackupRestoreParameters, options?: ApiManagementServiceRestoreOptionalParams ): Promise<ApiManagementServiceRestoreResponse> { const poller = await this.beginRestore( resourceGroupName, serviceName, parameters, options ); return poller.pollUntilDone(); } /** * Creates a backup of the API Management service to the given Azure Storage Account. This is long * running operation and could take several minutes to complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the ApiManagementService_Backup operation. * @param options The options parameters. */ async beginBackup( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceBackupRestoreParameters, options?: ApiManagementServiceBackupOptionalParams ): Promise< PollerLike< PollOperationState<ApiManagementServiceBackupResponse>, ApiManagementServiceBackupResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ApiManagementServiceBackupResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, parameters, options }, backupOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Creates a backup of the API Management service to the given Azure Storage Account. This is long * running operation and could take several minutes to complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the ApiManagementService_Backup operation. * @param options The options parameters. */ async beginBackupAndWait( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceBackupRestoreParameters, options?: ApiManagementServiceBackupOptionalParams ): Promise<ApiManagementServiceBackupResponse> { const poller = await this.beginBackup( resourceGroupName, serviceName, parameters, options ); return poller.pollUntilDone(); } /** * Creates or updates an API Management service. This is long running operation and could take several * minutes to complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceResource, options?: ApiManagementServiceCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ApiManagementServiceCreateOrUpdateResponse>, ApiManagementServiceCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ApiManagementServiceCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, parameters, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Creates or updates an API Management service. This is long running operation and could take several * minutes to complete. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceResource, options?: ApiManagementServiceCreateOrUpdateOptionalParams ): Promise<ApiManagementServiceCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, serviceName, parameters, options ); return poller.pollUntilDone(); } /** * Updates an existing API Management service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @param options The options parameters. */ async beginUpdate( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceUpdateParameters, options?: ApiManagementServiceUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ApiManagementServiceUpdateResponse>, ApiManagementServiceUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ApiManagementServiceUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, parameters, options }, updateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Updates an existing API Management service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @param options The options parameters. */ async beginUpdateAndWait( resourceGroupName: string, serviceName: string, parameters: ApiManagementServiceUpdateParameters, options?: ApiManagementServiceUpdateOptionalParams ): Promise<ApiManagementServiceUpdateResponse> { const poller = await this.beginUpdate( resourceGroupName, serviceName, parameters, options ); return poller.pollUntilDone(); } /** * Gets an API Management service resource description. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ get( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceGetOptionalParams ): Promise<ApiManagementServiceGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, options }, getOperationSpec ); } /** * Deletes an existing API Management service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Deletes an existing API Management service. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, serviceName, options ); return poller.pollUntilDone(); } /** * List all API Management services within a resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: ApiManagementServiceListByResourceGroupOptionalParams ): Promise<ApiManagementServiceListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Lists all API Management services within an Azure subscription. * @param options The options parameters. */ private _list( options?: ApiManagementServiceListOptionalParams ): Promise<ApiManagementServiceListResponse> { return this.client.sendOperationRequest({ options }, listOperationSpec); } /** * Gets the Single-Sign-On token for the API Management Service which is valid for 5 Minutes. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ getSsoToken( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceGetSsoTokenOptionalParams ): Promise<ApiManagementServiceGetSsoTokenResponse> { return this.client.sendOperationRequest( { resourceGroupName, serviceName, options }, getSsoTokenOperationSpec ); } /** * Checks availability and correctness of a name for an API Management service. * @param parameters Parameters supplied to the CheckNameAvailability operation. * @param options The options parameters. */ checkNameAvailability( parameters: ApiManagementServiceCheckNameAvailabilityParameters, options?: ApiManagementServiceCheckNameAvailabilityOptionalParams ): Promise<ApiManagementServiceCheckNameAvailabilityResponse> { return this.client.sendOperationRequest( { parameters, options }, checkNameAvailabilityOperationSpec ); } /** * Get the custom domain ownership identifier for an API Management service. * @param options The options parameters. */ getDomainOwnershipIdentifier( options?: ApiManagementServiceGetDomainOwnershipIdentifierOptionalParams ): Promise<ApiManagementServiceGetDomainOwnershipIdentifierResponse> { return this.client.sendOperationRequest( { options }, getDomainOwnershipIdentifierOperationSpec ); } /** * Updates the Microsoft.ApiManagement resource running in the Virtual network to pick the updated DNS * changes. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ async beginApplyNetworkConfigurationUpdates( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceApplyNetworkConfigurationUpdatesOptionalParams ): Promise< PollerLike< PollOperationState< ApiManagementServiceApplyNetworkConfigurationUpdatesResponse >, ApiManagementServiceApplyNetworkConfigurationUpdatesResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ApiManagementServiceApplyNetworkConfigurationUpdatesResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, serviceName, options }, applyNetworkConfigurationUpdatesOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Updates the Microsoft.ApiManagement resource running in the Virtual network to pick the updated DNS * changes. * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param options The options parameters. */ async beginApplyNetworkConfigurationUpdatesAndWait( resourceGroupName: string, serviceName: string, options?: ApiManagementServiceApplyNetworkConfigurationUpdatesOptionalParams ): Promise<ApiManagementServiceApplyNetworkConfigurationUpdatesResponse> { const poller = await this.beginApplyNetworkConfigurationUpdates( resourceGroupName, serviceName, options ); return poller.pollUntilDone(); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: ApiManagementServiceListByResourceGroupNextOptionalParams ): Promise<ApiManagementServiceListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } /** * ListNext * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( nextLink: string, options?: ApiManagementServiceListNextOptionalParams ): Promise<ApiManagementServiceListNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const restoreOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/restore", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceResource }, 201: { bodyMapper: Mappers.ApiManagementServiceResource }, 202: { bodyMapper: Mappers.ApiManagementServiceResource }, 204: { bodyMapper: Mappers.ApiManagementServiceResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters24, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const backupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/backup", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceResource }, 201: { bodyMapper: Mappers.ApiManagementServiceResource }, 202: { bodyMapper: Mappers.ApiManagementServiceResource }, 204: { bodyMapper: Mappers.ApiManagementServiceResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters24, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceResource }, 201: { bodyMapper: Mappers.ApiManagementServiceResource }, 202: { bodyMapper: Mappers.ApiManagementServiceResource }, 204: { bodyMapper: Mappers.ApiManagementServiceResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters25, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceResource }, 201: { bodyMapper: Mappers.ApiManagementServiceResource }, 202: { bodyMapper: Mappers.ApiManagementServiceResource }, 204: { bodyMapper: Mappers.ApiManagementServiceResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters26, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceResource }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.ApiManagement/service", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const getSsoTokenOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/getssotoken", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceGetSsoTokenResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const checkNameAvailabilityOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.ApiManagement/checkNameAvailability", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceNameAvailabilityResult }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters27, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getDomainOwnershipIdentifierOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.ApiManagement/getDomainOwnershipIdentifier", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceGetDomainOwnershipIdentifierResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const applyNetworkConfigurationUpdatesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/applynetworkconfigurationupdates", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceResource }, 201: { bodyMapper: Mappers.ApiManagementServiceResource }, 202: { bodyMapper: Mappers.ApiManagementServiceResource }, 204: { bodyMapper: Mappers.ApiManagementServiceResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters28, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.serviceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ApiManagementServiceListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import log from "../../log"; import type Period from "../period"; import { MANIFEST_UPDATE_TYPE } from "../types"; import updatePeriodInPlace from "../update_period_in_place"; /* eslint-disable @typescript-eslint/no-explicit-any */ const oldVideoRepresentation1 = { contentWarnings: [], id: "rep-video-1", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const oldVideoRepresentation2 = { contentWarnings: [], id: "rep-video-2", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const oldVideoRepresentation3 = { contentWarnings: [], id: "rep-video-3", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const oldVideoRepresentation4 = { contentWarnings: [], id: "rep-video-4", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const oldAudioRepresentation = { contentWarnings: [], id: "rep-audio-1", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const newVideoRepresentation1 = { contentWarnings: [], id: "rep-video-1", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const newVideoRepresentation2 = { contentWarnings: [], id: "rep-video-2", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const newVideoRepresentation3 = { contentWarnings: [], id: "rep-video-3", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const newVideoRepresentation4 = { contentWarnings: [], id: "rep-video-4", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; const newAudioRepresentation = { contentWarnings: [], id: "rep-audio-1", index: { _update() { /* noop */ }, _replace() { /* noop */ } } }; describe("Manifest - updatePeriodInPlace", () => { let oldVideoRepresentation1ReplaceSpy : jest.MockInstance<void, []> | undefined; let oldVideoRepresentation2ReplaceSpy : jest.MockInstance<void, []> | undefined; let oldVideoRepresentation3ReplaceSpy : jest.MockInstance<void, []> | undefined; let oldVideoRepresentation4ReplaceSpy : jest.MockInstance<void, []> | undefined; let oldAudioRepresentationReplaceSpy : jest.MockInstance<void, []> | undefined; let oldVideoRepresentation1UpdateSpy : jest.MockInstance<void, []> | undefined; let oldVideoRepresentation2UpdateSpy : jest.MockInstance<void, []> | undefined; let oldVideoRepresentation3UpdateSpy : jest.MockInstance<void, []> | undefined; let oldVideoRepresentation4UpdateSpy : jest.MockInstance<void, []> | undefined; let oldAudioRepresentationUpdateSpy : jest.MockInstance<void, []> | undefined; let newVideoRepresentation1ReplaceSpy : jest.MockInstance<void, []> | undefined; let newVideoRepresentation2ReplaceSpy : jest.MockInstance<void, []> | undefined; let newVideoRepresentation3ReplaceSpy : jest.MockInstance<void, []> | undefined; let newVideoRepresentation4ReplaceSpy : jest.MockInstance<void, []> | undefined; let newAudioRepresentationReplaceSpy : jest.MockInstance<void, []> | undefined; let newVideoRepresentation1UpdateSpy : jest.MockInstance<void, []> | undefined; let newVideoRepresentation2UpdateSpy : jest.MockInstance<void, []> | undefined; let newVideoRepresentation3UpdateSpy : jest.MockInstance<void, []> | undefined; let newVideoRepresentation4UpdateSpy : jest.MockInstance<void, []> | undefined; let newAudioRepresentationUpdateSpy : jest.MockInstance<void, []> | undefined; beforeEach(() => { oldVideoRepresentation1ReplaceSpy = jest.spyOn(oldVideoRepresentation1.index, "_replace"); oldVideoRepresentation2ReplaceSpy = jest.spyOn(oldVideoRepresentation2.index, "_replace"); oldVideoRepresentation3ReplaceSpy = jest.spyOn(oldVideoRepresentation3.index, "_replace"); oldVideoRepresentation4ReplaceSpy = jest.spyOn(oldVideoRepresentation4.index, "_replace"); oldAudioRepresentationReplaceSpy = jest.spyOn(oldAudioRepresentation.index, "_replace"); oldVideoRepresentation1UpdateSpy = jest.spyOn(oldVideoRepresentation1.index, "_update"); oldVideoRepresentation2UpdateSpy = jest.spyOn(oldVideoRepresentation2.index, "_update"); oldVideoRepresentation3UpdateSpy = jest.spyOn(oldVideoRepresentation3.index, "_update"); oldVideoRepresentation4UpdateSpy = jest.spyOn(oldVideoRepresentation4.index, "_update"); oldAudioRepresentationUpdateSpy = jest.spyOn(oldAudioRepresentation.index, "_update"); newVideoRepresentation1ReplaceSpy = jest.spyOn(newVideoRepresentation1.index, "_replace"); newVideoRepresentation2ReplaceSpy = jest.spyOn(newVideoRepresentation2.index, "_replace"); newVideoRepresentation3ReplaceSpy = jest.spyOn(newVideoRepresentation3.index, "_replace"); newVideoRepresentation4ReplaceSpy = jest.spyOn(newVideoRepresentation4.index, "_replace"); newAudioRepresentationReplaceSpy = jest.spyOn(newAudioRepresentation.index, "_replace"); newVideoRepresentation1UpdateSpy = jest.spyOn(newVideoRepresentation1.index, "_update"); newVideoRepresentation2UpdateSpy = jest.spyOn(newVideoRepresentation2.index, "_update"); newVideoRepresentation3UpdateSpy = jest.spyOn(newVideoRepresentation3.index, "_update"); newVideoRepresentation4UpdateSpy = jest.spyOn(newVideoRepresentation4.index, "_update"); newAudioRepresentationUpdateSpy = jest.spyOn(newAudioRepresentation.index, "_update"); }); afterEach(() => { oldVideoRepresentation1ReplaceSpy?.mockRestore(); oldVideoRepresentation2ReplaceSpy?.mockRestore(); oldVideoRepresentation3ReplaceSpy?.mockRestore(); oldVideoRepresentation4ReplaceSpy?.mockRestore(); oldAudioRepresentationReplaceSpy?.mockRestore(); oldVideoRepresentation1UpdateSpy?.mockRestore(); oldVideoRepresentation2UpdateSpy?.mockRestore(); oldVideoRepresentation3UpdateSpy?.mockRestore(); oldVideoRepresentation4UpdateSpy?.mockRestore(); oldAudioRepresentationUpdateSpy?.mockRestore(); newVideoRepresentation1ReplaceSpy?.mockRestore(); newVideoRepresentation2ReplaceSpy?.mockRestore(); newVideoRepresentation3ReplaceSpy?.mockRestore(); newVideoRepresentation4ReplaceSpy?.mockRestore(); newAudioRepresentationReplaceSpy?.mockRestore(); newVideoRepresentation1UpdateSpy?.mockRestore(); newVideoRepresentation2UpdateSpy?.mockRestore(); newVideoRepresentation3UpdateSpy?.mockRestore(); newVideoRepresentation4UpdateSpy?.mockRestore(); newAudioRepresentationUpdateSpy?.mockRestore(); }); /* eslint-disable max-len */ it("should fully update the first Period given by the second one in a full update", () => { /* eslint-enable max-len */ const oldVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [oldVideoRepresentation1, oldVideoRepresentation2] }; const oldVideoAdaptation2 = { contentWarnings: [], id: "ada-video-2", representations: [oldVideoRepresentation3, oldVideoRepresentation4] }; const oldAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [oldAudioRepresentation] }; const oldPeriod = { contentWarnings: [], start: 5, end: 15, duration: 10, adaptations: { video: [oldVideoAdaptation1, oldVideoAdaptation2], audio: [oldAudioAdaptation] }, getAdaptations() { return [oldVideoAdaptation1, oldVideoAdaptation2, oldAudioAdaptation]; }, }; const newVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [newVideoRepresentation1, newVideoRepresentation2] }; const newVideoAdaptation2 = { contentWarnings: [], id: "ada-video-2", representations: [newVideoRepresentation3, newVideoRepresentation4] }; const newAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [newAudioRepresentation] }; const newPeriod = { contentWarnings: [], start: 500, end: 520, duration: 20, adaptations: { video: [newVideoAdaptation1, newVideoAdaptation2], audio: [newAudioAdaptation] }, getAdaptations() { return [ newVideoAdaptation1, newVideoAdaptation2, newAudioAdaptation ]; }, }; const oldPeriodAdaptationsSpy = jest.spyOn(oldPeriod, "getAdaptations"); const newPeriodAdaptationsSpy = jest.spyOn(newPeriod, "getAdaptations"); const logSpy = jest.spyOn(log, "warn"); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Full); expect(oldPeriod.start).toEqual(500); expect(oldPeriod.end).toEqual(520); expect(oldPeriod.duration).toEqual(20); expect(oldPeriodAdaptationsSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation1ReplaceSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation1ReplaceSpy) .toHaveBeenCalledWith(newVideoRepresentation1.index); expect(oldVideoRepresentation2ReplaceSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation2ReplaceSpy) .toHaveBeenCalledWith(newVideoRepresentation2.index); expect(oldVideoRepresentation3ReplaceSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation3ReplaceSpy) .toHaveBeenCalledWith(newVideoRepresentation3.index); expect(oldVideoRepresentation4ReplaceSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation4ReplaceSpy) .toHaveBeenCalledWith(newVideoRepresentation4.index); expect(oldAudioRepresentationReplaceSpy).toHaveBeenCalledTimes(1); expect(oldAudioRepresentationReplaceSpy) .toHaveBeenCalledWith(newAudioRepresentation.index); expect(newPeriod.start).toEqual(500); expect(newPeriod.end).toEqual(520); expect(newPeriod.duration).toEqual(20); expect(newPeriodAdaptationsSpy).toHaveBeenCalledTimes(1); expect(newVideoRepresentation1ReplaceSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation2ReplaceSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation3ReplaceSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation4ReplaceSpy).not.toHaveBeenCalled(); expect(newAudioRepresentationReplaceSpy).not.toHaveBeenCalled(); expect(oldVideoRepresentation1UpdateSpy).not.toHaveBeenCalled(); expect(oldVideoRepresentation2UpdateSpy).not.toHaveBeenCalled(); expect(oldVideoRepresentation3UpdateSpy).not.toHaveBeenCalled(); expect(oldVideoRepresentation4UpdateSpy).not.toHaveBeenCalled(); expect(oldAudioRepresentationUpdateSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation1UpdateSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation2UpdateSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation3UpdateSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation4UpdateSpy).not.toHaveBeenCalled(); expect(newAudioRepresentationUpdateSpy).not.toHaveBeenCalled(); expect(logSpy).not.toHaveBeenCalled(); logSpy.mockRestore(); }); /* eslint-disable max-len */ it("should partially update the first Period given by the second one in a partial update", () => { /* eslint-enable max-len */ const oldVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [oldVideoRepresentation1, oldVideoRepresentation2] }; const oldVideoAdaptation2 = { contentWarnings: [], id: "ada-video-2", representations: [oldVideoRepresentation3, oldVideoRepresentation4] }; const oldAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [oldAudioRepresentation] }; const oldPeriod = { contentWarnings: [], start: 5, end: 15, duration: 10, adaptations: { video: [oldVideoAdaptation1, oldVideoAdaptation2], audio: [oldAudioAdaptation] }, getAdaptations() { return [oldVideoAdaptation1, oldVideoAdaptation2, oldAudioAdaptation]; }, }; const newVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [newVideoRepresentation1, newVideoRepresentation2] }; const newVideoAdaptation2 = { contentWarnings: [], id: "ada-video-2", representations: [newVideoRepresentation3, newVideoRepresentation4] }; const newAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [newAudioRepresentation] }; const newPeriod = { contentWarnings: [], start: 500, end: 520, duration: 20, adaptations: { video: [newVideoAdaptation1, newVideoAdaptation2], audio: [newAudioAdaptation] }, getAdaptations() { return [ newVideoAdaptation1, newVideoAdaptation2, newAudioAdaptation ]; }, }; const oldPeriodAdaptationsSpy = jest.spyOn(oldPeriod, "getAdaptations"); const newPeriodAdaptationsSpy = jest.spyOn(newPeriod, "getAdaptations"); const logSpy = jest.spyOn(log, "warn"); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Partial); expect(oldPeriod.start).toEqual(500); expect(oldPeriod.end).toEqual(520); expect(oldPeriod.duration).toEqual(20); expect(oldPeriodAdaptationsSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation1UpdateSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation1UpdateSpy) .toHaveBeenCalledWith(newVideoRepresentation1.index); expect(oldVideoRepresentation2UpdateSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation2UpdateSpy) .toHaveBeenCalledWith(newVideoRepresentation2.index); expect(oldVideoRepresentation3UpdateSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation3UpdateSpy) .toHaveBeenCalledWith(newVideoRepresentation3.index); expect(oldVideoRepresentation4UpdateSpy).toHaveBeenCalledTimes(1); expect(oldVideoRepresentation4UpdateSpy) .toHaveBeenCalledWith(newVideoRepresentation4.index); expect(oldAudioRepresentationUpdateSpy).toHaveBeenCalledTimes(1); expect(oldAudioRepresentationUpdateSpy) .toHaveBeenCalledWith(newAudioRepresentation.index); expect(newPeriod.start).toEqual(500); expect(newPeriod.end).toEqual(520); expect(newPeriod.duration).toEqual(20); expect(newPeriodAdaptationsSpy).toHaveBeenCalledTimes(1); expect(newVideoRepresentation1UpdateSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation2UpdateSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation3UpdateSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation4UpdateSpy).not.toHaveBeenCalled(); expect(newAudioRepresentationUpdateSpy).not.toHaveBeenCalled(); expect(oldVideoRepresentation1ReplaceSpy).not.toHaveBeenCalled(); expect(oldVideoRepresentation2ReplaceSpy).not.toHaveBeenCalled(); expect(oldVideoRepresentation3ReplaceSpy).not.toHaveBeenCalled(); expect(oldVideoRepresentation4ReplaceSpy).not.toHaveBeenCalled(); expect(oldAudioRepresentationReplaceSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation1ReplaceSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation2ReplaceSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation3ReplaceSpy).not.toHaveBeenCalled(); expect(newVideoRepresentation4ReplaceSpy).not.toHaveBeenCalled(); expect(newAudioRepresentationReplaceSpy).not.toHaveBeenCalled(); expect(logSpy).not.toHaveBeenCalled(); logSpy.mockRestore(); }); it("should do nothing with new Adaptations", () => { const oldVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [oldVideoRepresentation1, oldVideoRepresentation2] }; const oldAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [oldAudioRepresentation] }; const oldPeriod = { contentWarnings: [], start: 5, end: 15, duration: 10, adaptations: { video: [oldVideoAdaptation1], audio: [oldAudioAdaptation] }, getAdaptations() { return [oldVideoAdaptation1, oldAudioAdaptation]; }, }; const newVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [newVideoRepresentation1, newVideoRepresentation2] }; const newVideoAdaptation2 = { contentWarnings: [], id: "ada-video-2", representations: [newVideoRepresentation3, newVideoRepresentation4] }; const newAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [newAudioRepresentation] }; const newPeriod = { contentWarnings: [], start: 500, end: 520, duration: 20, adaptations: { video: [newVideoAdaptation1, newVideoAdaptation2], audio: [newAudioAdaptation] }, getAdaptations() { return [newVideoAdaptation1, newVideoAdaptation2, newAudioAdaptation]; }, }; const logSpy = jest.spyOn(log, "warn"); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Full); expect(logSpy).not.toHaveBeenCalled(); expect(oldPeriod.adaptations.video).toHaveLength(1); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Partial); expect(logSpy).not.toHaveBeenCalled(); expect(oldPeriod.adaptations.video).toHaveLength(1); logSpy.mockRestore(); }); it("should warn if an old Adaptation is not found", () => { const oldVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [oldVideoRepresentation1, oldVideoRepresentation2] }; const oldVideoAdaptation2 = { contentWarnings: [], id: "ada-video-2", representations: [oldVideoRepresentation3, oldVideoRepresentation4] }; const oldAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [oldAudioRepresentation] }; const oldPeriod = { contentWarnings: [], start: 500, end: 520, duration: 20, adaptations: { video: [oldVideoAdaptation1, oldVideoAdaptation2], audio: [oldAudioAdaptation] }, getAdaptations() { return [oldVideoAdaptation1, oldVideoAdaptation2, oldAudioAdaptation]; }, }; const newVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [newVideoRepresentation1, newVideoRepresentation2] }; const newAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [newAudioRepresentation] }; const newPeriod = { contentWarnings: [], start: 5, end: 15, duration: 10, adaptations: { video: [newVideoAdaptation1], audio: [newAudioAdaptation] }, getAdaptations() { return [newVideoAdaptation1, newAudioAdaptation]; }, }; const logSpy = jest.spyOn(log, "warn"); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Full); expect(logSpy).toHaveBeenCalledTimes(1); expect(logSpy).toHaveBeenCalledWith( "Manifest: Adaptation \"ada-video-2\" not found when merging." ); expect(oldPeriod.adaptations.video).toHaveLength(2); logSpy.mockClear(); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Partial); expect(logSpy).toHaveBeenCalledTimes(1); expect(logSpy).toHaveBeenCalledWith( "Manifest: Adaptation \"ada-video-2\" not found when merging." ); expect(oldPeriod.adaptations.video).toHaveLength(2); logSpy.mockRestore(); }); it("should do nothing with new Representations", () => { const oldVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [oldVideoRepresentation1] }; const oldAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [oldAudioRepresentation] }; const oldPeriod = { contentWarnings: [], start: 5, end: 15, duration: 10, adaptations: { video: [oldVideoAdaptation1], audio: [oldAudioAdaptation] }, getAdaptations() { return [oldVideoAdaptation1, oldAudioAdaptation]; } }; const newVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [newVideoRepresentation1, newVideoRepresentation2] }; const newAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [newAudioRepresentation] }; const newPeriod = { contentWarnings: [], start: 500, end: 520, duration: 20, adaptations: { video: [newVideoAdaptation1], audio: [newAudioAdaptation] }, getAdaptations() { return [newVideoAdaptation1, newAudioAdaptation]; }, }; const logSpy = jest.spyOn(log, "warn"); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Full); expect(logSpy).not.toHaveBeenCalled(); expect(oldVideoAdaptation1.representations).toHaveLength(1); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Partial); expect(logSpy).not.toHaveBeenCalled(); expect(oldVideoAdaptation1.representations).toHaveLength(1); logSpy.mockRestore(); }); it("should warn if an old Representation is not found", () => { const oldVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [oldVideoRepresentation1, oldVideoRepresentation2] }; const oldAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [oldAudioRepresentation] }; const oldPeriod = { contentWarnings: [], start: 500, end: 520, duration: 20, adaptations: { video: [oldVideoAdaptation1], audio: [oldAudioAdaptation] }, getAdaptations() { return [oldVideoAdaptation1, oldAudioAdaptation]; } }; const newVideoAdaptation1 = { contentWarnings: [], id: "ada-video-1", representations: [newVideoRepresentation1] }; const newAudioAdaptation = { contentWarnings: [], id: "ada-audio-1", representations: [newAudioRepresentation] }; const newPeriod = { contentWarnings: [], start: 5, end: 15, duration: 10, adaptations: { video: [newVideoAdaptation1], audio: [newAudioAdaptation], }, getAdaptations() { return [newVideoAdaptation1, newAudioAdaptation]; }, }; const logSpy = jest.spyOn(log, "warn"); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Full); expect(logSpy).toHaveBeenCalledTimes(1); expect(logSpy).toHaveBeenCalledWith( "Manifest: Representation \"rep-video-2\" not found when merging." ); expect(oldVideoAdaptation1.representations).toHaveLength(2); logSpy.mockClear(); updatePeriodInPlace(oldPeriod as unknown as Period, newPeriod as unknown as Period, MANIFEST_UPDATE_TYPE.Partial); expect(logSpy).toHaveBeenCalledTimes(1); expect(logSpy).toHaveBeenCalledWith( "Manifest: Representation \"rep-video-2\" not found when merging." ); expect(oldVideoAdaptation1.representations).toHaveLength(2); logSpy.mockRestore(); }); });
the_stack
import { colors, path, Sha256 } from "./deps.ts"; import { Asset, getAsset, Graph } from "./graph.ts"; import { Logger, logLevels } from "./logger.ts"; import { Bundles, Cache, Chunk, Chunks, Context, DependencyType, History, Item, OutputMap, Plugin, Source, Sources, } from "./plugins/plugin.ts"; import { readTextFile, removeRelativePrefix, size, timestamp, } from "./_util.ts"; import { resolve as resolveCache } from "./cache/cache.ts"; function checkCircularDependency(history: History, dependency: string) { const index = history.indexOf(dependency); if (index > 0) { const deps = [...history.slice(0, index + 1).reverse(), dependency]; console.error( colors.red(`Circular Dependency`), colors.dim(deps.join(` → `)), ); throw new Error(`Circular Dependency`); } } interface Options { importMap?: Deno.ImportMap; sources?: Sources; reload?: boolean | string[]; logger?: Logger; } export interface CreateGraphOptions extends Options { graph?: Graph; outDirPath?: string; outputMap?: OutputMap; } export interface CreateChunkOptions extends Options { chunks?: Chunks; } export interface CreateBundleOptions extends Options { bundles?: Bundles; optimize?: boolean; cache?: Cache; } export interface BundleOptions extends Options { outDirPath?: string; outputMap?: OutputMap; graph?: Graph; chunks?: Chunks; bundles?: Bundles; cache?: Cache; optimize?: boolean; } export class Bundler { plugins: Plugin[]; logger: Logger; constructor( plugins: Plugin[], ) { this.plugins = plugins; this.logger = new Logger({ logLevel: logLevels.info }); } async readSource(item: Item, context: Context): Promise<Source> { const { logger } = context; const input = item.history[0]; const source = context.sources[input]; if (source !== undefined) { return source; } for (const plugin of this.plugins) { if (plugin.readSource && await plugin.test(item, context)) { try { const time = performance.now(); const source = await plugin.readSource(input, context); context.sources[input] = source; logger.debug( colors.cyan("Read Source"), input, colors.dim(plugin.constructor.name), colors.dim(colors.italic(`(${timestamp(time)})`)), ); return source; } catch (error) { if (error instanceof Deno.errors.NotFound) { throw new Error(`file was not found: ${input}`); } throw error; } } } throw new Error(`No readSource plugin found: '${input}'`); } async transformSource( bundleInput: string, item: Item, context: Context, ) { const { logger } = context; const input = item.history[0]; let source = await this.readSource(item, context); for (const plugin of this.plugins) { if (plugin.transformSource && await plugin.test(item, context)) { const time = performance.now(); const newSource = await plugin.transformSource( bundleInput, item, context, ); if (newSource !== undefined) { source = newSource; logger.debug( colors.cyan("Transform Source"), input, colors.dim(plugin.constructor.name), colors.dim(colors.italic(`(${timestamp(time)})`)), ); } } } return source; } async createAsset( item: Item, context: Context, ): Promise<Asset> { const { logger } = context; const time = performance.now(); const input = item.history[0]; for (const plugin of this.plugins) { if (plugin.createAsset && await plugin.test(item, context)) { const asset = await plugin.createAsset(item, context); if (asset !== undefined) { logger.debug( colors.cyan("Create Asset"), input, colors.dim(plugin.constructor.name), colors.dim(colors.italic(`(${timestamp(time)})`)), ); Object.keys(asset.dependencies).forEach( (dependency) => { logger.debug( colors.dim(`→`), colors.dim(dependency), ); }, ); return asset; } } } throw new Error(`No createAsset plugin found: '${input}'`); } async createGraph(inputs: string[], options: CreateGraphOptions = {}) { const time = performance.now(); const outDirPath = "dist"; const context: Context = { importMap: { imports: {}, scopes: {} }, outputMap: {}, reload: false, optimize: false, quiet: false, outDirPath, depsDirPath: path.join(outDirPath, "deps"), cacheDirPath: path.join(outDirPath, ".cache"), sources: {}, cache: {}, graph: {}, chunks: [], bundles: {}, logger: new Logger({ logLevel: this.logger.logLevel, quiet: this.logger.quiet, }), ...options, bundler: this, }; const graph: Graph = {}; const itemList: Item[] = inputs.map(( input, ) => ({ history: [input], type: DependencyType.Import, })); const checkedInputs: Set<string> = new Set(); for (const item of itemList) { const { history, type } = item; const input = removeRelativePrefix(history[0]); if (checkedInputs.has(input)) continue; checkedInputs.add(input); const needsReload = context.reload === true || Array.isArray(context.reload) && context.reload.includes(input); let needsUpdate = needsReload; let asset = context.graph[input]?.find((asset) => asset.type === type); if (!asset) { needsUpdate = true; } else if (!needsReload) { try { if ( Deno.statSync(asset.input).mtime! > Deno.statSync(asset.output).mtime! ) { needsUpdate = true; } } catch (error) { if (error instanceof Deno.errors.NotFound) { needsUpdate = true; } else { throw error; } } } if (needsUpdate) { asset = await this.createAsset(item, context); } if (!asset) { throw new Error( `asset not found: ${input} ${DependencyType[item.type]}`, ); } const entry = graph[input] ||= []; entry.push(asset); Object.entries(asset.dependencies).forEach( ([dependency, types]) => { Object.keys(types).forEach((type) => { checkCircularDependency(history, dependency); itemList.push({ history: [dependency, ...history], type: type as DependencyType, }); }); }, ); } const length = Object.keys(checkedInputs).length; context.logger.info( colors.green("Create"), "Graph", colors.dim( `${length} file${length === 1 ? "" : "s"}`, ), colors.dim(colors.italic(`(${timestamp(time)})`)), ); Object.entries(graph).forEach(([input, types]) => { Object.values(types).forEach((asset) => { const { type, dependencies } = asset!; context.logger.debug( colors.dim(`➞`), colors.dim(input), colors.dim(`{ ${DependencyType[type]} }`), ); Object.keys(dependencies).forEach((dependency) => { context.logger.debug( colors.dim(` ➞`), colors.dim(dependency), colors.dim(`{ ${DependencyType[type]} }`), ); }); }); }); return graph; } async createChunk( item: Item, context: Context, chunkList: Item[], ) { const { logger } = context; const time = performance.now(); for (const plugin of this.plugins) { if (plugin.createChunk && await plugin.test(item, context)) { const chunk = await plugin.createChunk( item, context, chunkList, ); if (chunk !== undefined) { const { history } = item; const input = history[0]; logger.debug( colors.cyan("Create Chunk"), input, colors.dim(plugin.constructor.name), colors.dim(colors.italic(`(${timestamp(time)})`)), ); chunk.dependencyItems.forEach((dependencyItem) => { const { history, type } = dependencyItem; const input = history[0]; logger.debug( colors.dim(`➞`), colors.dim(input), colors.dim( `{ ${DependencyType[type]} }`, ), ); }); return chunk; } } } const input = item.history[0]; throw new Error(`No createChunk plugin found: '${input}'`); } async createChunks( inputs: string[], graph: Graph, options: CreateChunkOptions = {}, ) { const time = performance.now(); const context: Context = { importMap: { imports: {} }, outputMap: {}, reload: false, optimize: false, quiet: false, outDirPath: "dist", depsDirPath: "dist/deps", cacheDirPath: "dist/.cache", sources: {}, cache: {}, chunks: [], bundles: {}, logger: new Logger({ logLevel: this.logger.logLevel, quiet: this.logger.quiet, }), ...options, graph, bundler: this, }; const chunkList: Item[] = inputs.map((input) => { return { history: [input], type: DependencyType.Import, }; }); const { chunks } = context; const checkedChunks: Partial< Record<DependencyType, Record<string, Chunk>> > = {}; const allItems: Record<string, Set<DependencyType>> = {}; for (const item of chunkList) { const { history, type } = item; const input = history[0]; if (checkedChunks[type]?.[input]) continue; const chunk = await this.createChunk(item, context, chunkList); checkedChunks[type] ||= {}; checkedChunks[type]![input] = chunk; chunks.push(chunk); await this.splitChunk(chunk, context, chunkList, allItems); } const length = chunks.length; context.logger.info( colors.green("Create"), "Chunks", colors.dim(`${length} file${length === 1 ? "" : "s"}`), colors.dim(colors.italic(`(${timestamp(time)})`)), ); return chunks; } private async splitChunk( chunk: Chunk, context: Context, chunkList: Item[], allItems: Record<string, Set<DependencyType>>, ) { const { logger, chunks } = context; logger.debug(colors.cyan("Split Chunk"), chunk.item.history[0]); const checked: Record<string, Set<DependencyType>> = {}; // cache outside loop for faster chunk splits const items = [...chunk.dependencyItems]; function addItem(input: string, type: DependencyType) { (allItems[input] ||= new Set()).add(type); } function hasItem(input: string, type: DependencyType) { return allItems[input]?.has(type); } function addChunkItems({ item, dependencyItems }: Chunk) { addItem(item.history[0], item.type); dependencyItems.forEach((item) => addItem(item.history[0], item.type)); } chunks.forEach((c) => { if (c === chunk) return; addChunkItems(c); }); for (const item of items) { const { history, type } = item; const input = history[0]; if ( chunks.some(({ item }) => item.history[0] === input && item.type === type ) ) { continue; } const newChunk = await this.createChunk(item, { ...context, logger: new Logger({ logLevel: logger.logLevel, quiet: true, }), }, chunkList); if (hasItem(input, type)) { logger.debug(colors.dim("→"), colors.yellow("Split"), input); chunks.push(newChunk); items.push(...newChunk.dependencyItems); } else { logger.debug( colors.dim("→"), colors.dim("Check"), colors.dim(input), ); (checked[input] ||= new Set()).add(type); addChunkItems(newChunk); } } } async createBundle( chunk: Chunk, context: Context, ) { const { logger } = context; const item = chunk.item; const { history, type } = item; const input = history[0]; const time = performance.now(); for (const plugin of this.plugins) { if (plugin.createBundle && await plugin.test(item, context)) { const bundle = await plugin.createBundle(chunk, context) as string; const asset = getAsset(context.graph, input, type); if (bundle !== undefined) { const length = bundle.length; logger.info( colors.green("Create"), "Bundle", input, colors.dim(size(length)), colors.dim(colors.italic(`(${timestamp(time)})`)), ); logger.debug( colors.dim(`➞`), colors.dim(asset.output), ); return bundle; } else { // if bundle is up-to-date logger.info( colors.green("Check"), "Bundle", input, colors.dim(colors.italic(`(${timestamp(time)})`)), ); // logger.debug( // colors.dim(`➞`), // colors.dim(asset.output), // ); // exit return; } } } throw new Error(`No createBundle plugin found: '${input}'`); } async optimizeBundle(chunk: Chunk, context: Context) { const { logger } = context; const item = chunk.item; const { type, history } = item; const input = history[0]; const asset = getAsset(context.graph, input, type); const { output } = asset; let bundle = context.bundles[output]; for (const plugin of this.plugins) { if (plugin.optimizeBundle && await plugin.test(item, context)) { const time = performance.now(); bundle = await plugin.optimizeBundle(output, context); logger.debug( "Optimize Bundle", input, colors.dim(`➞`), colors.dim((asset.output)), colors.dim(plugin.constructor.name), colors.dim(colors.italic(`(${timestamp(time)})`)), ); } } return bundle; } async createBundles( chunks: Chunks, graph: Graph, options: CreateBundleOptions = {}, ) { const context: Context = { importMap: { imports: {} }, outputMap: {}, reload: false, quiet: false, optimize: false, outDirPath: "dist", depsDirPath: "dist/deps", cacheDirPath: "dist/.cache", bundles: {}, sources: {}, cache: {}, logger: new Logger({ logLevel: this.logger.logLevel, quiet: this.logger.quiet, }), ...options, graph, chunks, bundler: this, }; const bundles = context.bundles; for (const chunk of context.chunks) { const bundle = await this.createBundle(chunk, context); if (bundle !== undefined) { const item = chunk.item; const { history, type } = item; const input = history[0]; const chunkAsset = getAsset(graph, input, type); const output = chunkAsset.output; bundles[output] = bundle; if (context.optimize) { bundles[output] = await this.optimizeBundle(chunk, context); } } } return bundles; } async bundle(inputs: string[], options: BundleOptions = {}) { const time = performance.now(); const cache: Cache = {}; options = { sources: {}, // will be shared between createGraph, createChunks and createBundles cache: {}, // will be shared between createGraph, createChunks and createBundle ...options, }; inputs = [...new Set(inputs)]; inputs.forEach((input) => { this.logger.info(colors.brightBlue("Entry"), input); }); const graph = await this.createGraph( inputs, { ...options }, ); const chunks = await this.createChunks( inputs, graph, { ...options }, ); const bundles = await this.createBundles( chunks, graph, { ...options, cache }, ); const length = Object.keys(bundles).length; this.logger.info( colors.brightBlue("Bundle"), colors.dim( length ? `${length} file${length === 1 ? "" : "s"}` : `up-to-date`, ), colors.dim(colors.italic(`(${timestamp(time)})`)), ); return { cache, graph, chunks, bundles }; } private createCacheFilePath( bundleInput: string, input: string, cacheDirPath: string, ) { const bundleCacheDirPath = new Sha256().update(bundleInput).hex(); const filePath = resolveCache(input); const cacheFilePath = new Sha256().update(filePath).hex(); return path.join( cacheDirPath, bundleCacheDirPath, cacheFilePath, ); } /** * returns true if an entry exists in `context.cache` or cacheFile `mtime` is bigger than sourceFile `mtime` */ hasCache(bundleInput: string, input: string, context: Context) { const { cacheDirPath, cache } = context; const filePath = resolveCache(input); const cacheFilePath = this.createCacheFilePath( bundleInput, input, cacheDirPath, ); try { return cache[cacheFilePath] !== undefined || Deno.statSync(cacheFilePath).mtime! > Deno.statSync(filePath).mtime!; } catch (error) { if (error instanceof Deno.errors.NotFound) { return false; } throw error; } } setCache( bundleInput: string, input: string, source: string, context: Context, ) { const { logger } = context; const { cacheDirPath, cache } = context; const cacheFilePath = this.createCacheFilePath( bundleInput, input, cacheDirPath, ); logger.trace( "Cache", input, ); logger.debug(colors.dim(`➞`), colors.dim(cacheFilePath)); cache[cacheFilePath] = source; } async getCache(bundleInput: string, input: string, context: Context) { const { logger } = context; const time = performance.now(); const { cacheDirPath, cache } = context; const cacheFilePath = this.createCacheFilePath( bundleInput, input, cacheDirPath, ); if (cache[cacheFilePath]) return cache[cacheFilePath]; const source = await readTextFile(cacheFilePath); logger.trace( "Read Cache", input, colors.dim(cacheFilePath), colors.dim(colors.italic(`(${timestamp(time)})`)), ); return source; } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [iot](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Iot extends PolicyStatement { public servicePrefix = 'iot'; /** * Statement provider for service [iot](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.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 accept a pending certificate transfer * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_AcceptCertificateTransfer.html */ public toAcceptCertificateTransfer() { return this.to('AcceptCertificateTransfer'); } /** * Grants permission to add a thing to the specified billing group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_AddThingToBillingGroup.html */ public toAddThingToBillingGroup() { return this.to('AddThingToBillingGroup'); } /** * Grants permission to add a thing to the specified thing group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_AddThingToThingGroup.html */ public toAddThingToThingGroup() { return this.to('AddThingToThingGroup'); } /** * Grants permission to associate a group with a continuous job * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_AssociateTargetsWithJob.html */ public toAssociateTargetsWithJob() { return this.to('AssociateTargetsWithJob'); } /** * Grants permission to attach a policy to the specified target * * Access Level: Permissions management * * https://docs.aws.amazon.com/iot/latest/apireference/API_AttachPolicy.html */ public toAttachPolicy() { return this.to('AttachPolicy'); } /** * Grants permission to attach the specified policy to the specified principal (certificate or other credential) * * Access Level: Permissions management * * https://docs.aws.amazon.com/iot/latest/apireference/API_AttachPrincipalPolicy.html */ public toAttachPrincipalPolicy() { return this.to('AttachPrincipalPolicy'); } /** * Grants permission to associate a Device Defender security profile with a thing group or with this account * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_AttachSecurityProfile.html */ public toAttachSecurityProfile() { return this.to('AttachSecurityProfile'); } /** * Grants permission to attach the specified principal to the specified thing * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_AttachThingPrincipal.html */ public toAttachThingPrincipal() { return this.to('AttachThingPrincipal'); } /** * Grants permission to cancel a mitigation action task that is in progress * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CancelAuditMitigationActionsTask.html */ public toCancelAuditMitigationActionsTask() { return this.to('CancelAuditMitigationActionsTask'); } /** * Grants permission to cancel an audit that is in progress. The audit can be either scheduled or on-demand * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CancelAuditTask.html */ public toCancelAuditTask() { return this.to('CancelAuditTask'); } /** * Grants permission to cancel a pending transfer for the specified certificate * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CancelCertificateTransfer.html */ public toCancelCertificateTransfer() { return this.to('CancelCertificateTransfer'); } /** * Grants permission to cancel a Device Defender ML Detect mitigation action * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CancelDetectMitigationActionsTask.html */ public toCancelDetectMitigationActionsTask() { return this.to('CancelDetectMitigationActionsTask'); } /** * Grants permission to cancel a job * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CancelJob.html */ public toCancelJob() { return this.to('CancelJob'); } /** * Grants permission to cancel a job execution on a particular device * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CancelJobExecution.html */ public toCancelJobExecution() { return this.to('CancelJobExecution'); } /** * Grants permission to clear the default authorizer * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_ClearDefaultAuthorizer.html */ public toClearDefaultAuthorizer() { return this.to('ClearDefaultAuthorizer'); } /** * Grants permission to close a tunnel * * Access Level: Write * * Possible conditions: * - .ifDelete() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CloseTunnel.html */ public toCloseTunnel() { return this.to('CloseTunnel'); } /** * Grants permission to confirm a http url TopicRuleDestinationDestination * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_ConfirmTopicRuleDestination.html */ public toConfirmTopicRuleDestination() { return this.to('ConfirmTopicRuleDestination'); } /** * Grants permission to connect as the specified client * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toConnect() { return this.to('Connect'); } /** * Grants permission to create a Device Defender audit suppression * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateAuditSuppression.html */ public toCreateAuditSuppression() { return this.to('CreateAuditSuppression'); } /** * Grants permission to create an authorizer * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateAuthorizer.html */ public toCreateAuthorizer() { return this.to('CreateAuthorizer'); } /** * Grants permission to create a billing group * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateBillingGroup.html */ public toCreateBillingGroup() { return this.to('CreateBillingGroup'); } /** * Grants permission to create an X.509 certificate using the specified certificate signing request * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateCertificateFromCsr.html */ public toCreateCertificateFromCsr() { return this.to('CreateCertificateFromCsr'); } /** * Grants permission to create a custom metric for device side metric reporting and monitoring * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateCustomMetric.html */ public toCreateCustomMetric() { return this.to('CreateCustomMetric'); } /** * Grants permission to define a dimension that can be used to to limit the scope of a metric used in a security profile * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateDimension.html */ public toCreateDimension() { return this.to('CreateDimension'); } /** * Grants permission to create a domain configuration * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifDomainName() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateDomainConfiguration.html */ public toCreateDomainConfiguration() { return this.to('CreateDomainConfiguration'); } /** * Grants permission to create a Dynamic Thing Group * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateDynamicThingGroup.html */ public toCreateDynamicThingGroup() { return this.to('CreateDynamicThingGroup'); } /** * Grants permission to create a fleet metric * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/iot-indexing.html */ public toCreateFleetMetric() { return this.to('CreateFleetMetric'); } /** * Grants permission to create a job * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateJob.html */ public toCreateJob() { return this.to('CreateJob'); } /** * Grants permission to create a job template * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateJobTemplate.html */ public toCreateJobTemplate() { return this.to('CreateJobTemplate'); } /** * Grants permission to create a 2048 bit RSA key pair and issues an X.509 certificate using the issued public key * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateKeysAndCertificate.html */ public toCreateKeysAndCertificate() { return this.to('CreateKeysAndCertificate'); } /** * Grants permission to define an action that can be applied to audit findings by using StartAuditMitigationActionsTask * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateMitigationAction.html */ public toCreateMitigationAction() { return this.to('CreateMitigationAction'); } /** * Grants permission to create an OTA update job * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateOTAUpdate.html */ public toCreateOTAUpdate() { return this.to('CreateOTAUpdate'); } /** * Grants permission to create an AWS IoT policy * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreatePolicy.html */ public toCreatePolicy() { return this.to('CreatePolicy'); } /** * Grants permission to create a new version of the specified AWS IoT policy * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreatePolicyVersion.html */ public toCreatePolicyVersion() { return this.to('CreatePolicyVersion'); } /** * Grants permission to create a provisioning claim * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateProvisioningClaim.html */ public toCreateProvisioningClaim() { return this.to('CreateProvisioningClaim'); } /** * Grants permission to create a fleet provisioning template * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateProvisioningTemplate.html */ public toCreateProvisioningTemplate() { return this.to('CreateProvisioningTemplate'); } /** * Grants permission to create a new version of a fleet provisioning template * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateProvisioningTemplateVersion.html */ public toCreateProvisioningTemplateVersion() { return this.to('CreateProvisioningTemplateVersion'); } /** * Grants permission to create a role alias * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateRoleAlias.html */ public toCreateRoleAlias() { return this.to('CreateRoleAlias'); } /** * Grants permission to create a scheduled audit that is run at a specified time interval * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateScheduledAudit.html */ public toCreateScheduledAudit() { return this.to('CreateScheduledAudit'); } /** * Grants permission to create a Device Defender security profile * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateSecurityProfile.html */ public toCreateSecurityProfile() { return this.to('CreateSecurityProfile'); } /** * Grants permission to create a new AWS IoT stream * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateStream.html */ public toCreateStream() { return this.to('CreateStream'); } /** * Grants permission to create a thing in the thing registry * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateThing.html */ public toCreateThing() { return this.to('CreateThing'); } /** * Grants permission to create a thing group * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateThingGroup.html */ public toCreateThingGroup() { return this.to('CreateThingGroup'); } /** * Grants permission to create a new thing type * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateThingType.html */ public toCreateThingType() { return this.to('CreateThingType'); } /** * Grants permission to create a rule * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateTopicRule.html */ public toCreateTopicRule() { return this.to('CreateTopicRule'); } /** * Grants permission to create a TopicRuleDestination * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_CreateTopicRuleDestination.html */ public toCreateTopicRuleDestination() { return this.to('CreateTopicRuleDestination'); } /** * Grants permission to delete the audit configuration associated with the account * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteAccountAuditConfiguration.html */ public toDeleteAccountAuditConfiguration() { return this.to('DeleteAccountAuditConfiguration'); } /** * Grants permission to delete a Device Defender audit suppression * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteAuditSuppression.html */ public toDeleteAuditSuppression() { return this.to('DeleteAuditSuppression'); } /** * Grants permission to delete the specified authorizer * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteAuthorizer.html */ public toDeleteAuthorizer() { return this.to('DeleteAuthorizer'); } /** * Grants permission to delete the specified billing group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteBillingGroup.html */ public toDeleteBillingGroup() { return this.to('DeleteBillingGroup'); } /** * Grants permission to delete a registered CA certificate * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteCACertificate.html */ public toDeleteCACertificate() { return this.to('DeleteCACertificate'); } /** * Grants permission to delete the specified certificate * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteCertificate.html */ public toDeleteCertificate() { return this.to('DeleteCertificate'); } /** * Grants permission to deletes the specified custom metric from your AWS account * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteCustomMetric.html */ public toDeleteCustomMetric() { return this.to('DeleteCustomMetric'); } /** * Grants permission to remove the specified dimension from your AWS account * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteDimension.html */ public toDeleteDimension() { return this.to('DeleteDimension'); } /** * Grants permission to delete a domain configuration * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteDomainConfiguration.html */ public toDeleteDomainConfiguration() { return this.to('DeleteDomainConfiguration'); } /** * Grants permission to delete the specified Dynamic Thing Group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteDynamicThingGroup.html */ public toDeleteDynamicThingGroup() { return this.to('DeleteDynamicThingGroup'); } /** * Grants permission to delete the specified fleet metric * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/iot-indexing.html */ public toDeleteFleetMetric() { return this.to('DeleteFleetMetric'); } /** * Grants permission to delete a job and its related job executions * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteJob.html */ public toDeleteJob() { return this.to('DeleteJob'); } /** * Grants permission to delete a job execution * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteJobExecution.html */ public toDeleteJobExecution() { return this.to('DeleteJobExecution'); } /** * Grants permission to delete a job template * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteJobTemplate.html */ public toDeleteJobTemplate() { return this.to('DeleteJobTemplate'); } /** * Grants permission to delete a defined mitigation action from your AWS account * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteMitigationAction.html */ public toDeleteMitigationAction() { return this.to('DeleteMitigationAction'); } /** * Grants permission to delete an OTA update job * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteOTAUpdate.html */ public toDeleteOTAUpdate() { return this.to('DeleteOTAUpdate'); } /** * Grants permission to delete the specified policy * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeletePolicy.html */ public toDeletePolicy() { return this.to('DeletePolicy'); } /** * Grants permission to Delete the specified version of the specified policy * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeletePolicyVersion.html */ public toDeletePolicyVersion() { return this.to('DeletePolicyVersion'); } /** * Grants permission to delete a fleet provisioning template * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteProvisioningTemplate.html */ public toDeleteProvisioningTemplate() { return this.to('DeleteProvisioningTemplate'); } /** * Grants permission to delete a fleet provisioning template version * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteProvisioningTemplateVersion.html */ public toDeleteProvisioningTemplateVersion() { return this.to('DeleteProvisioningTemplateVersion'); } /** * Grants permission to delete a CA certificate registration code * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteRegistrationCode.html */ public toDeleteRegistrationCode() { return this.to('DeleteRegistrationCode'); } /** * Grants permission to delete the specified role alias * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteRoleAlias.html */ public toDeleteRoleAlias() { return this.to('DeleteRoleAlias'); } /** * Grants permission to delete a scheduled audit * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteScheduledAudit.html */ public toDeleteScheduledAudit() { return this.to('DeleteScheduledAudit'); } /** * Grants permission to delete a Device Defender security profile * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteSecurityProfile.html */ public toDeleteSecurityProfile() { return this.to('DeleteSecurityProfile'); } /** * Grants permission to delete a specified stream * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteStream.html */ public toDeleteStream() { return this.to('DeleteStream'); } /** * Grants permission to delete the specified thing * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteThing.html */ public toDeleteThing() { return this.to('DeleteThing'); } /** * Grants permission to delete the specified thing group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteThingGroup.html */ public toDeleteThingGroup() { return this.to('DeleteThingGroup'); } /** * Grants permission to delete the specified thing shadow * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toDeleteThingShadow() { return this.to('DeleteThingShadow'); } /** * Grants permission to delete the specified thing type * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteThingType.html */ public toDeleteThingType() { return this.to('DeleteThingType'); } /** * Grants permission to delete the specified rule * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteTopicRule.html */ public toDeleteTopicRule() { return this.to('DeleteTopicRule'); } /** * Grants permission to delete a TopicRuleDestination * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteTopicRuleDestination.html */ public toDeleteTopicRuleDestination() { return this.to('DeleteTopicRuleDestination'); } /** * Grants permission to delete the specified v2 logging level * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteV2LoggingLevel.html */ public toDeleteV2LoggingLevel() { return this.to('DeleteV2LoggingLevel'); } /** * Grants permission to deprecate the specified thing type * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DeprecateThingType.html */ public toDeprecateThingType() { return this.to('DeprecateThingType'); } /** * Grants permission to get information about audit configurations for the account * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAccountAuditConfiguration.html */ public toDescribeAccountAuditConfiguration() { return this.to('DescribeAccountAuditConfiguration'); } /** * Grants permission to get information about a single audit finding. Properties include the reason for noncompliance, the severity of the issue, and when the audit that returned the finding was started * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuditFinding.html */ public toDescribeAuditFinding() { return this.to('DescribeAuditFinding'); } /** * Grants permission to get information about an audit mitigation task that is used to apply mitigation actions to a set of audit findings * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuditMitigationActionsTask.html */ public toDescribeAuditMitigationActionsTask() { return this.to('DescribeAuditMitigationActionsTask'); } /** * Grants permission to get information about a Device Defender audit suppression * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuditSuppression.html */ public toDescribeAuditSuppression() { return this.to('DescribeAuditSuppression'); } /** * Grants permission to get information about a Device Defender audit * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuditTask.html */ public toDescribeAuditTask() { return this.to('DescribeAuditTask'); } /** * Grants permission to describe an authorizer * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuthorizer.html */ public toDescribeAuthorizer() { return this.to('DescribeAuthorizer'); } /** * Grants permission to get information about the specified billing group * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeBillingGroup.html */ public toDescribeBillingGroup() { return this.to('DescribeBillingGroup'); } /** * Grants permission to describe a registered CA certificate * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeCACertificate.html */ public toDescribeCACertificate() { return this.to('DescribeCACertificate'); } /** * Grants permission to get information about the specified certificate * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeCertificate.html */ public toDescribeCertificate() { return this.to('DescribeCertificate'); } /** * Grants permission to describe a custom metric that is defined in your AWS account * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeCustomMetric.html */ public toDescribeCustomMetric() { return this.to('DescribeCustomMetric'); } /** * Grants permission to describe the default authorizer * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeDefaultAuthorizer.html */ public toDescribeDefaultAuthorizer() { return this.to('DescribeDefaultAuthorizer'); } /** * Grants permission to describe a Device Defender ML Detect mitigation action * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeDetectMitigationActionsTask.html */ public toDescribeDetectMitigationActionsTask() { return this.to('DescribeDetectMitigationActionsTask'); } /** * Grants permission to get details about a dimension that is defined in your AWS account * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeDimension.html */ public toDescribeDimension() { return this.to('DescribeDimension'); } /** * Grants permission to get information about the domain configuration * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeDomainConfiguration.html */ public toDescribeDomainConfiguration() { return this.to('DescribeDomainConfiguration'); } /** * Grants permission to get a unique endpoint specific to the AWS account making the call * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeEndpoint.html */ public toDescribeEndpoint() { return this.to('DescribeEndpoint'); } /** * Grants permission to get account event configurations * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeEventConfigurations.html */ public toDescribeEventConfigurations() { return this.to('DescribeEventConfigurations'); } /** * Grants permission to get information about the specified fleet metric * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/iot-indexing.html */ public toDescribeFleetMetric() { return this.to('DescribeFleetMetric'); } /** * Grants permission to get information about the specified index * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeIndex.html */ public toDescribeIndex() { return this.to('DescribeIndex'); } /** * Grants permission to describe a job * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeJob.html */ public toDescribeJob() { return this.to('DescribeJob'); } /** * Grants permission to describe a job execution * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeJobExecution.html */ public toDescribeJobExecution() { return this.to('DescribeJobExecution'); } /** * Grants permission to describe a job template * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeJobTemplate.html */ public toDescribeJobTemplate() { return this.to('DescribeJobTemplate'); } /** * Grants permission to get information about a mitigation action * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeMitigationAction.html */ public toDescribeMitigationAction() { return this.to('DescribeMitigationAction'); } /** * Grants permission to get information about a fleet provisioning template * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeProvisioningTemplate.html */ public toDescribeProvisioningTemplate() { return this.to('DescribeProvisioningTemplate'); } /** * Grants permission to get information about a fleet provisioning template version * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeProvisioningTemplateVersion.html */ public toDescribeProvisioningTemplateVersion() { return this.to('DescribeProvisioningTemplateVersion'); } /** * Grants permission to describe a role alias * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeRoleAlias.html */ public toDescribeRoleAlias() { return this.to('DescribeRoleAlias'); } /** * Grants permission to get information about a scheduled audit * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeScheduledAudit.html */ public toDescribeScheduledAudit() { return this.to('DescribeScheduledAudit'); } /** * Grants permission to get information about a Device Defender security profile * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeSecurityProfile.html */ public toDescribeSecurityProfile() { return this.to('DescribeSecurityProfile'); } /** * Grants permission to get information about the specified stream * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeStream.html */ public toDescribeStream() { return this.to('DescribeStream'); } /** * Grants permission to get information about the specified thing * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeThing.html */ public toDescribeThing() { return this.to('DescribeThing'); } /** * Grants permission to get information about the specified thing group * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeThingGroup.html */ public toDescribeThingGroup() { return this.to('DescribeThingGroup'); } /** * Grants permission to get information about the bulk thing registration task * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeThingRegistrationTask.html */ public toDescribeThingRegistrationTask() { return this.to('DescribeThingRegistrationTask'); } /** * Grants permission to get information about the specified thing type * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeThingType.html */ public toDescribeThingType() { return this.to('DescribeThingType'); } /** * Grants permission to describe a tunnel * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeTunnel.html */ public toDescribeTunnel() { return this.to('DescribeTunnel'); } /** * Grants permission to detach a policy from the specified target * * Access Level: Permissions management * * https://docs.aws.amazon.com/iot/latest/apireference/API_DetachPolicy.html */ public toDetachPolicy() { return this.to('DetachPolicy'); } /** * Grants permission to remove the specified policy from the specified certificate * * Access Level: Permissions management * * https://docs.aws.amazon.com/iot/latest/apireference/API_DetachPrincipalPolicy.html */ public toDetachPrincipalPolicy() { return this.to('DetachPrincipalPolicy'); } /** * Grants permission to disassociate a Device Defender security profile from a thing group or from this account * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DetachSecurityProfile.html */ public toDetachSecurityProfile() { return this.to('DetachSecurityProfile'); } /** * Grants permission to detach the specified principal from the specified thing * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DetachThingPrincipal.html */ public toDetachThingPrincipal() { return this.to('DetachThingPrincipal'); } /** * Grants permission to disable the specified rule * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_DisableTopicRule.html */ public toDisableTopicRule() { return this.to('DisableTopicRule'); } /** * Grants permission to enable the specified rule * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_EnableTopicRule.html */ public toEnableTopicRule() { return this.to('EnableTopicRule'); } /** * Grants permission to fetch a Device Defender's ML Detect Security Profile training model's status * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetBehaviorModelTrainingSummaries.html */ public toGetBehaviorModelTrainingSummaries() { return this.to('GetBehaviorModelTrainingSummaries'); } /** * Grants permission to get buckets aggregation for IoT fleet index * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/iot-indexing.html */ public toGetBucketsAggregation() { return this.to('GetBucketsAggregation'); } /** * Grants permission to get cardinality for IoT fleet index * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetCardinality.html */ public toGetCardinality() { return this.to('GetCardinality'); } /** * Grants permission to get effective policies * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetEffectivePolicies.html */ public toGetEffectivePolicies() { return this.to('GetEffectivePolicies'); } /** * Grants permission to get current fleet indexing configuration * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetIndexingConfiguration.html */ public toGetIndexingConfiguration() { return this.to('GetIndexingConfiguration'); } /** * Grants permission to get a job document * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetJobDocument.html */ public toGetJobDocument() { return this.to('GetJobDocument'); } /** * Grants permission to get the logging options * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetLoggingOptions.html */ public toGetLoggingOptions() { return this.to('GetLoggingOptions'); } /** * Grants permission to get the information about the OTA update job * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetOTAUpdate.html */ public toGetOTAUpdate() { return this.to('GetOTAUpdate'); } /** * Grants permission to get the list of all jobs for a thing that are not in a terminal state * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetPendingJobExecutions.html */ public toGetPendingJobExecutions() { return this.to('GetPendingJobExecutions'); } /** * Grants permission to get percentiles for IoT fleet index * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetPercentiles.html */ public toGetPercentiles() { return this.to('GetPercentiles'); } /** * Grants permission to get information about the specified policy with the policy document of the default version * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetPolicy.html */ public toGetPolicy() { return this.to('GetPolicy'); } /** * Grants permission to get information about the specified policy version * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetPolicyVersion.html */ public toGetPolicyVersion() { return this.to('GetPolicyVersion'); } /** * Grants permission to get a registration code used to register a CA certificate with AWS IoT * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetRegistrationCode.html */ public toGetRegistrationCode() { return this.to('GetRegistrationCode'); } /** * Grants permission to get the retained message on the specified topic * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toGetRetainedMessage() { return this.to('GetRetainedMessage'); } /** * Grants permission to get statistics for IoT fleet index * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetStatistics.html */ public toGetStatistics() { return this.to('GetStatistics'); } /** * Grants permission to get the thing shadow * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toGetThingShadow() { return this.to('GetThingShadow'); } /** * Grants permission to get information about the specified rule * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetTopicRule.html */ public toGetTopicRule() { return this.to('GetTopicRule'); } /** * Grants permission to get a TopicRuleDestination * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetTopicRuleDestination.html */ public toGetTopicRuleDestination() { return this.to('GetTopicRuleDestination'); } /** * Grants permission to get v2 logging options * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_GetV2LoggingOptions.html */ public toGetV2LoggingOptions() { return this.to('GetV2LoggingOptions'); } /** * Grants permission to list the active violations for a given Device Defender security profile or Thing * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListActiveViolations.html */ public toListActiveViolations() { return this.to('ListActiveViolations'); } /** * Grants permission to list the policies attached to the specified thing group * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListAttachedPolicies.html */ public toListAttachedPolicies() { return this.to('ListAttachedPolicies'); } /** * Grants permission to list the findings (results) of a Device Defender audit or of the audits performed during a specified time period * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuditFindings.html */ public toListAuditFindings() { return this.to('ListAuditFindings'); } /** * Grants permission to get the status of audit mitigation action tasks that were executed * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuditMitigationActionsExecutions.html */ public toListAuditMitigationActionsExecutions() { return this.to('ListAuditMitigationActionsExecutions'); } /** * Grants permission to get a list of audit mitigation action tasks that match the specified filters * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuditMitigationActionsTasks.html */ public toListAuditMitigationActionsTasks() { return this.to('ListAuditMitigationActionsTasks'); } /** * Grants permission to list your Device Defender audit suppressions * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuditSuppressions.html */ public toListAuditSuppressions() { return this.to('ListAuditSuppressions'); } /** * Grants permission to list the Device Defender audits that have been performed during a given time period * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuditTasks.html */ public toListAuditTasks() { return this.to('ListAuditTasks'); } /** * Grants permission to list the authorizers registered in your account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuthorizers.html */ public toListAuthorizers() { return this.to('ListAuthorizers'); } /** * Grants permission to list all billing groups * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListBillingGroups.html */ public toListBillingGroups() { return this.to('ListBillingGroups'); } /** * Grants permission to list the CA certificates registered for your AWS account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListCACertificates.html */ public toListCACertificates() { return this.to('ListCACertificates'); } /** * Grants permission to list your certificates * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListCertificates.html */ public toListCertificates() { return this.to('ListCertificates'); } /** * Grants permission to list the device certificates signed by the specified CA certificate * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListCertificatesByCA.html */ public toListCertificatesByCA() { return this.to('ListCertificatesByCA'); } /** * Grants permission to list the custom metrics in your AWS account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListCustomMetrics.html */ public toListCustomMetrics() { return this.to('ListCustomMetrics'); } /** * Grants permission to lists mitigation actions executions for a Device Defender ML Detect Security Profile * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListDetectMitigationActionsExecutions.html */ public toListDetectMitigationActionsExecutions() { return this.to('ListDetectMitigationActionsExecutions'); } /** * Grants permission to list Device Defender ML Detect mitigation actions tasks * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListDetectMitigationActionsTasks.html */ public toListDetectMitigationActionsTasks() { return this.to('ListDetectMitigationActionsTasks'); } /** * Grants permission to list the dimensions that are defined for your AWS account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListDimensions.html */ public toListDimensions() { return this.to('ListDimensions'); } /** * Grants permission to list the domain configuration created by your AWS account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListDomainConfigurations.html */ public toListDomainConfigurations() { return this.to('ListDomainConfigurations'); } /** * Grants permission to list the fleet metrics in your account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/iot-indexing.html */ public toListFleetMetrics() { return this.to('ListFleetMetrics'); } /** * Grants permission to list all indices for fleet index * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListIndices.html */ public toListIndices() { return this.to('ListIndices'); } /** * Grants permission to list the job executions for a job * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListJobExecutionsForJob.html */ public toListJobExecutionsForJob() { return this.to('ListJobExecutionsForJob'); } /** * Grants permission to list the job executions for the specified thing * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListJobExecutionsForThing.html */ public toListJobExecutionsForThing() { return this.to('ListJobExecutionsForThing'); } /** * Grants permission to list job templates * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListJobTemplates.html */ public toListJobTemplates() { return this.to('ListJobTemplates'); } /** * Grants permission to list jobs * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListJobs.html */ public toListJobs() { return this.to('ListJobs'); } /** * Grants permission to get a list of all mitigation actions that match the specified filter criteria * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListMitigationActions.html */ public toListMitigationActions() { return this.to('ListMitigationActions'); } /** * Grants permission to list all named shadows for a given thing * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListNamedShadowsForThing.html */ public toListNamedShadowsForThing() { return this.to('ListNamedShadowsForThing'); } /** * Grants permission to list OTA update jobs in the account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListOTAUpdates.html */ public toListOTAUpdates() { return this.to('ListOTAUpdates'); } /** * Grants permission to list certificates that are being transfered but not yet accepted * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListOutgoingCertificates.html */ public toListOutgoingCertificates() { return this.to('ListOutgoingCertificates'); } /** * Grants permission to list your policies * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListPolicies.html */ public toListPolicies() { return this.to('ListPolicies'); } /** * Grants permission to list the principals associated with the specified policy * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListPolicyPrincipals.html */ public toListPolicyPrincipals() { return this.to('ListPolicyPrincipals'); } /** * Grants permission to list the versions of the specified policy, and identifies the default version * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListPolicyVersions.html */ public toListPolicyVersions() { return this.to('ListPolicyVersions'); } /** * Grants permission to list the policies attached to the specified principal. If you use an Amazon Cognito identity, the ID needs to be in Amazon Cognito Identity format * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListPrincipalPolicies.html */ public toListPrincipalPolicies() { return this.to('ListPrincipalPolicies'); } /** * Grants permission to list the things associated with the specified principal * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListPrincipalThings.html */ public toListPrincipalThings() { return this.to('ListPrincipalThings'); } /** * Grants permission to get a list of fleet provisioning template versions * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListProvisioningTemplateVersions.html */ public toListProvisioningTemplateVersions() { return this.to('ListProvisioningTemplateVersions'); } /** * Grants permission to list the fleet provisioning templates in your AWS account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListProvisioningTemplates.html */ public toListProvisioningTemplates() { return this.to('ListProvisioningTemplates'); } /** * Grants permission to list the retained messages for your account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toListRetainedMessages() { return this.to('ListRetainedMessages'); } /** * Grants permission to list role aliases * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListRoleAliases.html */ public toListRoleAliases() { return this.to('ListRoleAliases'); } /** * Grants permission to list all of your scheduled audits * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListScheduledAudits.html */ public toListScheduledAudits() { return this.to('ListScheduledAudits'); } /** * Grants permission to list the Device Defender security profiles you have created * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListSecurityProfiles.html */ public toListSecurityProfiles() { return this.to('ListSecurityProfiles'); } /** * Grants permission to list the Device Defender security profiles attached to a target * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListSecurityProfilesForTarget.html */ public toListSecurityProfilesForTarget() { return this.to('ListSecurityProfilesForTarget'); } /** * Grants permission to list the streams in your account * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListStreams.html */ public toListStreams() { return this.to('ListStreams'); } /** * Grants permission to list all tags for a given resource * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to list targets for the specified policy * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListTargetsForPolicy.html */ public toListTargetsForPolicy() { return this.to('ListTargetsForPolicy'); } /** * Grants permission to list the targets associated with a given Device Defender security profile * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListTargetsForSecurityProfile.html */ public toListTargetsForSecurityProfile() { return this.to('ListTargetsForSecurityProfile'); } /** * Grants permission to list all thing groups * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingGroups.html */ public toListThingGroups() { return this.to('ListThingGroups'); } /** * Grants permission to list thing groups to which the specified thing belongs * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingGroupsForThing.html */ public toListThingGroupsForThing() { return this.to('ListThingGroupsForThing'); } /** * Grants permission to list the principals associated with the specified thing * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingPrincipals.html */ public toListThingPrincipals() { return this.to('ListThingPrincipals'); } /** * Grants permission to list information about bulk thing registration tasks * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingRegistrationTaskReports.html */ public toListThingRegistrationTaskReports() { return this.to('ListThingRegistrationTaskReports'); } /** * Grants permission to list bulk thing registration tasks * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingRegistrationTasks.html */ public toListThingRegistrationTasks() { return this.to('ListThingRegistrationTasks'); } /** * Grants permission to list all thing types * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingTypes.html */ public toListThingTypes() { return this.to('ListThingTypes'); } /** * Grants permission to list all things * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThings.html */ public toListThings() { return this.to('ListThings'); } /** * Grants permission to list all things in the specified billing group * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingsInBillingGroup.html */ public toListThingsInBillingGroup() { return this.to('ListThingsInBillingGroup'); } /** * Grants permission to list all things in the specified thing group * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingsInThingGroup.html */ public toListThingsInThingGroup() { return this.to('ListThingsInThingGroup'); } /** * Grants permission to list all TopicRuleDestinations * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListTopicRuleDestinations.html */ public toListTopicRuleDestinations() { return this.to('ListTopicRuleDestinations'); } /** * Grants permission to list the rules for the specific topic * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListTopicRules.html */ public toListTopicRules() { return this.to('ListTopicRules'); } /** * Grants permission to list tunnels * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListTunnels.html */ public toListTunnels() { return this.to('ListTunnels'); } /** * Grants permission to list the v2 logging levels * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListV2LoggingLevels.html */ public toListV2LoggingLevels() { return this.to('ListV2LoggingLevels'); } /** * Grants permission to list the Device Defender security profile violations discovered during the given time period * * Access Level: List * * https://docs.aws.amazon.com/iot/latest/apireference/API_ListViolationEvents.html */ public toListViolationEvents() { return this.to('ListViolationEvents'); } /** * Grants permission to open a tunnel * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifThingGroupArn() * - .ifTunnelDestinationService() * * https://docs.aws.amazon.com/iot/latest/apireference/API_OpenTunnel.html */ public toOpenTunnel() { return this.to('OpenTunnel'); } /** * Grants permission to publish to the specified topic * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toPublish() { return this.to('Publish'); } /** * Grants permission to receive from the specified topic * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toReceive() { return this.to('Receive'); } /** * Grants permission to register a CA certificate with AWS IoT * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCACertificate.html */ public toRegisterCACertificate() { return this.to('RegisterCACertificate'); } /** * Grants permission to register a device certificate with AWS IoT * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCertificate.html */ public toRegisterCertificate() { return this.to('RegisterCertificate'); } /** * Grants permission to register a device certificate with AWS IoT without a registered CA (certificate authority) * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCertificateWithoutCA.html */ public toRegisterCertificateWithoutCA() { return this.to('RegisterCertificateWithoutCA'); } /** * Grants permission to register your thing * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterThing.html */ public toRegisterThing() { return this.to('RegisterThing'); } /** * Grants permission to reject a pending certificate transfer * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_RejectCertificateTransfer.html */ public toRejectCertificateTransfer() { return this.to('RejectCertificateTransfer'); } /** * Grants permission to remove thing from the specified billing group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_RemoveThingFromBillingGroup.html */ public toRemoveThingFromBillingGroup() { return this.to('RemoveThingFromBillingGroup'); } /** * Grants permission to remove thing from the specified thing group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_RemoveThingFromThingGroup.html */ public toRemoveThingFromThingGroup() { return this.to('RemoveThingFromThingGroup'); } /** * Grants permission to replace the specified rule * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_ReplaceTopicRule.html */ public toReplaceTopicRule() { return this.to('ReplaceTopicRule'); } /** * Grants permission to publish a retained message to the specified topic * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toRetainPublish() { return this.to('RetainPublish'); } /** * Grants permission to search IoT fleet index * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_SearchIndex.html */ public toSearchIndex() { return this.to('SearchIndex'); } /** * Grants permission to set the default authorizer. This will be used if a websocket connection is made without specifying an authorizer * * Access Level: Permissions management * * https://docs.aws.amazon.com/iot/latest/apireference/API_SetDefaultAuthorizer.html */ public toSetDefaultAuthorizer() { return this.to('SetDefaultAuthorizer'); } /** * Grants permission to set the specified version of the specified policy as the policy's default (operative) version * * Access Level: Permissions management * * https://docs.aws.amazon.com/iot/latest/apireference/API_SetDefaultPolicyVersion.html */ public toSetDefaultPolicyVersion() { return this.to('SetDefaultPolicyVersion'); } /** * Grants permission to set the logging options * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_SetLoggingOptions.html */ public toSetLoggingOptions() { return this.to('SetLoggingOptions'); } /** * Grants permission to set the v2 logging level * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_SetV2LoggingLevel.html */ public toSetV2LoggingLevel() { return this.to('SetV2LoggingLevel'); } /** * Grants permission to set the v2 logging options * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_SetV2LoggingOptions.html */ public toSetV2LoggingOptions() { return this.to('SetV2LoggingOptions'); } /** * Grants permission to start a task that applies a set of mitigation actions to the specified target * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_StartAuditMitigationActionsTask.html */ public toStartAuditMitigationActionsTask() { return this.to('StartAuditMitigationActionsTask'); } /** * Grants permission to start a Device Defender ML Detect mitigation actions task * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_StartDetectMitigationActionsTask.html */ public toStartDetectMitigationActionsTask() { return this.to('StartDetectMitigationActionsTask'); } /** * Grants permission to get and start the next pending job execution for a thing * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_StartNextPendingJobExecution.html */ public toStartNextPendingJobExecution() { return this.to('StartNextPendingJobExecution'); } /** * Grants permission to start an on-demand Device Defender audit * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_StartOnDemandAuditTask.html */ public toStartOnDemandAuditTask() { return this.to('StartOnDemandAuditTask'); } /** * Grants permission to start a bulk thing registration task * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_StartThingRegistrationTask.html */ public toStartThingRegistrationTask() { return this.to('StartThingRegistrationTask'); } /** * Grants permission to stop a bulk thing registration task * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_StopThingRegistrationTask.html */ public toStopThingRegistrationTask() { return this.to('StopThingRegistrationTask'); } /** * Grants permission to subscribe to the specified TopicFilter * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toSubscribe() { return this.to('Subscribe'); } /** * Grants permission to tag a specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to test the policies evaluation for group policies * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_TestAuthorization.html */ public toTestAuthorization() { return this.to('TestAuthorization'); } /** * Grants permission to test invoke the specified custom authorizer for testing purposes * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_TestInvokeAuthorizer.html */ public toTestInvokeAuthorizer() { return this.to('TestInvokeAuthorizer'); } /** * Grants permission to transfer the specified certificate to the specified AWS account * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_TransferCertificate.html */ public toTransferCertificate() { return this.to('TransferCertificate'); } /** * Grants permission to untag a specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/iot/latest/apireference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to configure or reconfigure the Device Defender audit settings for this account * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateAccountAuditConfiguration.html */ public toUpdateAccountAuditConfiguration() { return this.to('UpdateAccountAuditConfiguration'); } /** * Grants permission to update a Device Defender audit suppression * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateAuditSuppression.html */ public toUpdateAuditSuppression() { return this.to('UpdateAuditSuppression'); } /** * Grants permission to update an authorizer * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateAuthorizer.html */ public toUpdateAuthorizer() { return this.to('UpdateAuthorizer'); } /** * Grants permission to update information associated with the specified billing group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateBillingGroup.html */ public toUpdateBillingGroup() { return this.to('UpdateBillingGroup'); } /** * Grants permission to update a registered CA certificate * * Access Level: Write * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateCACertificate.html */ public toUpdateCACertificate() { return this.to('UpdateCACertificate'); } /** * Grants permission to update the status of the specified certificate. This operation is idempotent * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateCertificate.html */ public toUpdateCertificate() { return this.to('UpdateCertificate'); } /** * Grants permission to update the specified custom metric * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateCustomMetric.html */ public toUpdateCustomMetric() { return this.to('UpdateCustomMetric'); } /** * Grants permission to update the definition for a dimension * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateDimension.html */ public toUpdateDimension() { return this.to('UpdateDimension'); } /** * Grants permission to update a domain configuration * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateDomainConfiguration.html */ public toUpdateDomainConfiguration() { return this.to('UpdateDomainConfiguration'); } /** * Grants permission to update a Dynamic Thing Group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateDynamicThingGroup.html */ public toUpdateDynamicThingGroup() { return this.to('UpdateDynamicThingGroup'); } /** * Grants permission to update event configurations * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateEventConfigurations.html */ public toUpdateEventConfigurations() { return this.to('UpdateEventConfigurations'); } /** * Grants permission to update a fleet metric * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/iot-indexing.html */ public toUpdateFleetMetric() { return this.to('UpdateFleetMetric'); } /** * Grants permission to update fleet indexing configuration * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateIndexingConfiguration.html */ public toUpdateIndexingConfiguration() { return this.to('UpdateIndexingConfiguration'); } /** * Grants permission to update a job * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateJob.html */ public toUpdateJob() { return this.to('UpdateJob'); } /** * Grants permission to update a job execution * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateJobExecution.html */ public toUpdateJobExecution() { return this.to('UpdateJobExecution'); } /** * Grants permission to update the definition for the specified mitigation action * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateMitigationAction.html */ public toUpdateMitigationAction() { return this.to('UpdateMitigationAction'); } /** * Grants permission to update a fleet provisioning template * * Access Level: Write * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateProvisioningTemplate.html */ public toUpdateProvisioningTemplate() { return this.to('UpdateProvisioningTemplate'); } /** * Grants permission to update the role alias * * Access Level: Write * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateRoleAlias.html */ public toUpdateRoleAlias() { return this.to('UpdateRoleAlias'); } /** * Grants permission to update a scheduled audit, including what checks are performed and how often the audit takes place * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateScheduledAudit.html */ public toUpdateScheduledAudit() { return this.to('UpdateScheduledAudit'); } /** * Grants permission to update a Device Defender security profile * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateSecurityProfile.html */ public toUpdateSecurityProfile() { return this.to('UpdateSecurityProfile'); } /** * Grants permission to update the data for a stream * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateStream.html */ public toUpdateStream() { return this.to('UpdateStream'); } /** * Grants permission to update information associated with the specified thing * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateThing.html */ public toUpdateThing() { return this.to('UpdateThing'); } /** * Grants permission to update information associated with the specified thing group * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateThingGroup.html */ public toUpdateThingGroup() { return this.to('UpdateThingGroup'); } /** * Grants permission to update the thing groups to which the thing belongs * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateThingGroupsForThing.html */ public toUpdateThingGroupsForThing() { return this.to('UpdateThingGroupsForThing'); } /** * Grants permission to update the thing shadow * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/developerguide/policy-actions.html */ public toUpdateThingShadow() { return this.to('UpdateThingShadow'); } /** * Grants permission to update a TopicRuleDestination * * Access Level: Write * * https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateTopicRuleDestination.html */ public toUpdateTopicRuleDestination() { return this.to('UpdateTopicRuleDestination'); } /** * Grants permission to validate a Device Defender security profile behaviors specification * * Access Level: Read * * https://docs.aws.amazon.com/iot/latest/apireference/API_ValidateSecurityProfileBehaviors.html */ public toValidateSecurityProfileBehaviors() { return this.to('ValidateSecurityProfileBehaviors'); } protected accessLevelList: AccessLevelList = { "Write": [ "AcceptCertificateTransfer", "AddThingToBillingGroup", "AddThingToThingGroup", "AssociateTargetsWithJob", "AttachSecurityProfile", "AttachThingPrincipal", "CancelAuditMitigationActionsTask", "CancelAuditTask", "CancelCertificateTransfer", "CancelDetectMitigationActionsTask", "CancelJob", "CancelJobExecution", "ClearDefaultAuthorizer", "CloseTunnel", "ConfirmTopicRuleDestination", "Connect", "CreateAuditSuppression", "CreateAuthorizer", "CreateBillingGroup", "CreateCertificateFromCsr", "CreateCustomMetric", "CreateDimension", "CreateDomainConfiguration", "CreateDynamicThingGroup", "CreateFleetMetric", "CreateJob", "CreateJobTemplate", "CreateKeysAndCertificate", "CreateMitigationAction", "CreateOTAUpdate", "CreatePolicy", "CreatePolicyVersion", "CreateProvisioningClaim", "CreateProvisioningTemplate", "CreateProvisioningTemplateVersion", "CreateRoleAlias", "CreateScheduledAudit", "CreateSecurityProfile", "CreateStream", "CreateThing", "CreateThingGroup", "CreateThingType", "CreateTopicRule", "CreateTopicRuleDestination", "DeleteAccountAuditConfiguration", "DeleteAuditSuppression", "DeleteAuthorizer", "DeleteBillingGroup", "DeleteCACertificate", "DeleteCertificate", "DeleteCustomMetric", "DeleteDimension", "DeleteDomainConfiguration", "DeleteDynamicThingGroup", "DeleteFleetMetric", "DeleteJob", "DeleteJobExecution", "DeleteJobTemplate", "DeleteMitigationAction", "DeleteOTAUpdate", "DeletePolicy", "DeletePolicyVersion", "DeleteProvisioningTemplate", "DeleteProvisioningTemplateVersion", "DeleteRegistrationCode", "DeleteRoleAlias", "DeleteScheduledAudit", "DeleteSecurityProfile", "DeleteStream", "DeleteThing", "DeleteThingGroup", "DeleteThingShadow", "DeleteThingType", "DeleteTopicRule", "DeleteTopicRuleDestination", "DeleteV2LoggingLevel", "DeprecateThingType", "DetachSecurityProfile", "DetachThingPrincipal", "DisableTopicRule", "EnableTopicRule", "OpenTunnel", "Publish", "Receive", "RegisterCACertificate", "RegisterCertificate", "RegisterCertificateWithoutCA", "RegisterThing", "RejectCertificateTransfer", "RemoveThingFromBillingGroup", "RemoveThingFromThingGroup", "ReplaceTopicRule", "RetainPublish", "SetLoggingOptions", "SetV2LoggingLevel", "SetV2LoggingOptions", "StartAuditMitigationActionsTask", "StartDetectMitigationActionsTask", "StartNextPendingJobExecution", "StartOnDemandAuditTask", "StartThingRegistrationTask", "StopThingRegistrationTask", "Subscribe", "TransferCertificate", "UpdateAccountAuditConfiguration", "UpdateAuditSuppression", "UpdateAuthorizer", "UpdateBillingGroup", "UpdateCACertificate", "UpdateCertificate", "UpdateCustomMetric", "UpdateDimension", "UpdateDomainConfiguration", "UpdateDynamicThingGroup", "UpdateEventConfigurations", "UpdateFleetMetric", "UpdateIndexingConfiguration", "UpdateJob", "UpdateJobExecution", "UpdateMitigationAction", "UpdateProvisioningTemplate", "UpdateRoleAlias", "UpdateScheduledAudit", "UpdateSecurityProfile", "UpdateStream", "UpdateThing", "UpdateThingGroup", "UpdateThingGroupsForThing", "UpdateThingShadow", "UpdateTopicRuleDestination" ], "Permissions management": [ "AttachPolicy", "AttachPrincipalPolicy", "DetachPolicy", "DetachPrincipalPolicy", "SetDefaultAuthorizer", "SetDefaultPolicyVersion" ], "Read": [ "DescribeAccountAuditConfiguration", "DescribeAuditFinding", "DescribeAuditMitigationActionsTask", "DescribeAuditSuppression", "DescribeAuditTask", "DescribeAuthorizer", "DescribeBillingGroup", "DescribeCACertificate", "DescribeCertificate", "DescribeCustomMetric", "DescribeDefaultAuthorizer", "DescribeDetectMitigationActionsTask", "DescribeDimension", "DescribeDomainConfiguration", "DescribeEndpoint", "DescribeEventConfigurations", "DescribeFleetMetric", "DescribeIndex", "DescribeJob", "DescribeJobExecution", "DescribeJobTemplate", "DescribeMitigationAction", "DescribeProvisioningTemplate", "DescribeProvisioningTemplateVersion", "DescribeRoleAlias", "DescribeScheduledAudit", "DescribeSecurityProfile", "DescribeStream", "DescribeThing", "DescribeThingGroup", "DescribeThingRegistrationTask", "DescribeThingType", "DescribeTunnel", "GetBucketsAggregation", "GetCardinality", "GetEffectivePolicies", "GetIndexingConfiguration", "GetJobDocument", "GetLoggingOptions", "GetOTAUpdate", "GetPendingJobExecutions", "GetPercentiles", "GetPolicy", "GetPolicyVersion", "GetRegistrationCode", "GetRetainedMessage", "GetStatistics", "GetThingShadow", "GetTopicRule", "GetTopicRuleDestination", "GetV2LoggingOptions", "ListTagsForResource", "SearchIndex", "TestAuthorization", "TestInvokeAuthorizer", "ValidateSecurityProfileBehaviors" ], "List": [ "GetBehaviorModelTrainingSummaries", "ListActiveViolations", "ListAttachedPolicies", "ListAuditFindings", "ListAuditMitigationActionsExecutions", "ListAuditMitigationActionsTasks", "ListAuditSuppressions", "ListAuditTasks", "ListAuthorizers", "ListBillingGroups", "ListCACertificates", "ListCertificates", "ListCertificatesByCA", "ListCustomMetrics", "ListDetectMitigationActionsExecutions", "ListDetectMitigationActionsTasks", "ListDimensions", "ListDomainConfigurations", "ListFleetMetrics", "ListIndices", "ListJobExecutionsForJob", "ListJobExecutionsForThing", "ListJobTemplates", "ListJobs", "ListMitigationActions", "ListNamedShadowsForThing", "ListOTAUpdates", "ListOutgoingCertificates", "ListPolicies", "ListPolicyPrincipals", "ListPolicyVersions", "ListPrincipalPolicies", "ListPrincipalThings", "ListProvisioningTemplateVersions", "ListProvisioningTemplates", "ListRetainedMessages", "ListRoleAliases", "ListScheduledAudits", "ListSecurityProfiles", "ListSecurityProfilesForTarget", "ListStreams", "ListTargetsForPolicy", "ListTargetsForSecurityProfile", "ListThingGroups", "ListThingGroupsForThing", "ListThingPrincipals", "ListThingRegistrationTaskReports", "ListThingRegistrationTasks", "ListThingTypes", "ListThings", "ListThingsInBillingGroup", "ListThingsInThingGroup", "ListTopicRuleDestinations", "ListTopicRules", "ListTunnels", "ListV2LoggingLevels", "ListViolationEvents" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type client to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-message-broker.html * * @param clientId - Identifier for the clientId. * @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`. */ public onClient(clientId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:client/${ClientId}'; arn = arn.replace('${ClientId}', clientId); 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 index to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-indexing.html * * @param indexName - Identifier for the indexName. * @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`. */ public onIndex(indexName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:index/${IndexName}'; arn = arn.replace('${IndexName}', indexName); 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 fleetmetric to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-indexing.html * * @param fleetMetricName - Identifier for the fleetMetricName. * @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 onFleetmetric(fleetMetricName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:fleetmetric/${FleetMetricName}'; arn = arn.replace('${FleetMetricName}', fleetMetricName); 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 job to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-jobs.html * * @param jobId - Identifier for the jobId. * @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 onJob(jobId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:job/${JobId}'; arn = arn.replace('${JobId}', jobId); 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 jobtemplate to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-job-templates.html * * @param jobTemplateId - Identifier for the jobTemplateId. * @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 onJobtemplate(jobTemplateId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:jobtemplate/${JobTemplateId}'; arn = arn.replace('${JobTemplateId}', jobTemplateId); 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 tunnel to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-tunnels.html * * @param tunnelId - Identifier for the tunnelId. * @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 onTunnel(tunnelId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:tunnel/${TunnelId}'; arn = arn.replace('${TunnelId}', tunnelId); 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 thing to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry.html * * @param thingName - Identifier for the thingName. * @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`. */ public onThing(thingName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:thing/${ThingName}'; arn = arn.replace('${ThingName}', thingName); 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 thinggroup to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html * * @param thingGroupName - Identifier for the thingGroupName. * @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 onThinggroup(thingGroupName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:thinggroup/${ThingGroupName}'; arn = arn.replace('${ThingGroupName}', thingGroupName); 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 billinggroup to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/billing-groups.html * * @param billingGroupName - Identifier for the billingGroupName. * @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 onBillinggroup(billingGroupName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:billinggroup/${BillingGroupName}'; arn = arn.replace('${BillingGroupName}', billingGroupName); 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 dynamicthinggroup to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/dynamic-thing-groups.html * * @param thingGroupName - Identifier for the thingGroupName. * @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 onDynamicthinggroup(thingGroupName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:thinggroup/${ThingGroupName}'; arn = arn.replace('${ThingGroupName}', thingGroupName); 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 thingtype to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html * * @param thingTypeName - Identifier for the thingTypeName. * @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 onThingtype(thingTypeName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:thingtype/${ThingTypeName}'; arn = arn.replace('${ThingTypeName}', thingTypeName); 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 topic to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-message-broker.html * * @param topicName - Identifier for the topicName. * @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`. */ public onTopic(topicName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:topic/${TopicName}'; arn = arn.replace('${TopicName}', topicName); 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 topicfilter to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/topics.html * * @param topicFilter - Identifier for the topicFilter. * @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`. */ public onTopicfilter(topicFilter: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:topicfilter/${TopicFilter}'; arn = arn.replace('${TopicFilter}', topicFilter); 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 rolealias to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html * * @param roleAlias - Identifier for the roleAlias. * @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 onRolealias(roleAlias: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:rolealias/${RoleAlias}'; arn = arn.replace('${RoleAlias}', roleAlias); 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 authorizer to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/custom-authorizer.html * * @param authorizerName - Identifier for the authorizerName. * @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 onAuthorizer(authorizerName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:authorizer/${AuthorizerName}'; arn = arn.replace('${AuthorizerName}', authorizerName); 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 policy to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html * * @param policyName - Identifier for the policyName. * @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 onPolicy(policyName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:policy/${PolicyName}'; arn = arn.replace('${PolicyName}', policyName); 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 cert to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/x509-certs.html * * @param certificate - Identifier for the certificate. * @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`. */ public onCert(certificate: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:cert/${Certificate}'; arn = arn.replace('${Certificate}', certificate); 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 cacert to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/x509-certs.html * * @param cACertificate - Identifier for the cACertificate. * @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 onCacert(cACertificate: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:cacert/${CACertificate}'; arn = arn.replace('${CACertificate}', cACertificate); 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/freertos/latest/userguide/freertos-ota-dev.html * * @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(streamId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:stream/${StreamId}'; 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 otaupdate to the statement * * https://docs.aws.amazon.com/freertos/latest/userguide/freertos-ota-dev.html * * @param otaUpdateId - Identifier for the otaUpdateId. * @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 onOtaupdate(otaUpdateId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:otaupdate/${OtaUpdateId}'; arn = arn.replace('${OtaUpdateId}', otaUpdateId); 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 scheduledaudit to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/device-defender-audit.html * * @param scheduleName - Identifier for the scheduleName. * @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 onScheduledaudit(scheduleName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:scheduledaudit/${ScheduleName}'; arn = arn.replace('${ScheduleName}', scheduleName); 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 mitigationaction to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/device-defender-mitigation-actions.html * * @param mitigationActionName - Identifier for the mitigationActionName. * @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 onMitigationaction(mitigationActionName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:mitigationaction/${MitigationActionName}'; arn = arn.replace('${MitigationActionName}', mitigationActionName); 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 securityprofile to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/device-defender-detect.html * * @param securityProfileName - Identifier for the securityProfileName. * @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 onSecurityprofile(securityProfileName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:securityprofile/${SecurityProfileName}'; arn = arn.replace('${SecurityProfileName}', securityProfileName); 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 custommetric to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/device-defender-detect.html * * @param metricName - Identifier for the metricName. * @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 onCustommetric(metricName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:custommetric/${MetricName}'; arn = arn.replace('${MetricName}', metricName); 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 dimension to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/device-defender-detect.html * * @param dimensionName - Identifier for the dimensionName. * @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 onDimension(dimensionName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:dimension/${DimensionName}'; arn = arn.replace('${DimensionName}', dimensionName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type rule to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/iot-rules.html * * @param ruleName - Identifier for the ruleName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onRule(ruleName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:rule/${RuleName}'; arn = arn.replace('${RuleName}', ruleName); 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 destination to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html * * @param destinationType - Identifier for the destinationType. * @param uuid - Identifier for the uuid. * @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`. */ public onDestination(destinationType: string, uuid: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:destination/${DestinationType}/${Uuid}'; arn = arn.replace('${DestinationType}', destinationType); arn = arn.replace('${Uuid}', uuid); 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 provisioningtemplate to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/provision-template.html * * @param provisioningTemplate - Identifier for the provisioningTemplate. * @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 onProvisioningtemplate(provisioningTemplate: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:provisioningtemplate/${ProvisioningTemplate}'; arn = arn.replace('${ProvisioningTemplate}', provisioningTemplate); 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 domainconfiguration to the statement * * https://docs.aws.amazon.com/iot/latest/developerguide/domain-configuration.html * * @param domainConfigurationName - Identifier for the domainConfigurationName. * @param id - Identifier for the id. * @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 onDomainconfiguration(domainConfigurationName: string, id: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:iot:${Region}:${Account}:domainconfiguration/${DomainConfigurationName}/${Id}'; arn = arn.replace('${DomainConfigurationName}', domainConfigurationName); arn = arn.replace('${Id}', id); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access by a flag indicating whether or not to also delete an IoT Tunnel immediately when making iot:CloseTunnel request * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html * * Applies to actions: * - .toCloseTunnel() * * @param value `true` or `false`. **Default:** `true` */ public ifDelete(value?: boolean) { return this.if(`Delete`, (typeof value !== 'undefined' ? value : true), 'Bool'); } /** * Filters access by based on the domain name of an IoT DomainConfiguration * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html * * Applies to actions: * - .toCreateDomainConfiguration() * * @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 ifDomainName(value: string | string[], operator?: Operator | string) { return this.if(`DomainName`, value, operator || 'StringLike'); } /** * Filters access by a list of IoT Thing Group ARNs that the destination IoT Thing belongs to for an IoT Tunnel * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html * * Applies to actions: * - .toOpenTunnel() * * @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 ifThingGroupArn(value: string | string[], operator?: Operator | string) { return this.if(`ThingGroupArn`, value, operator || 'StringLike'); } /** * Filters access by a list of destination services for an IoT Tunnel * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html * * Applies to actions: * - .toOpenTunnel() * * @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 ifTunnelDestinationService(value: string | string[], operator?: Operator | string) { return this.if(`TunnelDestinationService`, value, operator || 'StringLike'); } }
the_stack
import { TileDao } from '../user/tileDao'; import { TileMatrix } from '../matrix/tileMatrix'; import { TileBoundingBoxUtils } from '../tileBoundingBoxUtils'; import { BoundingBox } from '../../boundingBox'; import { TileCreator } from '../creator/tileCreator'; import { TileRow } from '../user/tileRow'; import { TileScaling } from '../../extension/scale/tileScaling'; import { TileScalingType } from '../../extension/scale/tileScalingType'; export class GeoPackageTileRetriever { tileDao: TileDao<TileRow>; width: number; height: number; setWebMercatorBoundingBox: BoundingBox; setProjectionBoundingBox: BoundingBox; scaling: TileScaling; constructor(tileDao: TileDao<TileRow>, width: number, height: number) { this.tileDao = tileDao; this.tileDao.adjustTileMatrixLengths(); this.width = width; this.height = height; this.scaling = null; } setScaling(scaling: TileScaling): void { this.scaling = scaling; } getWebMercatorBoundingBox(): BoundingBox { if (this.setWebMercatorBoundingBox) { return this.setWebMercatorBoundingBox; } else { const tileMatrixSetDao = this.tileDao.geoPackage.tileMatrixSetDao; const tileMatrixSet = this.tileDao.tileMatrixSet; const srs = tileMatrixSetDao.getSrs(tileMatrixSet); this.setProjectionBoundingBox = tileMatrixSet.boundingBox; if (srs.organization_coordsys_id === 4326 && srs.organization === 'EPSG') { this.setProjectionBoundingBox.minLatitude = Math.max(this.setProjectionBoundingBox.minLatitude, -85.05); this.setProjectionBoundingBox.maxLatitude = Math.min(this.setProjectionBoundingBox.maxLatitude, 85.05); } this.setWebMercatorBoundingBox = this.setProjectionBoundingBox.projectBoundingBox( this.tileDao.projection, 'EPSG:3857', ); return this.setWebMercatorBoundingBox; } } /** * Determine the web mercator bounding box from xyz and see if there is a tile for the bounding box. * @param x * @param y * @param zoom */ hasTile(x: number, y: number, zoom: number): boolean { let hasTile = false; if (x >= 0 && y >= 0 && zoom >= 0) { const tilesBoundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, zoom); hasTile = this.hasTileForBoundingBox(tilesBoundingBox, 'EPSG:3857'); } return hasTile; } hasTileForBoundingBox(tilesBoundingBox: BoundingBox, targetProjection: string): boolean { const projectedBoundingBox = tilesBoundingBox.projectBoundingBox(targetProjection, this.tileDao.projection); const tileMatrices = this.getTileMatrices(projectedBoundingBox); let hasTile = false; for (let i = 0; !hasTile && i < tileMatrices.length; i++) { const tileMatrix = tileMatrices[i]; const tileGrid = TileBoundingBoxUtils.getTileGridWithTotalBoundingBox( this.tileDao.tileMatrixSet.boundingBox, tileMatrix.matrix_width, tileMatrix.matrix_height, projectedBoundingBox, ); hasTile = this.tileDao.countByTileGrid(tileGrid, tileMatrix.zoom_level) > 0; } return hasTile; } async getTile(x: number, y: number, zoom: number): Promise<any> { const webMercatorBoundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, zoom); return this.getTileWithBounds(webMercatorBoundingBox, 'EPSG:3857'); } async getWebMercatorTile(x: number, y: number, zoom: number): Promise<any> { // need to determine the geoPackage zoom level from the web mercator zoom level const webMercatorBoundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, zoom); return this.getTileWithBounds(webMercatorBoundingBox, 'EPSG:3857'); } async drawTileIn(x: number, y: number, zoom: number, canvas?: any): Promise<any> { const webMercatorBoundingBox = TileBoundingBoxUtils.getWebMercatorBoundingBoxFromXYZ(x, y, zoom); return this.getTileWithBounds(webMercatorBoundingBox, 'EPSG:3857', canvas); } async getTileWithWgs84Bounds(wgs84BoundingBox: BoundingBox, canvas?: any): Promise<any> { const webMercatorBoundingBox = wgs84BoundingBox.projectBoundingBox('EPSG:4326', 'EPSG:3857'); return this.getTileWithBounds(webMercatorBoundingBox, 'EPSG:3857', canvas); } async getTileWithWgs84BoundsInProjection( wgs84BoundingBox: BoundingBox, zoom: number, targetProjection: string, canvas?: any, ): Promise<any> { const targetBoundingBox = wgs84BoundingBox.projectBoundingBox('EPSG:4326', targetProjection); return this.getTileWithBounds(targetBoundingBox, targetProjection, canvas); } async getTileWithBounds(targetBoundingBox: BoundingBox, targetProjection: string, canvas?: any): Promise<any> { const projectedBoundingBox = targetBoundingBox.projectBoundingBox(targetProjection, this.tileDao.projection); const tileMatrices = this.getTileMatrices(projectedBoundingBox); let tileFound = false; let tile = null; for (let i = 0; !tileFound && i < tileMatrices.length; i++) { const tileMatrix = tileMatrices[i]; const tileWidth = tileMatrix.tile_width; const tileHeight = tileMatrix.tile_height; const creator = await TileCreator.create( this.width || tileWidth, this.height || tileHeight, tileMatrix, this.tileDao.tileMatrixSet, targetBoundingBox, this.tileDao.srs, targetProjection, canvas, ); const iterator = this.retrieveTileResults(projectedBoundingBox, tileMatrix); for (const tile of iterator) { // Get the bounding box of the tile const tileBoundingBox = TileBoundingBoxUtils.getTileBoundingBox( this.tileDao.tileMatrixSet.boundingBox, tileMatrix, tile.tileColumn, tile.row, ); const overlap = TileBoundingBoxUtils.intersection(projectedBoundingBox, tileBoundingBox); if (overlap != null) { const src = TileBoundingBoxUtils.getFloatRoundedRectangle( tileMatrix.tile_width, tileMatrix.tile_height, tileBoundingBox, overlap, ); const dest = TileBoundingBoxUtils.getFloatRoundedRectangle( this.width, this.height, projectedBoundingBox, overlap, ); if (src.isValid && dest.isValid) { await creator.addTile(tile.tileData, tile.tileColumn, tile.row); tileFound = true; } } } if (!canvas && tileFound) { tile = creator.getCompleteTile('png'); } } return tile; } retrieveTileResults( tileMatrixProjectionBoundingBox: BoundingBox, tileMatrix?: TileMatrix, ): IterableIterator<TileRow> { if (tileMatrix) { const tileGrid = TileBoundingBoxUtils.getTileGridWithTotalBoundingBox( this.tileDao.tileMatrixSet.boundingBox, tileMatrix.matrix_width, tileMatrix.matrix_height, tileMatrixProjectionBoundingBox, ); return this.tileDao.queryByTileGrid(tileGrid, tileMatrix.zoom_level); } } /** * Get the tile matrices that may contain the tiles for the bounding box, * matches against the bounding box and zoom level options * @param projectedRequestBoundingBox bounding box projected to the tiles * @return tile matrices */ getTileMatrices(projectedRequestBoundingBox: BoundingBox): TileMatrix[] { const tileMatrices: TileMatrix[] = []; // Check if the request overlaps the tile matrix set if ( this.tileDao.tileMatrices.length !== 0 && TileBoundingBoxUtils.intersects(projectedRequestBoundingBox, this.tileDao.tileMatrixSet.boundingBox) ) { // Get the tile distance const distanceWidth = projectedRequestBoundingBox.maxLongitude - projectedRequestBoundingBox.minLongitude; const distanceHeight = projectedRequestBoundingBox.maxLatitude - projectedRequestBoundingBox.minLatitude; // Get the zoom level to request based upon the tile size let requestZoomLevel = null; if (this.scaling != null) { // When options are provided, get the approximate zoom level regardless of whether a tile level exists requestZoomLevel = this.tileDao.getApproximateZoomLevelForWidthAndHeight(distanceWidth, distanceHeight); } else { // Get the closest existing zoom level requestZoomLevel = this.tileDao.getZoomLevelForWidthAndHeight(distanceWidth, distanceHeight); } // If there is a matching zoom level if (requestZoomLevel != null) { let zoomLevels: number[] = []; // If options are configured, build the possible zoom levels in // order to request if (this.scaling != null && this.scaling.scaling_type != null) { // Find zoom in levels const zoomInLevels: number[] = []; if (this.scaling.isZoomIn()) { const zoomIn = this.scaling.zoom_in != null ? requestZoomLevel + this.scaling.zoom_in : this.tileDao.maxZoom; for (let zoomLevel = requestZoomLevel + 1; zoomLevel <= zoomIn; zoomLevel++) { zoomInLevels.push(zoomLevel); } } // Find zoom out levels const zoomOutLevels = []; if (this.scaling.isZoomOut()) { const zoomOut = this.scaling.zoom_out != null ? requestZoomLevel - this.scaling.zoom_out : this.tileDao.minZoom; for (let zoomLevel = requestZoomLevel - 1; zoomLevel >= zoomOut; zoomLevel--) { zoomOutLevels.push(zoomLevel); } } if (zoomInLevels.length == 0) { // Only zooming out zoomLevels = zoomOutLevels; } else if (zoomOutLevels.length == 0) { // Only zooming in zoomLevels = zoomInLevels; } else { // Determine how to order the zoom in and zoom out // levels const type = this.scaling.scaling_type; switch (type) { case TileScalingType.IN: case TileScalingType.IN_OUT: // Order zoom in levels before zoom out levels zoomLevels = zoomInLevels.concat(zoomOutLevels); break; case TileScalingType.OUT: case TileScalingType.OUT_IN: // Order zoom out levels before zoom in levels zoomLevels = zoomOutLevels.concat(zoomInLevels); break; case TileScalingType.CLOSEST_IN_OUT: case TileScalingType.CLOSEST_OUT_IN: // Alternate the zoom in and out levels let firstLevels; let secondLevels; if (type == TileScalingType.CLOSEST_IN_OUT) { // Alternate starting with zoom in firstLevels = zoomInLevels; secondLevels = zoomOutLevels; } else { // Alternate starting with zoom out firstLevels = zoomOutLevels; secondLevels = zoomInLevels; } zoomLevels = []; const maxLevels = Math.max(firstLevels.length, secondLevels.length); for (let i = 0; i < maxLevels; i++) { if (i < firstLevels.length) { zoomLevels.push(firstLevels[i]); } if (i < secondLevels.length) { zoomLevels.push(secondLevels[i]); } } break; default: throw new Error('Unsupported TileScalingType: ' + type); } } } else { zoomLevels = []; } // Always check the request zoom level first zoomLevels.unshift(requestZoomLevel); // Build a list of tile matrices that exist for the zoom levels zoomLevels.forEach(zoomLevel => { const tileMatrix = this.tileDao.getTileMatrixWithZoomLevel(zoomLevel); if (tileMatrix != null) { tileMatrices.push(tileMatrix); } }); } } return tileMatrices; } }
the_stack
import { setup } from '../../../../test/setup' import request, { Response } from 'supertest' import { INestApplication } from '@nestjs/common' import { EmailService } from '@island.is/email-service' import { EmailVerification } from '../emailVerification.model' import { SmsVerification } from '../smsVerification.model' import { SmsService } from '@island.is/nova-sms' import { IdsUserGuard, MockAuthGuard } from '@island.is/auth-nest-tools' import { UserProfileScope } from '@island.is/auth/scopes' import { SMS_VERIFICATION_MAX_TRIES } from '../verification.service' jest.useFakeTimers('modern') let app: INestApplication let emailService: EmailService let smsService: SmsService const mockProfile = { nationalId: '1234567890', locale: 'en', email: 'email@example.com', mobilePhoneNumber: '9876543', } beforeAll(async () => { app = await setup({ override: (builder) => builder.overrideGuard(IdsUserGuard).useValue( new MockAuthGuard({ nationalId: mockProfile.nationalId, scope: [UserProfileScope.read, UserProfileScope.write], }), ), }) emailService = app.get<EmailService>(EmailService) jest .spyOn(emailService, 'sendEmail') .mockImplementation(() => Promise.resolve('')) smsService = app.get<SmsService>(SmsService) jest.spyOn(smsService, 'sendSms').mockImplementation() }) describe('User profile API', () => { describe('POST /userProfile', () => { it('POST /userProfile should register userProfile with no phonenumber', async () => { // Arrange const { mobilePhoneNumber, ...sutProfile } = mockProfile // Act const spy = jest .spyOn(emailService, 'sendEmail') .mockImplementation(() => Promise.resolve('user')) const response = await request(app.getHttpServer()) .post('/userProfile') .send(sutProfile) .expect(201) expect(spy).toHaveBeenCalled() expect(response.body.id).toBeTruthy() }) it('POST /userProfile should register userProfile with no email', async () => { // Arrange const { email, ...sutProfile } = mockProfile // Act const spy = jest .spyOn(emailService, 'sendEmail') .mockImplementation(() => Promise.resolve('user')) const response = await request(app.getHttpServer()) .post('/userProfile') .send(sutProfile) .expect(201) expect(spy).toHaveBeenCalled() expect(response.body.id).toBeTruthy() }) it('POST /userProfile should register userProfile and create verification', async () => { // Act const spy = jest .spyOn(emailService, 'sendEmail') .mockImplementation(() => Promise.resolve('user')) const response = await request(app.getHttpServer()) .post('/userProfile') .send(mockProfile) .expect(201) expect(spy).toHaveBeenCalled() expect(response.body.id).toBeTruthy() const verification = await EmailVerification.findOne({ where: { nationalId: response.body.nationalId }, }) // Assert expect(verification.email).toEqual(mockProfile.email) expect(verification.nationalId).toEqual(mockProfile.nationalId) expect(response.body).toEqual( expect.objectContaining({ nationalId: verification.nationalId }), ) expect(response.body).toEqual( expect.objectContaining({ email: verification.email }), ) }) it('POST /userProfile should return conflict on existing nationalId', async () => { // Act await request(app.getHttpServer()) .post('/userProfile') .send(mockProfile) .expect(201) const conflictResponse = await request(app.getHttpServer()) .post('/userProfile') .send(mockProfile) .expect(409) // Assert expect(conflictResponse.body.error).toBe('Conflict') expect(conflictResponse.body.message).toBe( `A profile with nationalId - "${mockProfile.nationalId}" already exists`, ) }) it('POST /userProfile should return 400 bad request on invalid locale', async () => { // Act const response = await request(app.getHttpServer()) .post('/userProfile') .send({ ...mockProfile, locale: 'en123', }) .expect(400) // Assert expect(response.body.error).toBe('Bad Request') expect(response.body.message).toEqual( expect.arrayContaining(['locale must be a valid enum value']), ) }) it('POST /userProrfile should return 403 forbidden on invalid authentication', async () => { // Act await request(app.getHttpServer()) .post('/userProfile') .send({ ...mockProfile, nationalId: '0987654321', }) // Assert .expect(403) }) }) describe('GET /userProfile', () => { it('GET /userProfile should return 404 not found error msg', async () => { // Act const getResponse = await request(app.getHttpServer()) .get(`/userProfile/${mockProfile.nationalId}`) .expect(404) // Assert expect(getResponse.body.error).toBe('Not Found') expect(getResponse.body.message).toBe( `A user profile with nationalId ${mockProfile.nationalId} does not exist`, ) }) it('GET /userProfile should return profile', async () => { // Arrange await request(app.getHttpServer()).post('/userProfile').send(mockProfile) // Act const getResponse = await request(app.getHttpServer()) .get(`/userProfile/${mockProfile.nationalId}`) .expect(200) // Assert expect(getResponse.body).toEqual( expect.objectContaining({ nationalId: mockProfile.nationalId }), ) expect(getResponse.body).toEqual( expect.objectContaining({ locale: mockProfile.locale }), ) expect(getResponse.body).toEqual( expect.objectContaining({ email: mockProfile.email }), ) }) it('GET /userProfile should return 403 forbidden on invalid authentication', async () => { //Arrange const invalidNationalId = '0987654321' // Act await request(app.getHttpServer()) .get(`/userProfile/${invalidNationalId}`) // Assert .expect(403) }) }) describe('PUT /userProfile', () => { it('PUT /userProfile/ should return 404 not found error msg', async () => { // Arrange const updatedProfile = { mobilePhoneNumber: '9876543', locale: 'is', email: 'email@email.is', } // Act const updateResponse = await request(app.getHttpServer()) .put(`/userProfile/${mockProfile.nationalId}`) .send(updatedProfile) .expect(404) // Assert expect(updateResponse.body.error).toBe('Not Found') expect(updateResponse.body.message).toBe( `A user profile with nationalId ${mockProfile.nationalId} does not exist`, ) }) it('PUT /userProfile should update profile', async () => { //Arrange const updatedProfile = { locale: 'is', } await request(app.getHttpServer()).post('/userProfile').send(mockProfile) // Act const updateResponse = await request(app.getHttpServer()) .put(`/userProfile/${mockProfile.nationalId}`) .send(updatedProfile) .expect(200) // Assert expect(updateResponse.body).toEqual( expect.objectContaining({ nationalId: mockProfile.nationalId }), ) expect(updateResponse.body).toEqual( expect.objectContaining({ locale: updatedProfile.locale }), ) }) it('PUT /userProfile with email should create verification', async () => { // Arrange const spy = jest .spyOn(emailService, 'sendEmail') .mockImplementation(() => Promise.resolve('user')) await request(app.getHttpServer()) .post('/userProfile') .send({ nationalId: mockProfile.nationalId, locale: mockProfile.locale, mobilePhoneNumber: mockProfile.mobilePhoneNumber, }) .expect(201) //Act const response = await request(app.getHttpServer()) .put(`/userProfile/${mockProfile.nationalId}`) .send({ email: mockProfile.email, }) .expect(200) expect(spy).toHaveBeenCalled() expect(response.body.id).toBeTruthy() const verification = await EmailVerification.findOne({ where: { nationalId: response.body.nationalId }, }) expect(verification.email).toEqual(mockProfile.email) expect(verification.nationalId).toEqual(mockProfile.nationalId) }) it('PUT /userProfile/ should return 403 forbidden on invalid authentication', async () => { // Arrange const updatedProfile = { mobilePhoneNumber: '987654321', locale: 'is', email: 'email@email.is', } const invalidNationalId = '0987654321' // Act await request(app.getHttpServer()) .put(`/userProfile/${invalidNationalId}`) .send(updatedProfile) // Assert .expect(403) }) }) describe('POST /emailVerification', () => { it('POST /emailVerification/:nationalId re-creates an email verfication in db', async () => { // Arrange const spy = jest .spyOn(emailService, 'sendEmail') .mockImplementation(() => Promise.resolve('')) await request(app.getHttpServer()) .post('/userProfile') .send(mockProfile) .expect(201) const oldVerification = await EmailVerification.findOne({ where: { nationalId: mockProfile.nationalId }, order: [['created', 'DESC']], }) // Act await request(app.getHttpServer()) .post(`/emailVerification/${mockProfile.nationalId}`) .expect(204) const newVerification = await EmailVerification.findOne({ where: { nationalId: mockProfile.nationalId }, order: [['created', 'DESC']], }) // Assert expect(spy).toHaveBeenCalled() expect(newVerification.hash).not.toEqual(oldVerification.hash) }) it('POST /emailVerification/:nationalId returns 400 bad request on missing email', async () => { // Arrange await request(app.getHttpServer()) .post('/userProfile') .send({ nationalId: mockProfile.nationalId, locale: mockProfile.locale, }) .expect(201) // Act const response = await request(app.getHttpServer()) .post(`/emailVerification/${mockProfile.nationalId}`) // Assert .expect(400) expect(response.body.message).toBe( 'Profile does not have a configured email address.', ) }) it('POST /emailVerification/:nationalId returns 403 forbidden for invalid authentication', async () => { // Arrange const invalidNationalId = '0987654321' await request(app.getHttpServer()) .post('/userProfile') .send(mockProfile) .expect(201) // Act await request(app.getHttpServer()) .post(`/emailVerification/${invalidNationalId}`) // Assert .expect(403) }) }) describe('POST /confirmEmail', () => { it('POST /confirmEmail/ marks as confirmed', async () => { //Arrange await request(app.getHttpServer()) .post('/userProfile') .send(mockProfile) .expect(201) const verification = await EmailVerification.findOne({ where: { nationalId: mockProfile.nationalId }, }) // Act const response = await request(app.getHttpServer()) .post(`/confirmEmail/${mockProfile.nationalId}`) .send({ hash: verification.hash, }) .expect(200) // Assert expect(response.body).toEqual( expect.objectContaining({ confirmed: true }), ) }) it('POST /confirmEmail/ returns 403 forbidden for invalid authentication', async () => { //Arrange const invalidNationalId = '0987654321' await request(app.getHttpServer()) .post('/userProfile') .send(mockProfile) .expect(201) const verification = await EmailVerification.findOne({ where: { nationalId: mockProfile.nationalId }, }) // Act await request(app.getHttpServer()) .post(`/confirmEmail/${invalidNationalId}`) .send({ hash: verification.hash, }) // Assert .expect(403) }) }) describe('POST /smsVerification', () => { it('POST /smsVerification/ creates a sms verfication in db', async () => { // Act const spy = jest.spyOn(smsService, 'sendSms') await request(app.getHttpServer()) .post('/smsVerification/') .send({ nationalId: mockProfile.nationalId, mobilePhoneNumber: mockProfile.mobilePhoneNumber, }) .expect(204) expect(spy).toHaveBeenCalled() const verification = await SmsVerification.findOne({ where: { nationalId: mockProfile.nationalId }, }) // Assert expect(verification).toBeDefined() expect(verification.smsCode).toMatch(/^\d{6}$/) }) }) describe('POST /confirmSms', () => { it('POST /confirmSms/ marks as verified', async () => { // Arrange await request(app.getHttpServer()) .post('/smsVerification/') .send({ nationalId: mockProfile.nationalId, mobilePhoneNumber: mockProfile.mobilePhoneNumber, }) .expect(204) const verification = await SmsVerification.findOne({ where: { nationalId: mockProfile.nationalId }, }) // Act const response = await request(app.getHttpServer()) .post(`/confirmSms/${mockProfile.nationalId}`) .send({ code: verification.smsCode }) .expect(200) // Assert expect(response.body).toMatchInlineSnapshot(` Object { "confirmed": true, "message": "SMS confirmed", } `) }) it('POST /confirmSms/ returns 403 forbidden for invalid authentication', async () => { // Arrange const invalidNationalId = '0987654321' await request(app.getHttpServer()) .post('/smsVerification/') .send({ nationalId: mockProfile.nationalId, mobilePhoneNumber: mockProfile.mobilePhoneNumber, }) .expect(204) const verification = await SmsVerification.findOne({ where: { nationalId: mockProfile.nationalId }, }) // Act await request(app.getHttpServer()) .post(`/confirmSms/${invalidNationalId}`) .send({ code: verification.smsCode, }) // Assert .expect(403) }) it('POST /confirmSms/ returns confirmed: false for missing verifications', async () => { // Act const response = await request(app.getHttpServer()) .post(`/confirmSms/${mockProfile.nationalId}`) .send({ code: '123456' }) // Assert .expect(200) // Assert expect(response.body).toMatchInlineSnapshot(` Object { "confirmed": false, "message": "Sms verification does not exist for this user", } `) }) it('POST /confirmSms/ returns confirmed: false for expired verifications', async () => { // Arrange jest.setSystemTime(new Date(2020, 5, 1)) await request(app.getHttpServer()) .post('/smsVerification/') .send({ nationalId: mockProfile.nationalId, mobilePhoneNumber: mockProfile.mobilePhoneNumber, }) .expect(204) const verification = await SmsVerification.findOne({ where: { nationalId: mockProfile.nationalId }, }) jest.setSystemTime(new Date(2020, 5, 2)) // Act const response = await request(app.getHttpServer()) .post(`/confirmSms/${mockProfile.nationalId}`) .send({ code: verification.smsCode }) .expect(200) // Assert expect(response.body).toMatchInlineSnapshot(` Object { "confirmed": false, "message": "SMS verification is expired", } `) }) it('POST /confirmSms/ returns confirmed: false after too many tries', async () => { // Arrange await request(app.getHttpServer()) .post('/smsVerification/') .send({ nationalId: mockProfile.nationalId, mobilePhoneNumber: mockProfile.mobilePhoneNumber, }) .expect(204) const verification = await SmsVerification.findOne({ where: { nationalId: mockProfile.nationalId }, }) // Act for (let i = 0; i < SMS_VERIFICATION_MAX_TRIES; i++) { const response = await request(app.getHttpServer()) .post(`/confirmSms/${mockProfile.nationalId}`) .send({ code: '1' }) .expect(200) expect(response.body).toMatchObject({ confirmed: false, message: expect.stringMatching(/SMS code is not a match/), }) expect(response.body.message).toContain( SMS_VERIFICATION_MAX_TRIES - (i + 1), ) } const response = await request(app.getHttpServer()) .post(`/confirmSms/${mockProfile.nationalId}`) .send({ code: verification.smsCode }) .expect(200) // Assert expect(response.body).toMatchInlineSnapshot(` Object { "confirmed": false, "message": "Too many failed SMS verifications. Please restart verification.", } `) }) it('POST /confirmSms/ works after restarting a failed sms verification', async () => { // Arrange jest.setSystemTime(new Date(2020, 5, 1)) await request(app.getHttpServer()) .post('/smsVerification/') .send({ nationalId: mockProfile.nationalId, mobilePhoneNumber: mockProfile.mobilePhoneNumber, }) .expect(204) // Tried too many times. for (let i = 0; i < SMS_VERIFICATION_MAX_TRIES; i++) { await request(app.getHttpServer()) .post(`/confirmSms/${mockProfile.nationalId}`) .send({ code: '1' }) } // Expire verification. jest.setSystemTime(new Date(2020, 5, 2)) // Act - Try again await request(app.getHttpServer()) .post('/smsVerification/') .send({ nationalId: mockProfile.nationalId, mobilePhoneNumber: mockProfile.mobilePhoneNumber, }) .expect(204) const verification = await SmsVerification.findOne({ where: { nationalId: mockProfile.nationalId }, }) const response = await request(app.getHttpServer()) .post(`/confirmSms/${mockProfile.nationalId}`) .send({ code: verification.smsCode }) .expect(200) // Assert expect(response.body).toMatchInlineSnapshot(` Object { "confirmed": true, "message": "SMS confirmed", } `) }) }) })
the_stack
import * as d3 from 'd3'; import $ from 'jquery'; import _ from 'lodash'; import { StatusHeatmapCtrl } from './module'; let TOOLTIP_PADDING_X = 30; let TOOLTIP_PADDING_Y = 5; // TODO rename file to tooltip_ctrl.ts // TODO move DefaultValueDateFormat into tooltip.ts, as it used in several places (migration, partial and tooltip render) let DefaultValueDateFormat = 'YYYY/MM/DD/HH_mm_ss'; export class StatusmapTooltip { tooltip: any; scope: any; dashboard: any; panelCtrl: StatusHeatmapCtrl; panel: any; panelElem: any; mouseOverBucket: any; originalFillColor: any; tooltipWidth: number; tooltipFrozen: any; constructor(elem: any, scope: any) { this.scope = scope; this.dashboard = scope.ctrl.dashboard; this.panelCtrl = scope.ctrl; this.panel = scope.ctrl.panel; this.panelElem = elem; this.mouseOverBucket = false; this.originalFillColor = null; elem.on('mouseover', this.onMouseOver.bind(this)); elem.on('mouseleave', this.onMouseLeave.bind(this)); } onMouseOver(e) { if (!this.panel.tooltip.show || !this.scope.ctrl.data || _.isEmpty(this.scope.ctrl.data)) { return; } if (!this.tooltip) { this.add(); this.move(e, this.tooltip); } } onMouseLeave() { this.destroy(); } onMouseMove(e) { if (!this.panel.tooltip.show) { return; } this.move(e, this.tooltip); } add() { this.tooltip = d3 .select('body') .append('div') .attr('class', 'graph-tooltip statusmap-tooltip'); } destroy() { if (this.tooltip) { this.tooltip.remove(); } this.tooltip = null; } removeFrozen() { if (this.tooltipFrozen) { this.tooltipFrozen.remove(); this.tooltipFrozen = null; } } showFrozen(pos: any) { this.removeFrozen(); this.tooltipFrozen = d3 .select(this.panelElem[0]) .append('div') .attr('class', 'graph-tooltip statusmap-tooltip statusmap-tooltip-frozen'); this.displayTooltip(pos, this.tooltipFrozen, true); this.moveRelative(pos, this.tooltipFrozen); } show(pos: any) { if (!this.panel.tooltip.show || !this.tooltip) { return; } // TODO support for shared tooltip mode if (pos.panelRelY) { return; } this.displayTooltip(pos, this.tooltip, false); this.move(pos, this.tooltip); } // Retrieve bucket and create html content inside tooltip’s div element. displayTooltip(pos: any, tooltip: any, frozen: boolean) { let cardEl = d3.select(pos.target); let yid = cardEl.attr('yid'); let xid = cardEl.attr('xid'); // @ts-ignore let bucket = this.panelCtrl.bucketMatrix.get(yid, xid); // TODO string-to-number conversion for xid if (!bucket || bucket.isEmpty()) { this.destroy(); return; } let timestamp = bucket.to; let yLabel = bucket.yLabel; let pLabels = bucket.pLabels; let value = bucket.value; let values = bucket.values; // TODO create option for this formatting. let tooltipTimeFormat = 'YYYY-MM-DD HH:mm:ss'; let time: Date = this.dashboard.formatDate(+timestamp, tooltipTimeFormat); // Close button for the frozen tooltip. let tooltipClose = ``; if (frozen) { tooltipClose = ` <a class="pointer pull-right small tooltip-close"> <i class="fa fa-remove"></i> </a> `; } let tooltipHtml = `<div class="graph-tooltip-time">${time}${tooltipClose}</div>`; if (this.panel.color.mode === 'discrete') { let statuses; if (this.panel.seriesFilterIndex >= 0) { statuses = this.panelCtrl.discreteExtraSeries.convertValueToTooltips(value); } else { statuses = this.panelCtrl.discreteExtraSeries.convertValuesToTooltips(values); } let statusTitle = 'status:'; if (statuses.length > 1) { statusTitle = 'statuses:'; } tooltipHtml += ` <div> name: <b>${yLabel}</b> <br> <span>${statusTitle}</span> <ul> ${_.join( _.map( statuses, v => `<li style="background-color: ${v.color}; text-align:center" class="discrete-item">${v.tooltip}</li>` ), '' )} </ul> </div>`; } else { if (values.length === 1) { tooltipHtml += `<div> name: <b>${yLabel}</b> <br> value: <b>${value}</b> <br> </div>`; } else { tooltipHtml += `<div> name: <b>${yLabel}</b> <br> values: <ul> ${_.join( _.map(values, v => `<li>${v}</li>`), '' )} </ul> </div>`; } } tooltipHtml += `<div class="statusmap-histogram"></div>`; if (this.panel.tooltip.showItems) { // Additional information: urls, etc. // Clone additional items let items: any = JSON.parse(JSON.stringify(this.panel.tooltip.items)); let scopedVars = {}; let valueVar; for (let i = 0; i < bucket.values.length; i++) { valueVar = `__value_${i}`; scopedVars[valueVar] = { value: bucket.values[i] }; } scopedVars['__value'] = { value: bucket.value }; scopedVars['__y_label'] = { value: yLabel }; scopedVars['__y_label_trim'] = { value: yLabel.trim() }; // Grafana 7.0 compatible scopedVars['__url_time_range'] = { value: this.panelCtrl.retrieveTimeVar() }; //New vars based on partialLabels: for (let i in pLabels) { scopedVars[`__y_label_${i}`] = { value: pLabels[i] }; } for (let item of items) { if (_.isEmpty(item.urlTemplate)) { item.link = '#'; } else { let dateFormat = item.valueDateFormat; if (dateFormat === '') { dateFormat = DefaultValueDateFormat; } let valueDateVar; for (let i = 0; i < bucket.values.length; i++) { valueDateVar = `__value_${i}_date`; scopedVars[valueDateVar] = { value: this.dashboard.formatDate(+bucket.values[i], dateFormat) }; } scopedVars['__value_date'] = { value: this.dashboard.formatDate(+bucket.value, dateFormat) }; item.link = this.panelCtrl.templateSrv.replace(item.urlTemplate, scopedVars); // Force lowercase for link if (item.urlToLowerCase) { item.link = item.link.toLowerCase(); } } item.label = item.urlText; if (_.isEmpty(item.label)) { item.label = _.isEmpty(item.urlTemplate) ? 'Empty URL' : _.truncate(item.link); } } if (this.panel.tooltip.showCustomContent) { let customContent: string = this.panelCtrl.templateSrv.replace(this.panel.tooltip.customContent, scopedVars); tooltipHtml += `<div>${customContent}</div>`; } tooltipHtml += _.join( _.map( items, v => ` <div> <a href="${v.link}" target="_blank"> <div class="dashlist-item"> <p class="dashlist-link dashlist-link-dash-db"> <span style="word-wrap: break-word;" class="dash-title">${v.label}</span><span class="dashlist-star"> <i class="fa fa-${v.urlIcon}"></i> </span></p> </div></a><div>` ), '\n' ); } // Ambiguous state: there multiple values in bucket! // TODO rename useMax to expectMultipleValues if (!this.panel.useMax && bucket.multipleValues) { tooltipHtml += `<div><b>Error:</b> ${this.panelCtrl.dataWarnings.multipleValues.title}</div>`; } // Discrete mode errors if (this.panel.color.mode === 'discrete') { if (bucket.noColorDefined) { let badValues = this.panelCtrl.discreteExtraSeries.getNotColoredValues(values); tooltipHtml += `<div><b>Error:</b> ${this.panelCtrl.dataWarnings.noColorDefined.title} <br>not colored values: <ul> ${_.join( _.map(badValues, v => `<li>${v}</li>`), '' )} </ul> </div>`; } } tooltip.html(tooltipHtml); // Assign mouse event handlers for "frozen" tooltip. if (frozen) { // Stop propagation mouse events up to parents to allow interaction with frozen tooltip’s elements. tooltip .on('click', function() { // @ts-ignore d3.event.stopPropagation(); }) .on('mousedown', function() { // @ts-ignore d3.event.stopPropagation(); }) .on('mouseup', function() { // @ts-ignore d3.event.stopPropagation(); }); // Activate close button tooltip.select('a.tooltip-close').on('click', this.removeFrozen.bind(this)); } } // Move tooltip as absolute positioned element. move(pos, tooltip) { if (!tooltip) { return; } let elem = $(tooltip.node())[0]; let tooltipWidth = elem.clientWidth; this.tooltipWidth = tooltipWidth; let tooltipHeight = elem.clientHeight; let left = pos.pageX + TOOLTIP_PADDING_X; let top = pos.pageY + TOOLTIP_PADDING_Y; if (pos.pageX + tooltipWidth + 40 > window.innerWidth) { left = pos.pageX - tooltipWidth - TOOLTIP_PADDING_X; } if (pos.pageY - window.pageYOffset + tooltipHeight + 20 > window.innerHeight) { top = pos.pageY - tooltipHeight - TOOLTIP_PADDING_Y; } return tooltip.style('left', left + 'px').style('top', top + 'px'); } // Move tooltip relative to svg element of panel. moveRelative(pos, tooltip) { if (!tooltip) { return; } let panelX = pos.pageX - this.panelElem.offset().left; let panelY = pos.pageY - this.panelElem.offset().top; let panelWidth = this.panelElem.width(); let panelHeight = this.panelElem.height(); // 'position: relative' sets tooltip’s width to 100% of panel element. // Restore width from floating tooltip and add more space for 'Close' button. let tooltipWidth = this.tooltipWidth + 25; // Left property is clamped so tooltip stays inside panel bound box. let tooltipLeft = panelX + TOOLTIP_PADDING_X; if (tooltipLeft + tooltipWidth > panelWidth) { tooltipLeft = panelWidth - tooltipWidth; } if (tooltipLeft < 0) { tooltipLeft = 0; } // Frozen tooltip’s root element is appended next to panel’s svg element, // so top property is adjusted to move tooltip’s root element // up to the mouse pointer position. let tooltipTop = -(panelHeight - panelY + TOOLTIP_PADDING_Y); return tooltip .style('left', tooltipLeft + 'px') .style('top', tooltipTop + 'px') .style('width', tooltipWidth + 'px'); } }
the_stack
// $ExpectError VK.init(); // $ExpectError VK.init({}); // $ExpectError VK.init({ apiId: '123' }); VK.init({ apiId: 123 }); VK.init({ apiId: 123, onlyWidgets: '123', // $ExpectError }); VK.init({ apiId: 123, onlyWidgets: true }); VK.init({ apiId: 123, onlyWidgets: true, status: '', // $ExpectError }); VK.init({ apiId: 123, onlyWidgets: true, status: false }); // ---------------------------------------------------------------------------- // Auth // $ExpectError VK.Auth(); // $ExpectError VK.Auth.login(); // $ExpectError VK.Auth.login(() => {}); VK.Auth.login(status => { // $ExpectType LoginStatus status; // $ExpectType "connected" | "not_authorized" | "unknown" status.status; // $ExpectType Session status.session; // $ExpectType number status.session.expire; // $ExpectType number status.session.mid; // $ExpectType string status.session.secret; // $ExpectType string status.session.sid; // $ExpectType string status.session.sig; // $ExpectType string status.session.user.id; // $ExpectType string status.session.user.href; // $ExpectType string status.session.user.domain; // $ExpectType string status.session.user.first_name; // $ExpectType string status.session.user.last_name; // $ExpectType string status.session.user.nickname; }, 100); // $ExpectError VK.Auth.logout(); VK.Auth.logout(() => {}); VK.Auth.logout( () => {}, // $ExpectError 100, ); VK.Auth.logout(status => { // $ExpectType EmptyLoginStatus status; // $ExpectType null status.session; // $ExpectType "unknown" status.status; // $ExpectType undefined status.settings; }); // $ExpectError VK.Auth.revokeGrants(); VK.Auth.revokeGrants(() => {}); VK.Auth.revokeGrants( () => {}, // $ExpectError 100, ); VK.Auth.revokeGrants(status => { // $ExpectType EmptyLoginStatus status; // $ExpectType null status.session; // $ExpectType "unknown" status.status; // $ExpectType undefined status.settings; }); // $ExpectError VK.Auth.getLoginStatus(); VK.Auth.getLoginStatus(() => {}); VK.Auth.getLoginStatus( () => {}, // $ExpectError 100, ); VK.Auth.getLoginStatus(status => { // $ExpectType LoginStatus status; }); // $ExpectError VK.Auth.getSession(); VK.Auth.getSession(() => {}); VK.Auth.getSession( () => {}, // $ExpectError 100, ); VK.Auth.getSession(session => { // $ExpectType Session session; // $ExpectType number session.expire; // $ExpectType number session.mid; // $ExpectType string session.secret; // $ExpectType string session.sid; // $ExpectType string session.sig; // $ExpectType string session.user.id; // $ExpectType string session.user.href; // $ExpectType string session.user.domain; // $ExpectType string session.user.first_name; // $ExpectType string session.user.last_name; // $ExpectType string session.user.nickname; }); // ---------------------------------------------------------------------------- // Api // $ExpectError VK.Api(); // $ExpectError VK.Api.call(); // $ExpectError VK.Api.call('method'); // $ExpectError VK.Api.call('method', {}); VK.Api.call( 'method', {}, // $ExpectError (data: any) => {}, ); VK.Api.call('method', { v: '5' }, (data: any) => {}); // ---------------------------------------------------------------------------- // Widgets // $ExpectError VK.Widgets(); // ---------------------------------------------------------------------------- // Widgets.ContactUs // $ExpectError VK.Widgets.ContactUs(); // $ExpectError VK.Widgets.ContactUs('test'); // $ExpectError VK.Widgets.ContactUs('test', undefined); VK.Widgets.ContactUs('test', undefined, 10); VK.Widgets.ContactUs('test', {}, 10); VK.Widgets.ContactUs( 'test', // $ExpectError { height: 100 }, 10, ); VK.Widgets.ContactUs( 'test', // $ExpectError { text: 123 }, 10, ); VK.Widgets.ContactUs( 'test', { height: 22, text: 'text', }, 10, ); // ---------------------------------------------------------------------------- // Widgets.Comments // $ExpectError VK.Widgets.Comments(); // $ExpectError VK.Widgets.Comments(123); // $ExpectError VK.Widgets.Comments(null); // $ExpectError VK.Widgets.Comments(() => 'test'); // $ExpectError VK.Widgets.Comments({}); VK.Widgets.Comments('test'); VK.Widgets.Comments('test', undefined); VK.Widgets.Comments( 'test', undefined, 10, // $ExpectError ); VK.Widgets.Comments( 'test', {}, 10, // $ExpectError ); VK.Widgets.Comments( 'test', // $ExpectError { width: '111', height: '222', limit: 'no', attach: 111, autoPublish: 3, norealtime: 'zzz', pageUrl: () => void 0 }, ); VK.Widgets.Comments( 'test', // $ExpectError { width: null, height: {}, limit: () => 1, attach: {}, autoPublish: 'zzz', norealtime: 200, pageUrl: 1234 }, ); VK.Widgets.Comments('test', { width: 100, height: 10, limit: 4, attach: 'test', autoPublish: 0, norealtime: 1, pageUrl: '/page', }); // ---------------------------------------------------------------------------- // Widgets.Post // $ExpectError VK.Widgets.Post(); // $ExpectError VK.Widgets.Post(null); // $ExpectError VK.Widgets.Post(false); // $ExpectError VK.Widgets.Post(true); // $ExpectError VK.Widgets.Post(123); // $ExpectError VK.Widgets.Post('test'); // $ExpectError VK.Widgets.Post({}); // $ExpectError VK.Widgets.Post(() => '111'); // $ExpectError VK.Widgets.Post('test', 100); // $ExpectError VK.Widgets.Post('test', '100'); // $ExpectError VK.Widgets.Post('test', true); // $ExpectError VK.Widgets.Post('test', false); VK.Widgets.Post('test', 100, 20, 'hash'); VK.Widgets.Post( 'test', 100, 20, 'hash', // $ExpectError { width: 'test' }, ); VK.Widgets.Post( 'test', 100, 20, 'hash', // $ExpectError { width: true }, ); VK.Widgets.Post( 'test', 100, 20, 'hash', // $ExpectError { width: false }, ); VK.Widgets.Post( 'test', 100, 20, 'hash', // $ExpectError { width: {} }, ); VK.Widgets.Post( 'test', 100, 20, 'hash', // $ExpectError { width: () => 100 }, ); VK.Widgets.Post('test', 100, 20, 'hash', { width: 100 }); // ---------------------------------------------------------------------------- // Widgets.Group // $ExpectError VK.Widgets.Group(); // $ExpectError VK.Widgets.Group('test'); // $ExpectError VK.Widgets.Group('test', undefined); // $ExpectError VK.Widgets.Group('test', undefined, '100'); // $ExpectError VK.Widgets.Group('test', undefined, {}); VK.Widgets.Group('test', undefined, 100); VK.Widgets.Group( 'test', // $ExpectError { width: 'test', no_cover: 'false', wide: 'wat', color1: 111, color2: 222, color3: 333, mode: 1, height: 333 }, 100, ); VK.Widgets.Group( 'test', { width: 100, no_cover: 1, wide: 0, color1: 'dc143f', color2: '2196f3', color3: 'ff639f', mode: 4, height: 100, }, 100, ); // ---------------------------------------------------------------------------- // Widgets.Like // $ExpectError VK.Widgets.Like(); // $ExpectError VK.Widgets.Like(null); // $ExpectError VK.Widgets.Like(true); // $ExpectError VK.Widgets.Like(false); // $ExpectError VK.Widgets.Like(111); VK.Widgets.Like('test'); VK.Widgets.Like('test', {}); VK.Widgets.Like( 'test', // $ExpectError { height: 100, verb: 3, pageTitle: 123, pageUrl: true, pageImage: null }, ); VK.Widgets.Like( 'test', // $ExpectError { height: '30', verb: 'test', pageTitle: false, pageUrl: {}, pageImage: () => void 0 }, ); VK.Widgets.Like('test', { height: 20, verb: 1, pageTitle: 'hk4', pageUrl: '/dt', pageImage: 'path/to/some/image.png', }); // ---------------------------------------------------------------------------- // Widgets.Recommended // $ExpectError VK.Widgets.Recommended(); // $ExpectError VK.Widgets.Recommended(123); // $ExpectError VK.Widgets.Recommended(null); // $ExpectError VK.Widgets.Recommended(undefined); // $ExpectError VK.Widgets.Recommended({}); VK.Widgets.Recommended('element'); VK.Widgets.Recommended( 'element', // $ExpectError { limit: 'test', max: 'no', period: 'never' }, ); VK.Widgets.Recommended( 'element', // $ExpectError { limit: false, max: true, period: 10 }, ); VK.Widgets.Recommended('element', { limit: 5, max: 10, period: 'day', }); // $ExpectError VK.Widgets.Recommended('element', {}, false); // $ExpectError VK.Widgets.Recommended('element', {}, ''); // $ExpectError VK.Widgets.Recommended('element', {}, 123); // $ExpectError VK.Widgets.Recommended('element', {}, null); VK.Widgets.Recommended('element', {}, 0); VK.Widgets.Recommended('element', {}, 1); // $ExpectError VK.Widgets.Recommended('element', {}, 0, 'wat'); // $ExpectError VK.Widgets.Recommended('element', {}, 0, 1); // $ExpectError VK.Widgets.Recommended('element', {}, 0, true); // $ExpectError VK.Widgets.Recommended('element', {}, 0, {}); VK.Widgets.Recommended('element', {}, 0, 'likes'); VK.Widgets.Recommended('element', {}, 0, 'friend_likes'); // $ExpectError VK.Widgets.Recommended('element', {}, 0, 'likes', '/dev/null'); // $ExpectError VK.Widgets.Recommended('element', {}, 0, 'likes', 100); // $ExpectError VK.Widgets.Recommended('element', {}, 0, 'likes', true); // $ExpectError VK.Widgets.Recommended('element', {}, 0, 'likes', {}); // $ExpectError VK.Widgets.Recommended('element', {}, 0, 'likes', {}); // $ExpectError VK.Widgets.Recommended('element', {}, 0, 'likes', null); VK.Widgets.Recommended('element', {}, 0, 'likes', 'blank'); VK.Widgets.Recommended('element', {}, 0, 'likes', 'parent'); VK.Widgets.Recommended('element', {}, 0, 'likes', 'top'); // ---------------------------------------------------------------------------- // Widgets.Poll // $ExpectError VK.Widgets.Poll(); // $ExpectError VK.Widgets.Poll('test'); // $ExpectError VK.Widgets.Poll(123); // $ExpectError VK.Widgets.Poll(false); // $ExpectError VK.Widgets.Poll({}); // $ExpectError VK.Widgets.Poll(null); VK.Widgets.Poll( 'blackHole', {}, 100, // $ExpectError ); VK.Widgets.Poll( 'darling', {}, {}, // $ExpectError ); VK.Widgets.Poll( 'blackHole', {}, false, // $ExpectError ); VK.Widgets.Poll('wiredLife', {}, 'poll'); VK.Widgets.Poll( 'wiredLife', // $ExpectError { pageUrl: 123, width: '123' }, 'poll', ); VK.Widgets.Poll( 'wiredLife', // $ExpectError { pageUrl: false, width: () => 123 }, 'poll', ); VK.Widgets.Poll( 'wiredLife', // $ExpectError { pageUrl: false, width: null }, 'poll', ); VK.Widgets.Poll( 'wiredLife', { pageUrl: '/harmony', width: 100, }, 'poll', ); // ---------------------------------------------------------------------------- // Widgets.Auth // $ExpectError VK.Widgets.Auth(); // $ExpectError VK.Widgets.Auth(123); // $ExpectError VK.Widgets.Auth(null); // $ExpectError VK.Widgets.Auth(true); VK.Widgets.Auth('auth'); VK.Widgets.Auth( 'auth', // $ExpectError { authUrl: 123, onAuth: () => void 0, width: 'some' }, ); VK.Widgets.Auth('auth', { authUrl: '/mya/nee', width: 100, }); VK.Widgets.Auth('auth', { onAuth: authData => { // $ExpectType AuthUserData authData; // $ExpectType number authData.uid; // $ExpectType string authData.first_name; // $ExpectType string authData.last_name; // $ExpectType string authData.photo; // $ExpectType string authData.photo_rec; // $ExpectType string authData.hash; }, width: 100, }); // ---------------------------------------------------------------------------- // Widgets.Subscribe // $ExpectError VK.Widgets.Subscribe(); // $ExpectError VK.Widgets.Subscribe(null); // $ExpectError VK.Widgets.Subscribe(false); // $ExpectError VK.Widgets.Subscribe(123); // $ExpectError VK.Widgets.Subscribe('subber'); // $ExpectError VK.Widgets.Subscribe('element', 123); // $ExpectError VK.Widgets.Subscribe('element', false); // $ExpectError VK.Widgets.Subscribe('element', 'zsh'); VK.Widgets.Subscribe( 'element', {}, null, // $ExpectError ); VK.Widgets.Subscribe( 'element', {}, 'user', // $ExpectError ); VK.Widgets.Subscribe( 'element', {}, false, // $ExpectError ); VK.Widgets.Subscribe( 'element', {}, () => 123, // $ExpectError ); VK.Widgets.Subscribe('element', {}, 123); VK.Widgets.Subscribe( 'element', // $ExpectError { mode: 3, soft: 'test' }, 123, ); VK.Widgets.Subscribe( 'element', // $ExpectError { mode: null, soft: {} }, 123, ); VK.Widgets.Subscribe( 'element', // $ExpectError { mode: () => 1, soft: false }, 123, ); VK.Widgets.Subscribe( 'element', { mode: 0, soft: 1, }, 123, ); // ---------------------------------------------------------------------------- // Widgets.CommunityMessages // $ExpectError VK.Widgets.CommunityMessages(); // $ExpectError VK.Widgets.CommunityMessages(null); // $ExpectError VK.Widgets.CommunityMessages(1); // $ExpectError VK.Widgets.CommunityMessages(false); // $ExpectError VK.Widgets.CommunityMessages(true); // $ExpectError VK.Widgets.CommunityMessages({}); // $ExpectError VK.Widgets.CommunityMessages('test'); VK.Widgets.CommunityMessages( 'test', // $ExpectError {}, ); VK.Widgets.CommunityMessages( 'test', // $ExpectError null, ); VK.Widgets.CommunityMessages( 'test', // $ExpectError true, ); VK.Widgets.CommunityMessages( 'test', // $ExpectError false, ); VK.Widgets.CommunityMessages( 'test', // $ExpectError 'zxc', ); VK.Widgets.CommunityMessages('test', 123); VK.Widgets.CommunityMessages('test', 123, {}); VK.Widgets.CommunityMessages('test', 123, { onCanNotWrite: reason => { // $ExpectType: 'offline' | 'no_access' | 'disabled_messages' | 'cant_write' reason; }, welcomeScreen: 0, expandTimeout: 100, widgetPosition: '', buttonType: '', tooltipButtonText: '', }); VK.Widgets.CommunityMessages('test', 123, { expanded: 1, disableButtonTooltip: 1, disableNewMessagesSound: 1, disableExpandChatSound: 1, disableTitleChange: 1, }); VK.Widgets.CommunityMessages( 'test', 123, // prettier-ignore // $ExpectError { expanded: 0, disableButtonTooltip: 0, disableNewMessagesSound: 0, disableExpandChatSound: 0, disableTitleChange: 0 }, ); // ---------------------------------------------------------------------------- // Widgets.Playlist // $ExpectError VK.Widgets.Playlist(); // $ExpectError VK.Widgets.Playlist('element'); // $ExpectError VK.Widgets.Playlist('element', 1); // $ExpectError VK.Widgets.Playlist('element', 1, 10); VK.Widgets.Playlist( // $ExpectError null, 1, 10, 'hash', ); VK.Widgets.Playlist( // $ExpectError true, 1, 10, 'hash', ); VK.Widgets.Playlist( // $ExpectError false, 1, 10, 'hash', ); VK.Widgets.Playlist( // $ExpectError 123, 1, 10, 'hash', ); VK.Widgets.Playlist( // $ExpectError {}, 1, 10, 'hash', ); VK.Widgets.Playlist( // $ExpectError () => void 0, 1, 10, 'hash', ); VK.Widgets.Playlist( 'element', // $ExpectError null, 10, 'hash', ); VK.Widgets.Playlist( 'element', // $ExpectError true, 10, 'hash', ); VK.Widgets.Playlist( 'element', // $ExpectError false, 10, 'hash', ); VK.Widgets.Playlist( 'element', // $ExpectError 'true', 10, 'hash', ); VK.Widgets.Playlist( 'element', // $ExpectError () => void 0, 10, 'hash', ); VK.Widgets.Playlist( 'element', // $ExpectError {}, 10, 'hash', ); VK.Widgets.Playlist( 'element', 1, // $ExpectError null, 'hash', ); VK.Widgets.Playlist( 'element', 1, // $ExpectError true, 'hash', ); VK.Widgets.Playlist( 'element', 1, // $ExpectError false, 'hash', ); VK.Widgets.Playlist( 'element', 1, // $ExpectError {}, 'hash', ); VK.Widgets.Playlist( 'element', 1, // $ExpectError '', 'hash', ); VK.Widgets.Playlist( 'element', 1, // $ExpectError () => 123, 'hash', ); VK.Widgets.Playlist( 'element', 1, 10, // $ExpectError null, ); VK.Widgets.Playlist( 'element', 1, 10, // $ExpectError true, ); VK.Widgets.Playlist( 'element', 1, 10, // $ExpectError false, ); VK.Widgets.Playlist( 'element', 1, 10, // $ExpectError 123, ); VK.Widgets.Playlist( 'element', 1, 10, // $ExpectError {}, ); VK.Widgets.Playlist( 'element', 1, 10, // $ExpectError () => '', ); VK.Widgets.Playlist('element', 1, 10, 'hash'); VK.Widgets.Playlist('element', 1, 10, 'hash', {}); VK.Widgets.Playlist( 'element', 1, 10, 'hash', // $ExpectError { width: null }, ); VK.Widgets.Playlist( 'element', 1, 10, 'hash', // $ExpectError { width: true }, ); VK.Widgets.Playlist( 'element', 1, 10, 'hash', // $ExpectError { width: false }, ); VK.Widgets.Playlist( 'element', 1, 10, 'hash', // $ExpectError { width: '123' }, ); VK.Widgets.Playlist( 'element', 1, 10, 'hash', // $ExpectError { width: {} }, ); VK.Widgets.Playlist( 'element', 1, 10, 'hash', // $ExpectError { width: () => 213 }, ); VK.Widgets.Playlist('element', 1, 10, 'hash', { width: 100 }); // ---------------------------------------------------------------------------- // Widgets.AllowMessagesFromCommunity // $ExpectError VK.Widgets.AllowMessagesFromCommunity(); // $ExpectError VK.Widgets.AllowMessagesFromCommunity('element'); // $ExpectError VK.Widgets.AllowMessagesFromCommunity('element', {}); VK.Widgets.AllowMessagesFromCommunity('element', null, 1); VK.Widgets.AllowMessagesFromCommunity('element', undefined, 1); VK.Widgets.AllowMessagesFromCommunity('element', {}, 1); VK.Widgets.AllowMessagesFromCommunity( // $ExpectError null, {}, 1, ); VK.Widgets.AllowMessagesFromCommunity( // $ExpectError true, {}, 1, ); VK.Widgets.AllowMessagesFromCommunity( // $ExpectError false, {}, 1, ); VK.Widgets.AllowMessagesFromCommunity( // $ExpectError 123, {}, 1, ); VK.Widgets.AllowMessagesFromCommunity( // $ExpectError {}, {}, 1, ); VK.Widgets.AllowMessagesFromCommunity( // $ExpectError () => '', {}, 1, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError '', 1, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError true, 1, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError false, 1, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError 1, 1, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError () => {}, 1, ); VK.Widgets.AllowMessagesFromCommunity( 'element', {}, // $ExpectError null, ); VK.Widgets.AllowMessagesFromCommunity( 'element', {}, // $ExpectError true, ); VK.Widgets.AllowMessagesFromCommunity( 'element', {}, // $ExpectError false, ); VK.Widgets.AllowMessagesFromCommunity( 'element', {}, // $ExpectError '', ); VK.Widgets.AllowMessagesFromCommunity( 'element', {}, // $ExpectError {}, ); VK.Widgets.AllowMessagesFromCommunity( 'element', {}, // $ExpectError () => 123, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError { height: null }, 100, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError { height: true }, 100, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError { height: false }, 100, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError { height: 100 }, 100, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError { height: {} }, 100, ); VK.Widgets.AllowMessagesFromCommunity( 'element', // $ExpectError { height: {} }, 100, ); VK.Widgets.AllowMessagesFromCommunity('element', { height: 22 }, 100); VK.Widgets.AllowMessagesFromCommunity('element', { height: 24 }, 100); VK.Widgets.AllowMessagesFromCommunity('element', { height: 30 }, 100); // ---------------------------------------------------------------------------- // Widgets.App // $ExpectError VK.Widgets.App(); // $ExpectError VK.Widgets.App('element'); VK.Widgets.App('element', 100); VK.Widgets.App( // $ExpectError null, 100, ); VK.Widgets.App( // $ExpectError true, 100, ); VK.Widgets.App( // $ExpectError false, 100, ); VK.Widgets.App( // $ExpectError 123, 100, ); VK.Widgets.App( // $ExpectError {}, 100, ); VK.Widgets.App( // $ExpectError () => '', 100, ); VK.Widgets.App( 'element', // $ExpectError null, ); VK.Widgets.App( 'element', // $ExpectError true, ); VK.Widgets.App( 'element', // $ExpectError false, ); VK.Widgets.App( 'element', // $ExpectError '', ); VK.Widgets.App( 'element', // $ExpectError {}, ); VK.Widgets.App( 'element', // $ExpectError () => 123, ); VK.Widgets.App('element', 100, {}); VK.Widgets.App( 'element', 100, // $ExpectError { height: null }, ); VK.Widgets.App( 'element', 100, // $ExpectError { height: true }, ); VK.Widgets.App( 'element', 100, // $ExpectError { height: false }, ); VK.Widgets.App( 'element', 100, // $ExpectError { height: '' }, ); VK.Widgets.App( 'element', 100, // $ExpectError { height: {} }, ); VK.Widgets.App( 'element', 100, // $ExpectError { height: () => 123 }, ); VK.Widgets.App( 'element', 100, // $ExpectError { mode: null }, ); VK.Widgets.App( 'element', 100, // $ExpectError { mode: true }, ); VK.Widgets.App( 'element', 100, // $ExpectError { mode: false }, ); VK.Widgets.App( 'element', 100, // $ExpectError { mode: {} }, ); VK.Widgets.App( 'element', 100, // $ExpectError { mode: '' }, ); VK.Widgets.App( 'element', 100, // $ExpectError { mode: () => 1 }, ); VK.Widgets.App('element', 100, { mode: 1 }); VK.Widgets.App('element', 100, { mode: 2 }); VK.Widgets.App('element', 100, { mode: 3 }); VK.Widgets.App('element', 100, { height: 100, mode: 1 }); VK.Widgets.App('element', 100, { height: 100, mode: 2 }); VK.Widgets.App('element', 100, { height: 100, mode: 3 }); // ---------------------------------------------------------------------------- // Widgets.Article // $ExpectError VK.Widgets.Article(); // $ExpectError VK.Widgets.Article('element'); VK.Widgets.Article('element', 'article'); VK.Widgets.Article( // $ExpectError null, 'article', ); VK.Widgets.Article( // $ExpectError true, 'article', ); VK.Widgets.Article( // $ExpectError false, 'article', ); VK.Widgets.Article( // $ExpectError 100, 'article', ); VK.Widgets.Article( // $ExpectError {}, 'article', ); VK.Widgets.Article( // $ExpectError () => '', 'article', ); VK.Widgets.Article( 'element', // $ExpectError null, ); VK.Widgets.Article( 'element', // $ExpectError true, ); VK.Widgets.Article( 'element', // $ExpectError false, ); VK.Widgets.Article( 'element', // $ExpectError 100, ); VK.Widgets.Article( 'element', // $ExpectError {}, ); VK.Widgets.Article( 'element', // $ExpectError () => '', ); // ---------------------------------------------------------------------------- // Widgets.Bookmarks // $ExpectError VK.Widgets.Bookmarks(); VK.Widgets.Bookmarks('element'); VK.Widgets.Bookmarks( // $ExpectError null, ); VK.Widgets.Bookmarks( // $ExpectError true, ); VK.Widgets.Bookmarks( // $ExpectError false, ); VK.Widgets.Bookmarks( // $ExpectError 100, ); VK.Widgets.Bookmarks( // $ExpectError {}, ); VK.Widgets.Bookmarks( // $ExpectError () => '', ); VK.Widgets.Bookmarks('element', {}); VK.Widgets.Bookmarks( 'element', // $ExpectError { height: 100 }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { height: null }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { height: false }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { height: true }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { height: '' }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { height: {} }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { height: () => 18 }, ); VK.Widgets.Bookmarks('element', { height: 18 }); VK.Widgets.Bookmarks('element', { height: 20 }); VK.Widgets.Bookmarks('element', { height: 22 }); VK.Widgets.Bookmarks('element', { height: 24 }); VK.Widgets.Bookmarks('element', { height: 30 }); VK.Widgets.Bookmarks( 'element', // $ExpectError { url: null }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { url: true }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { url: false }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { url: 100 }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { url: {} }, ); VK.Widgets.Bookmarks( 'element', // $ExpectError { url: () => '' }, ); VK.Widgets.Bookmarks('element', { url: '/doggo' }); // ---------------------------------------------------------------------------- // Widgets.Podcast // $ExpectError VK.Widgets.Podcast(); // $ExpectError VK.Widgets.Podcast('element'); // $ExpectError VK.Widgets.Podcast('element', 'episode'); VK.Widgets.Podcast('element', 'episode', 'hash'); VK.Widgets.Podcast( // $ExpectError null, 'episode', 'hash', ); VK.Widgets.Podcast( // $ExpectError true, 'episode', 'hash', ); VK.Widgets.Podcast( // $ExpectError false, 'episode', 'hash', ); VK.Widgets.Podcast( // $ExpectError 100, 'episode', 'hash', ); VK.Widgets.Podcast( // $ExpectError {}, 'episode', 'hash', ); VK.Widgets.Podcast( // $ExpectError () => '', 'episode', 'hash', ); VK.Widgets.Podcast( 'element', // $ExpectError null, 'hash', ); VK.Widgets.Podcast( 'element', // $ExpectError true, 'hash', ); VK.Widgets.Podcast( 'element', // $ExpectError false, 'hash', ); VK.Widgets.Podcast( 'element', // $ExpectError 100, 'hash', ); VK.Widgets.Podcast( 'element', // $ExpectError {}, 'hash', ); VK.Widgets.Podcast( 'element', // $ExpectError () => '', 'hash', ); VK.Widgets.Podcast( 'element', 'episode', // $ExpectError null, ); VK.Widgets.Podcast( 'element', 'episode', // $ExpectError true, ); VK.Widgets.Podcast( 'element', 'episode', // $ExpectError false, ); VK.Widgets.Podcast( 'element', 'episode', // $ExpectError 100, ); VK.Widgets.Podcast( 'element', 'episode', // $ExpectError {}, ); VK.Widgets.Podcast( 'element', 'episode', // $ExpectError () => '', ); // ---------------------------------------------------------------------------- // Observer // $ExpectError VK.Observer(); // $ExpectError VK.Observer.subscribe(); // $ExpectError VK.Observer.unsubscribe(); // $ExpectError VK.Observer.unsubscribe(); // $ExpectError VK.Observer.subscribe('event.not.found'); // $ExpectError VK.Observer.subscribe('event.not.found', () => void 0); // $ExpectError VK.Observer.unsubscribe('404'); // $ExpectError VK.Observer.subscribe('auth.login', data => { data; }); // $ExpectError VK.Observer.subscribe('auth.logout', data => { data; }); // $ExpectError VK.Observer.subscribe('auth.statusChange', data => { data; }); // $ExpectError VK.Observer.subscribe('auth.sessionChange', data => { data; }); VK.Observer.subscribe('widgets.comments.new_comment', (num, lc, date, sign) => { // $ExpectType number num; // $ExpectType string lc; // $ExpectType string date; // $ExpectType string sign; }); VK.Observer.subscribe('widgets.comments.delete_comment', (num, lc, date, sign) => { // $ExpectType number num; // $ExpectType string lc; // $ExpectType string date; // $ExpectType string sign; }); // $ExpectError VK.Observer.subscribe('widgets.groups.joined', data => { data; }); // $ExpectError VK.Observer.subscribe('widgets.groups.leaved', data => { data; }); VK.Observer.subscribe('widgets.like.liked', likes => { // $ExpectType number likes; }); VK.Observer.subscribe('widgets.like.unliked', likes => { // $ExpectType number likes; }); VK.Observer.subscribe('widgets.like.shared', shares => { // $ExpectType number shares; }); VK.Observer.subscribe('widgets.like.unshared', shares => { // $ExpectType number shares; }); // $ExpectError VK.Observer.subscribe('widgets.subscribed', data => { data; }); // $ExpectError VK.Observer.subscribe('widgets.unsubscribed', data => { data; }); VK.Observer.subscribe('widgets.allowMessagesFromCommunity.allowed', data => { // $ExpectType number data; }); VK.Observer.subscribe('widgets.allowMessagesFromCommunity.denied', data => { // $ExpectType number data; }); VK.Observer.unsubscribe('auth.login'); VK.Observer.unsubscribe('auth.logout'); VK.Observer.unsubscribe('auth.statusChange'); VK.Observer.unsubscribe('auth.sessionChange'); VK.Observer.unsubscribe('widgets.comments.new_comment'); VK.Observer.unsubscribe('widgets.comments.delete_comment'); VK.Observer.unsubscribe('widgets.groups.joined'); VK.Observer.unsubscribe('widgets.groups.leaved'); VK.Observer.unsubscribe('widgets.like.liked'); VK.Observer.unsubscribe('widgets.like.unliked'); VK.Observer.unsubscribe('widgets.like.shared'); VK.Observer.unsubscribe('widgets.like.unshared'); VK.Observer.unsubscribe('widgets.subscribed'); VK.Observer.unsubscribe('widgets.unsubscribed'); VK.Observer.unsubscribe('widgets.allowMessagesFromCommunity.allowed'); VK.Observer.unsubscribe('widgets.allowMessagesFromCommunity.denied'); declare function handler(): void; VK.Observer.unsubscribe('auth.login', handler); VK.Observer.unsubscribe('auth.logout', handler); VK.Observer.unsubscribe('auth.statusChange', handler); VK.Observer.unsubscribe('auth.sessionChange', handler); VK.Observer.unsubscribe('widgets.comments.new_comment', handler); VK.Observer.unsubscribe('widgets.comments.delete_comment', handler); VK.Observer.unsubscribe('widgets.groups.joined', handler); VK.Observer.unsubscribe('widgets.groups.leaved', handler); VK.Observer.unsubscribe('widgets.like.liked', handler); VK.Observer.unsubscribe('widgets.like.unliked', handler); VK.Observer.unsubscribe('widgets.like.shared', handler); VK.Observer.unsubscribe('widgets.like.unshared', handler); VK.Observer.unsubscribe('widgets.subscribed', handler); VK.Observer.unsubscribe('widgets.unsubscribed', handler); VK.Observer.unsubscribe('widgets.allowMessagesFromCommunity.allowed', handler); VK.Observer.unsubscribe('widgets.allowMessagesFromCommunity.denied', handler); // ---------------------------------------------------------------------------- // Retargeting // $ExpectError VK.Retargeting(); // ---------------------------------------------------------------------------- // Retargeting.Init // $ExpectError VK.Retargeting.Init(); // $ExpectError VK.Retargeting.Init(null); // $ExpectError VK.Retargeting.Init(123); // $ExpectError VK.Retargeting.Init(true); // $ExpectError VK.Retargeting.Init(false); // $ExpectError VK.Retargeting.Init({}); VK.Retargeting.Init('some code'); // ---------------------------------------------------------------------------- // Retargeting.Hit VK.Retargeting.Hit(); // $ExpectError VK.Retargeting.Hit(null); // $ExpectError VK.Retargeting.Hit(123); // $ExpectError VK.Retargeting.Hit(false); // $ExpectError VK.Retargeting.Hit(true); // $ExpectError VK.Retargeting.Hit('test'); // $ExpectError VK.Retargeting.Hit({}); // $ExpectError VK.Retargeting.Hit(() => void 0); // ---------------------------------------------------------------------------- // Retargeting.Event // $ExpectError VK.Retargeting.Event(); // $ExpectError VK.Retargeting.Event(null); // $ExpectError VK.Retargeting.Event(true); // $ExpectError VK.Retargeting.Event(false); // $ExpectError VK.Retargeting.Event(123); // $ExpectError VK.Retargeting.Event({}); // $ExpectError VK.Retargeting.Event(() => 'test'); VK.Retargeting.Event('test'); // ---------------------------------------------------------------------------- // Retargeting.Add // $ExpectError VK.Retargeting.Add(); // $ExpectError VK.Retargeting.Add(null); // $ExpectError VK.Retargeting.Add(true); // $ExpectError VK.Retargeting.Add(false); // $ExpectError VK.Retargeting.Add('test'); // $ExpectError VK.Retargeting.Add({}); // $ExpectError VK.Retargeting.Add(() => 123); VK.Retargeting.Add(123); // ---------------------------------------------------------------------------- // Retargeting.ProductEvent // $ExpectError VK.Retargeting.ProductEvent(); // $ExpectError VK.Retargeting.ProductEvent(null); // $ExpectError VK.Retargeting.ProductEvent(true); // $ExpectError VK.Retargeting.ProductEvent(false); // $ExpectError VK.Retargeting.ProductEvent('test'); // $ExpectError VK.Retargeting.ProductEvent({}); // $ExpectError VK.Retargeting.ProductEvent(() => 123); // $ExpectError VK.Retargeting.ProductEvent(123); VK.Retargeting.ProductEvent( 123, null, // $ExpectError ); VK.Retargeting.ProductEvent( 123, true, // $ExpectError ); VK.Retargeting.ProductEvent( 123, false, // $ExpectError ); VK.Retargeting.ProductEvent( 123, () => 'test', // $ExpectError ); VK.Retargeting.ProductEvent( 123, 'event_not_found', // $ExpectError ); VK.Retargeting.ProductEvent(123, 'view_home'); VK.Retargeting.ProductEvent(123, 'view_category'); VK.Retargeting.ProductEvent(123, 'view_product'); VK.Retargeting.ProductEvent(123, 'view_search'); VK.Retargeting.ProductEvent(123, 'view_other'); VK.Retargeting.ProductEvent(123, 'add_to_wishlist'); VK.Retargeting.ProductEvent(123, 'add_to_cart'); VK.Retargeting.ProductEvent(123, 'remove_from_wishlist'); VK.Retargeting.ProductEvent(123, 'remove_from_cart'); VK.Retargeting.ProductEvent(123, 'init_checkout'); VK.Retargeting.ProductEvent(123, 'add_payment_info'); VK.Retargeting.ProductEvent(123, 'purchase'); const product: vk.OpenAPI.Retargeting.Product = { // $ExpectError id: null, // $ExpectError group_id: null, // $ExpectError recommended_ids: null, // $ExpectError price: null, // $ExpectError price_old: null, // $ExpectError price_from: null, }; const product2: vk.OpenAPI.Retargeting.Product = { // $ExpectError id: 1, // $ExpectError group_id: 10, // $ExpectError recommended_ids: 100, // $ExpectError price: '1000', // $ExpectError price_old: '10000', // $ExpectError price_from: true, }; // $ExpectError const product3: vk.OpenAPI.Retargeting.Product = {}; const product4: vk.OpenAPI.Retargeting.Product = { id: 'product', group_id: '1', recommended_ids: '10,11,12', price: 120, price_old: 140, price_from: 0, }; const product5: vk.OpenAPI.Retargeting.Product = { id: 'product', group_id: '1', recommended_ids: '10,11,12', price: 120, price_old: 140, price_from: 1, }; const params: vk.OpenAPI.Retargeting.ProductEventParams = { // $ExpectError products: null, // $ExpectError products_recommended_ids: null, // $ExpectError category_ids: null, // $ExpectError business_value: null, // $ExpectError currency_code: null, // $ExpectError total_price: null, // $ExpectError search_string: null, }; const params2: vk.OpenAPI.Retargeting.ProductEventParams = { // $ExpectError products: {}, // $ExpectError products_recommended_ids: 123, // $ExpectError category_ids: 100, // $ExpectError business_value: '100', // $ExpectError currency_code: 007, // $ExpectError total_price: '666', // $ExpectError search_string: 777, }; const params3: vk.OpenAPI.Retargeting.ProductEventParams = { products: [product4, product5], products_recommended_ids: '1,2,3', category_ids: '10,66,97', business_value: 500, currency_code: 'JPY', total_price: 1500, search_string: 'aqua', }; const params4: vk.OpenAPI.Retargeting.ProductEventParams = {}; VK.Retargeting.ProductEvent(123, 'purchase', params3); VK.Retargeting.ProductEvent(123, 'purchase', params4); // ---------------------------------------------------------------------------- // Goal // $ExpectError VK.Goal(); // $ExpectError VK.Goal(null); // $ExpectError VK.Goal(true); // $ExpectError VK.Goal(false); // $ExpectError VK.Goal(123); // $ExpectError VK.Goal(() => 'test'); // $ExpectError VK.Goal('goal_not_found'); VK.Goal('add_to_cart'); VK.Goal('add_to_wishlist'); VK.Goal('customize_product'); VK.Goal('initiate_checkout'); VK.Goal('add_payment_info'); VK.Goal('purchase'); VK.Goal('contact'); VK.Goal('lead'); VK.Goal('schedule'); VK.Goal('complete_registration'); VK.Goal('submit_application'); VK.Goal('start_trial'); VK.Goal('subscribe'); VK.Goal('page_view'); VK.Goal('view_content'); VK.Goal('search'); VK.Goal('find_location'); VK.Goal('donate'); VK.Goal('conversion'); VK.Goal('donate', {}); VK.Goal( 'donate', // $ExpectError { someAnotherValue: 123 }, ); VK.Goal( 'donate', // $ExpectError { value: null }, ); VK.Goal( 'donate', // $ExpectError { value: true }, ); VK.Goal( 'donate', // $ExpectError { value: false }, ); VK.Goal( 'donate', // $ExpectError { value: 'test' }, ); VK.Goal( 'donate', // $ExpectError { value: () => 123 }, ); VK.Goal('donate', { value: 123 });
the_stack
import { ExecOptions } from 'child_process'; import * as fs from 'fs'; import * as fse from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; import { URL } from 'url'; import { commands, Event, EventEmitter, window, workspace } from 'vscode'; import { Disposable } from 'vscode'; import { callWithTelemetryAndErrorHandling, IActionContext } from 'vscode-azureextensionui'; import { ext } from '../extensionVariables'; import { localize } from '../localize'; import { AsyncLazy } from '../utils/lazy'; import { isWindows } from '../utils/osUtils'; import { execAsync, spawnAsync } from '../utils/spawnAsync'; import { dockerExePath } from '../utils/dockerExePathProvider'; import { ContextType, DockerContext, DockerContextInspection, isNewContextType } from './Contexts'; import { ContextLoadingClient } from './ContextLoadingClient/ContextLoadingClient'; // CONSIDER // Any of the commands related to Docker context can take a very long time to execute (a minute or longer) // if the current context refers to a remote Docker engine that is unreachable (e.g. machine is shut down). // Consider having our own timeout for execution of any context-related Docker CLI commands. // The following timeout is for _starting_ the command only; in the current implementation there is no timeot // for command duration. const ContextCmdExecOptions: ExecOptions = { timeout: 5000 }; const dockerConfigFile = path.join(os.homedir(), '.docker', 'config.json'); const dockerContextsFolder = path.join(os.homedir(), '.docker', 'contexts', 'meta'); const WindowsLocalPipe = 'npipe:////./pipe/docker_engine'; const UnixLocalPipe = 'unix:///var/run/docker.sock'; const defaultContext: Partial<DockerContext> = { Id: 'default', Name: 'default', Description: 'Current DOCKER_HOST based configuration', ContextType: 'moby', }; export const defaultContextNames = ['default', 'desktop-windows', 'desktop-linux']; // These contexts are used by external consumers (e.g. the "Remote - Containers" extension), and should NOT be changed type VSCodeContext = 'vscode-docker:aciContext' | 'vscode-docker:newSdkContext' | 'vscode-docker:newCliPresent' | 'vscode-docker:contextLocked'; export interface ContextManager { readonly onContextChanged: Event<DockerContext>; refresh(): Promise<void>; getContexts(): Promise<DockerContext[]>; getCurrentContext(): Promise<DockerContext>; getCurrentContextType(): Promise<ContextType>; inspect(actionContext: IActionContext, contextName: string): Promise<DockerContextInspection>; use(actionContext: IActionContext, contextName: string): Promise<void>; remove(actionContext: IActionContext, contextName: string): Promise<void>; isNewCli(): Promise<boolean>; } // TODO: consider a periodic refresh as a catch-all; but make sure it compares old data to new before firing a change event // TODO: so that non-changes don't result in everything getting refreshed export class DockerContextManager implements ContextManager, Disposable { private readonly contextChangedEmitter = new EventEmitter<DockerContext>(); private readonly loadingFinishedEmitter = new EventEmitter<unknown | undefined>(); private readonly contextsCache: AsyncLazy<DockerContext[]>; private readonly newCli: AsyncLazy<boolean>; private readonly configFileWatcher: fs.FSWatcher; private readonly contextFolderWatcher: fs.FSWatcher; private refreshing: boolean = false; public constructor() { this.contextsCache = new AsyncLazy(async () => this.loadContexts()); this.newCli = new AsyncLazy(async () => this.getCliVersion()); // The file watchers are not strictly necessary; they serve to help the extension detect context switches // that are done in CLI. Worst case, a user would have to restart VSCode. try { if (fse.existsSync(dockerConfigFile)) { this.configFileWatcher = fs.watch(dockerConfigFile, async () => this.refresh()); } } catch { // Best effort } try { if (fse.existsSync(dockerContextsFolder)) { this.contextFolderWatcher = fs.watch(dockerContextsFolder, async () => this.refresh()); } } catch { // Best effort } // Set the initial DockerApiClient to be the context loading client ext.dockerClient = new ContextLoadingClient(this.loadingFinishedEmitter.event); } public dispose(): void { void this.configFileWatcher?.close(); void this.contextFolderWatcher?.close(); // No event is fired so the client present at the end needs to be disposed manually void ext.dockerClient?.dispose(); } public get onContextChanged(): Event<DockerContext> { return this.contextChangedEmitter.event; } public async refresh(): Promise<void> { if (this.refreshing) { return; } try { this.refreshing = true; ext.treeInitError = undefined; this.contextsCache.clear(); // Because the cache is cleared, this will load all the contexts before returning the current one const currentContext = await this.getCurrentContext(); void ext.dockerClient?.dispose(); // Emit some info about what is being connected to /* eslint-disable @typescript-eslint/indent */ // The linter is completely wrong about indentation here ext.outputChannel.appendLine( localize('vscode-docker.docker.contextManager.targetLog', 'The Docker extension will try to connect to \'{0}\', via context \'{1}\'.', currentContext.DockerEndpoint || currentContext.ContextType, currentContext.Name ) ); /* eslint-enable @typescript-eslint/indent */ // Create a new client if (isNewContextType(currentContext.ContextType)) { // Currently vscode-docker:aciContext vscode-docker:newSdkContext mean the same thing // But that probably won't be true in the future, so define both as separate concepts now this.setVsCodeContext('vscode-docker:aciContext', true); this.setVsCodeContext('vscode-docker:newSdkContext', true); const dsc = await import('./DockerServeClient/DockerServeClient'); ext.dockerClient = new dsc.DockerServeClient(currentContext); } else { this.setVsCodeContext('vscode-docker:aciContext', false); this.setVsCodeContext('vscode-docker:newSdkContext', false); const dockerode = await import('./DockerodeApiClient/DockerodeApiClient'); ext.dockerClient = new dockerode.DockerodeApiClient(currentContext); } // This will allow the ContextLoadingClient to proceed this.loadingFinishedEmitter.fire(undefined); // This will refresh the tree this.contextChangedEmitter.fire(currentContext); } catch (err) { ext.treeInitError = err; // This will allow the ContextLoadingClient to return an error this.loadingFinishedEmitter.fire(err); } finally { this.refreshing = false; } // Lastly, trigger a CLI version check but don't wait void this.newCli.getValue(); } public async getContexts(): Promise<DockerContext[]> { return this.contextsCache.getValue(); } public async getCurrentContext(): Promise<DockerContext> { const contexts = await this.getContexts(); return contexts.find(c => c.Current); } public async getCurrentContextType(): Promise<ContextType> { return (await this.getCurrentContext()).ContextType; } public async inspect(actionContext: IActionContext, contextName: string): Promise<DockerContextInspection> { const { stdout } = await execAsync(`${dockerExePath(actionContext)} context inspect ${contextName}`, { timeout: 10000 }); // The result is an array with one entry const result: DockerContextInspection[] = JSON.parse(stdout) as DockerContextInspection[]; return result[0]; } public async use(actionContext: IActionContext, contextName: string): Promise<void> { const useCmd: string = `${dockerExePath(actionContext)} context use ${contextName}`; await execAsync(useCmd, ContextCmdExecOptions); } public async remove(actionContext: IActionContext, contextName: string): Promise<void> { const removeCmd: string = `${dockerExePath(actionContext)} context rm ${contextName}`; await spawnAsync(removeCmd, ContextCmdExecOptions); } public async isNewCli(): Promise<boolean> { return this.newCli.getValue(); } private async loadContexts(): Promise<DockerContext[]> { return await callWithTelemetryAndErrorHandling(ext.dockerClient ? 'docker-context.change' : 'docker-context.initialize', async (actionContext: IActionContext) => { // docker-context.initialize and docker-context.change should be treated as "activation events", in that they aren't real user action actionContext.telemetry.properties.isActivationEvent = 'true'; actionContext.errorHandling.rethrow = true; // Errors are handled outside of this scope actionContext.errorHandling.suppressDisplay = true; let contextList: DockerContext[] | undefined; // First, we'll try shortcutting by getting a fixed context from extension settings, then from environment, then from filesystem clues const fixedContext = this.tryGetContextFromSettings(actionContext) || this.tryGetContextFromEnvironment(actionContext) || this.tryGetContextFromFilesystemClues(actionContext); // A result from any of these three implies that there is only one context, or it is fixed by `docker.host` / `DOCKER_HOST`, or `docker.context` / `DOCKER_CONTEXT` // As such, we will lock to the current context // Otherwise, unlock in case we were previously locked if (fixedContext) { this.setVsCodeContext('vscode-docker:contextLocked', true); } else { this.setVsCodeContext('vscode-docker:contextLocked', false); } // If the result is undefined, there are (probably) multiple contexts and none is chosen by `docker.context` or `DOCKER_CONTEXT`, so we will need to do a context listing // If the result is a string, that means `docker.context` or `DOCKER_CONTEXT` are set, so we will also need to do a context listing if (typeof (fixedContext) === 'undefined' || typeof (fixedContext) === 'string') { contextList = (await this.tryGetContextsFromApi(actionContext, fixedContext)) || (await this.tryGetContextsFromCli(actionContext, fixedContext)); } else { contextList = [fixedContext]; } if (!contextList || contextList.length === 0) { // If the load is empty, return the default // That way a returned value is ensured by this method // And `setHostProtocolFromContextList` will always have a non-empty input contextList = [{ ...defaultContext, Current: true, DockerEndpoint: isWindows() ? WindowsLocalPipe : UnixLocalPipe, } as DockerContext]; } this.setHostProtocolFromContextList(actionContext, contextList); return contextList; }); } private tryGetContextFromSettings(actionContext: IActionContext): DockerContext | undefined | string { const config = workspace.getConfiguration('docker'); let dockerHost: string | undefined; let dockerContext: string | undefined; if ((dockerHost = config.get('host'))) { // Assignment + check is intentional actionContext.telemetry.properties.hostSource = 'docker.host'; return { ...defaultContext, Current: true, DockerEndpoint: dockerHost, } as DockerContext; } else if ((dockerContext = config.get('context'))) { // Assignment + check is intentional actionContext.telemetry.properties.hostSource = 'docker.context'; return dockerContext; } return undefined; } private tryGetContextFromEnvironment(actionContext: IActionContext): DockerContext | undefined | string { let dockerHost: string | undefined; let dockerContext: string | undefined; if ((dockerHost = process.env.DOCKER_HOST)) { // Assignment + check is intentional actionContext.telemetry.properties.hostSource = 'env'; return { ...defaultContext, Current: true, DockerEndpoint: dockerHost, } as DockerContext; } else if ((dockerContext = process.env.DOCKER_CONTEXT)) { // Assignment + check is intentional actionContext.telemetry.properties.hostSource = 'envContext'; return dockerContext; } return undefined; } private tryGetContextFromFilesystemClues(actionContext: IActionContext): DockerContext | undefined { // If there's nothing inside ~/.docker/contexts/meta (or it doesn't exist), then there's only the default, unmodifiable DOCKER_HOST-based context // It is unnecessary to call `docker context inspect` if (!fse.pathExistsSync(dockerContextsFolder) || fse.readdirSync(dockerContextsFolder).length === 0) { // Sync is intentionally used for performance, this is on the activation code path actionContext.telemetry.properties.hostSource = 'defaultContextOnly'; return { ...defaultContext, Current: true, DockerEndpoint: isWindows() ? WindowsLocalPipe : UnixLocalPipe, } as DockerContext; } return undefined; } private async tryGetContextsFromApi(actionContext: IActionContext, maybeFixedContextName: string | undefined): Promise<Promise<DockerContext[] | undefined>> { try { const dsc = await import('./DockerServeClient/DockerServeClient'); const client = new dsc.DockerServeClient({ Name: maybeFixedContextName } as DockerContext); // Context name is the only thing used by DockerServeClient's constructor const result = await client.getContexts(actionContext); this.setHostSourceFromContextList(actionContext, result, 'api'); return result; } catch { // Best effort } return undefined; } private async tryGetContextsFromCli(actionContext: IActionContext, maybeFixedContextName: string | undefined): Promise<DockerContext[] | undefined> { // eslint-disable-next-line @typescript-eslint/naming-convention const { stdout } = await execAsync(`${dockerExePath()} context ls --format="{{json .}}"`, { ...ContextCmdExecOptions, env: { ...process.env, DOCKER_CONTEXT: maybeFixedContextName } }); const result: DockerContext[] = []; try { // Try parsing as-is; newer CLIs output a JSON object array const contexts = JSON.parse(stdout) as DockerContext[]; result.push(...contexts.map(toDockerContext)); } catch { // Otherwise split by line, older CLIs output one JSON object per line const lines = stdout.split(/\r?\n/im); for (const line of lines) { // Blank lines should be skipped if (!line) { continue; } const context = JSON.parse(line) as DockerContext; result.push(toDockerContext(context)); } } this.setHostSourceFromContextList(actionContext, result, 'cli'); return result; } private setHostSourceFromContextList(actionContext: IActionContext, contexts: DockerContext[], contextSource: 'api' | 'cli') { const currentContext = contexts.find(c => c.Current); if (!currentContext) { actionContext.telemetry.properties.hostSource = 'unknown'; return; } actionContext.telemetry.properties.contextSource = contextSource; // This won't overwrite the value if it's already set, because above it may have been set by `docker.context` / `DOCKER_CONTEXT` already if (defaultContextNames.indexOf(currentContext.Name) >= 0) { actionContext.telemetry.properties.hostSource = actionContext.telemetry.properties.hostSource || 'defaultContextSelected'; } else { actionContext.telemetry.properties.hostSource = actionContext.telemetry.properties.hostSource || 'customContextSelected'; } } private setHostProtocolFromContextList(actionContext: IActionContext, contexts: DockerContext[]) { const currentContext = contexts.find(c => c.Current); if (isNewContextType(currentContext.ContextType)) { actionContext.telemetry.properties.hostProtocol = currentContext.ContextType; } else { try { actionContext.telemetry.properties.hostProtocol = new URL(currentContext.DockerEndpoint).protocol; } catch (err) { // If URL parsing fails, let's catch it and give a better error message to help users from a common mistake actionContext.telemetry.properties.hostProtocol = 'unknown'; const message = localize('vscode-docker.docker.contextManager.invalidHostSetting', 'The value provided for the setting `docker.host` or environment variable `DOCKER_HOST` is invalid. It must include the protocol, for example, ssh://myuser@mymachine or tcp://1.2.3.4.'); const button = localize('vscode-docker.docker.contextManager.openSettings', 'Open Settings'); void window.showErrorMessage(message, button) .then((result: string) => { if (result === button) { void commands.executeCommand('workbench.action.openSettings', 'docker.host'); } }); // Rethrow throw err; } } } private async getCliVersion(): Promise<boolean> { try { let result: boolean = false; const contexts = await this.contextsCache.getValue(); if (contexts.some(c => isNewContextType(c.ContextType))) { // If there are any new contexts we automatically know it's the new CLI result = true; } else { // Otherwise we look at the output of `docker serve --help` // TODO: this is not a very good heuristic const { stdout } = await execAsync(`${dockerExePath()} serve --help`); if (/^\s*Start an api server/i.test(stdout)) { result = true; } } // Set the VSCode context to the result (which may expose commands, etc.) this.setVsCodeContext('vscode-docker:newCliPresent', result); return result; } catch { // Best effort } } private setVsCodeContext(vsCodeContext: VSCodeContext, value: boolean): void { void commands.executeCommand('setContext', vsCodeContext, value); } } function toDockerContext(cliContext: Partial<DockerContext>): DockerContext { return { ...cliContext, Id: cliContext.Name, ContextType: cliContext.ContextType || (cliContext.DockerEndpoint ? 'moby' : 'aci'), // TODO: this basically assumes no Type and no DockerEndpoint => aci } as DockerContext; }
the_stack
import React, { useEffect, useState } from 'react'; import * as d3 from 'd3'; // IMPORT HELPER FUNCTIONS import { getHorizontalPosition, getVerticalPosition, } from '../helpers/getSimulationDimensions'; import { getStatic } from '../helpers/static'; // IMPORT TYPES import { SNode, SetSelectedContainer, Services, Options } from '../App.d'; import boxPath from '../../../static/boxPath'; // IMPORT COMPONENTS type Props = { services: Services; setSelectedContainer: SetSelectedContainer; options: Options; getColor: any; }; function wrap(text: d3.Selection<SVGTextElement, SNode, d3.BaseType, unknown>) { text.each(function () { const text = d3.select(this); const className = text.attr('class'); const words = text.text(); let line = 0; const lineLength = 15; const maxLine = 3; const totalLinesNeeded = Math.ceil(words.length / lineLength); if (totalLinesNeeded === 2) { text.attr('y', 67); } const x = text.attr('x'); const y = text.attr('y'); if (words.length > 8) { text.text(''); while (line < maxLine) { const currentIndex = line * lineLength; const lineText = text .append('tspan') .attr('x', x) .attr('y', y) .attr('dx', 0) .attr('dy', currentIndex * 1.7 - 10) .attr('class', className); if (line < 2 || words.length <= 24) { lineText.text(words.slice(currentIndex, currentIndex + lineLength)); } else { lineText.text(words.slice(currentIndex, currentIndex + 5) + '...'); } line++; } } }); } const Nodes: React.FC<Props> = ({ setSelectedContainer, services, options, getColor, }) => { const { simulation, serviceGraph, treeDepth } = window.d3State; const [boxPorts, setBoxPorts] = useState< d3.Selection<SVGRectElement, SNode, any, any>[] | [] >([]); const [boxPortTexts, setBoxPortTexts] = useState< d3.Selection<SVGTextElement, SNode, any, any>[] | [] >([]); const [boxVolumes, setBoxVolumes] = useState< d3.Selection<SVGSVGElement, SNode, any, any>[] | [] >([]); const [boxVolumesTexts, setBoxVolumesTexts] = useState< d3.Selection<SVGTextElement, SNode, any, any>[] | [] >([]); /** HELPER FUNCTIONS */ const removeVolumes = () => { boxVolumes.forEach((node) => node.remove()); boxVolumesTexts.forEach((node) => node.remove()); setBoxVolumes([]); setBoxVolumesTexts([]); }; const addVolumes = () => { const x = 0; const y = 0; const width = 133; const height = 133; // VOLUMES VARIABLES let nodesWithVolumes: d3.Selection<SVGGElement, SNode, any, any>; const volumes: d3.Selection<SVGSVGElement, SNode, any, any>[] = []; const volumeText: d3.Selection<SVGTextElement, SNode, any, any>[] = []; // select all nodes with volumes nodesWithVolumes = d3 .select('.nodes') .selectAll<SVGGElement, SNode>('.node') .filter((d: SNode) => d.volumes.length > 0); // iterate through all nodes with volumes nodesWithVolumes.each(function (d: SNode) { const node = this; // iterate through all volumes of node d.volumes.reverse().forEach((vString, i) => { let onClick = false; let onceClicked = false; // add svg volume const volume = d3 .select<SVGElement, SNode>(node) .insert('svg', 'image') .attr('viewBox', '0 0 133 133') .html(boxPath) .attr('class', 'volumeSVG') .attr('fill', () => { let slicedVString = vString.slice(0, vString.indexOf(':')); return vString.includes(':') ? getColor(slicedVString) : getColor(vString); }) .attr('width', width + (d.volumes.length - i) * 20) .attr('height', height + (d.volumes.length - i) * 20) .attr('x', x - (d.volumes.length - i) * 10) .attr('y', y - (d.volumes.length - i) * 10) .on('mouseover', () => { return vText.style('visibility', 'visible'); }) .on('mouseout', () => { !onClick ? vText.style('visibility', 'hidden') : vText.style('visibility', 'visible'); }) .on('click', () => { onceClicked = !onceClicked; onClick = onceClicked; }); // store d3 object in volumes array so that they can be removed volumes.push(volume); // add svg volume text const vText = d3 .select<SVGElement, SNode>(node) .append('text') .text(vString) .attr('class', 'volume-text') .attr('fill', 'black') .attr('text-anchor', 'end') .attr('dx', x - 5) .attr('dy', y + (i + 1) * 11) .style('visibility', 'hidden'); // store d3 object in volumes text array volumeText.push(vText); }); setBoxVolumes(volumes); setBoxVolumesTexts(volumeText); }); }; const removePorts = () => { boxPorts.forEach((node) => node.remove()); boxPortTexts.forEach((node) => node.remove()); setBoxPorts([]); setBoxPortTexts([]); }; const addPorts = () => { const rx = 3; // size of rectangle const pWidth = 78; const pHeight = 15; // ports location const x = 133 - 60; const y = 133 - 30; // text location const dx = x + 21; // center of text element because of text-anchor const dy = y + pHeight; // PORTS VARIABLES console.log('adding ports'); let nodesWithPorts: d3.Selection<SVGGElement, SNode, any, any>; const ports: d3.Selection<SVGRectElement, SNode, any, any>[] = []; const portText: d3.Selection<SVGTextElement, SNode, any, any>[] = []; // select all nodes with ports nodesWithPorts = d3 .select('.nodes') .selectAll<SVGGElement, SNode>('.node') .filter((d: SNode) => { return d.ports.length > 0; }); // iterate through all nodes with ports nodesWithPorts.each(function (d: SNode) { const node = this; // iterate through all ports of node d.ports.forEach((pString, i) => { // set font size based on length of ports text const textSize = '12px'; // add svg port const port = d3 .select<SVGElement, SNode>(node) .append('rect') .attr('class', 'port') .attr('rx', rx) .attr('x', x) .attr('y', y + i * pHeight) .attr('width', pWidth) .attr('height', pHeight); // store d3 object in ports array ports.push(port); // add svg port text const pText = d3 .select<SVGElement, SNode>(node) .append('text') .attr('class', 'ports-text') .attr('color', 'white') .attr('dx', dx + 18) .attr('dy', dy + i * pHeight - 2) .attr('text-anchor', 'middle') .attr('font-size', textSize) // center the text in the rectangle .append('tspan') .text(pString) .attr('text-anchor', 'middle'); // store d3 object in ports text array portText.push(pText); }); }); setBoxPorts(ports); setBoxPortTexts(portText); }; /** ********************* * RENDER NODES ********************* */ useEffect(() => { const container = d3.select('.view-wrapper'); const width = parseInt(container.style('width'), 10); const height = parseInt(container.style('height'), 10); //sets 'clicked' nodes back to unfixed position const dblClick = (d: SNode) => { simulation.alphaTarget(0); d.fx = null; d.fy = null; }; // set up drag feature for nodes let drag = d3 .drag<SVGGElement, SNode>() .on('start', function dragstarted(d: SNode) { // if simulation has stopped, restart it if (!d3.event.active) simulation.alphaTarget(0.3).restart(); // set the x and y positions to fixed d.fx = d3.event.x; d.fy = d3.event.y; }) .on('drag', function dragged(d: SNode) { // raise the current selected node to the highest layer d3.select(this).raise(); // change the fx and fy to dragged position d.fx = d3.event.x; d.fy = d3.event.y; }) .on('end', function dragended(d: SNode) { // stop simulation when node is done being dragged if (!d3.event.active) simulation.alphaTarget(0); // fix the node to the place where the dragging stopped d.fx = d.x; d.fy = d.y; }); // create node container svgs const nodeContainers = d3 .select('.nodes') .selectAll('g') .data<SNode>(serviceGraph.nodes) .enter() .append('g') .attr('class', 'node') .attr('id', (node: SNode) => { return `container_${node.name}`; }) .on('click', (node: SNode) => { setSelectedContainer(node.name); }) .on('dblclick', dblClick) .call(drag) // initialize nodes in depends on view .attr('x', (d: SNode) => { //assign the initial x location to the relative displacement from the left return (d.x = getHorizontalPosition(d, width)); }) .attr('y', (d: SNode) => { return (d.y = getVerticalPosition(d, treeDepth, height)); }); //add container image to each node nodeContainers .append('svg:image') .attr('xlink:href', (d: SNode) => { return getStatic('box.svg'); }) .attr('height', 133) .attr('width', 133) .attr('class', 'containerImage'); // add node service name nodeContainers .append('text') .text((d: SNode) => d.name) .attr('class', 'nodeLabel') .attr('x', 133 / 2) .attr('y', 133 / 2) .attr('text-anchor', 'middle') .call(wrap); const statTextSize = '10px'; nodeContainers .append('text') .text((d: any) => 'CPU %') .attr('class', 'cpu-stat-title') .attr('x', 2) .attr('y', 11) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'x') .attr('class', 'cpu-stat') .attr('x', 2) .attr('y', 21) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'MEM USAGE/LIMIT') .attr('class', 'mem-usage-stat-title') .attr('x', 39) .attr('y', 11) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'x') .attr('class', 'mem-usage-stat') .attr('x', 39) .attr('y', 21) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'MEM %') .attr('class', 'mem-percent-stat-title') .attr('x', 2) .attr('y', 33) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'x') .attr('class', 'mem-percent-stat') .attr('x', 2) .attr('y', 45) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'NET I/O') .attr('class', 'net-stat-title') .attr('x', 39) .attr('y', 33) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'x') .attr('class', 'net-stat') .attr('x', 39) .attr('y', 45) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'BLOCK I/O') .attr('class', 'block-stat-title') .attr('x', 2) .attr('y', 57) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'x') .attr('class', 'block-stat') .attr('x', 2) .attr('y', 68) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'PIDS') .attr('class', 'pids-stat-title') .attr('x', 105) .attr('y', 57) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); nodeContainers .append('text') .text((d: any) => 'x') .attr('class', 'pids-stat') .attr('x', 105) .attr('y', 70) .attr('style', 'white-space:pre') .attr('font-size', statTextSize) .style('fill', 'rgb(0,255,0)') .style('display', 'none'); if (options.ports) addPorts(); if (options.volumes) addVolumes(); return () => { // remove containers when services change nodeContainers.remove(); }; }, [services]); useEffect(() => { if (options.ports) addPorts(); else if (boxPorts.length !== 0) removePorts(); return () => { // before unmounting, if ports option was on, remove the ports if (options.ports) removePorts(); }; }, [options.ports]); useEffect(() => { if (options.volumes) addVolumes(); else if (boxVolumes.length !== 0) removeVolumes(); return () => { // before unmounting, if volumes option was on, remove the ports if (options.volumes) removeVolumes(); }; }, [options.volumes]); return <g className="nodes"></g>; }; export default Nodes;
the_stack
import { options, triggerEvent } from '@tko/utils' import { observable } from '@tko/observable' import { computed } from '@tko/computed' import { applyBindings, dataFor, bindingContext } from '@tko/bind' import { Parser, Identifier, Arguments } from '@tko/utils.parser' import { DataBindProvider } from '../dist' import * as coreBindings from '@tko/binding.core'; var instance beforeEach(function () { instance = new DataBindProvider() }) describe('nodeHasBindings', function () { it('identifies elements with data-bind', function () { var div = document.createElement('div') div.setAttribute('data-bind', 'x') assert.ok(instance.nodeHasBindings(div)) }) }) describe('getBindingAccessors with string arg', function () { var div; beforeEach(function () { instance = options.bindingProviderInstance = new DataBindProvider() div = document.createElement('div'); instance.bindingHandlers.alpha = { init: sinon.spy(), update: sinon.spy() } }); it('reads multiple bindings', function () { div.setAttribute('data-bind', 'a: 123, b: "456"') var bindings = instance.getBindingAccessors(div); assert.equal(Object.keys(bindings).length, 2, 'len') assert.equal(bindings['a'](), 123, 'a') assert.equal(bindings['b'](), '456', 'b') }); it('escapes strings', function () { div.setAttribute('data-bind', 'a: "a\\"b", b: \'c\\\'d\'') var bindings = instance.getBindingAccessors(div); assert.equal(Object.keys(bindings).length, 2, 'len') assert.equal(bindings['a'](), 'a"b', 'a') assert.equal(bindings['b'](), "c\'d", 'b') }) it('returns a name/valueAccessor pair', function () { div.setAttribute('data-bind', 'alpha: "122.9"'); var bindings = instance.getBindingAccessors(div); assert.equal(Object.keys(bindings).length, 1, 'len') assert.isFunction(bindings['alpha'], 'is accessor') assert.equal(bindings['alpha'](), '122.9', '122.9') }); it('becomes the valueAccessor', function () { div.setAttribute('data-bind', 'alpha: "122.9"'); var i_spy = instance.bindingHandlers.alpha.init, u_spy = instance.bindingHandlers.alpha.update, args; applyBindings({ vm: true }, div); assert.equal(i_spy.callCount, 1, 'i_spy cc'); assert.equal(u_spy.callCount, 1, 'u_spy cc'); args = i_spy.getCall(0).args; assert.equal(args[0], div, 'u_spy div == node') assert.equal(args[1](), '122.9', 'valueAccessor') // args[2] == allBindings assert.deepEqual(args[3], { vm: true }, 'view model') }) }) describe('getBindingAccessors with function arg', function () { var div; beforeEach(function () { instance = options.bindingProviderInstance = new DataBindProvider() div = document.createElement('div'); div.setAttribute('data-bind', 'alpha: x'); instance.bindingHandlers.alpha = { init: sinon.spy(), update: sinon.spy() } }); it('returns a name/valueAccessor pair', function () { var bindings = instance.getBindingAccessors(div); assert.equal(Object.keys(bindings).length, 1) assert.isFunction(bindings['alpha']) }); it('becomes the valueAccessor', function () { var i_spy = instance.bindingHandlers.alpha.init, u_spy = instance.bindingHandlers.alpha.update, args; applyBindings({ x: 0xDEADBEEF }, div); assert.equal(i_spy.callCount, 1, 'i_spy cc'); assert.equal(u_spy.callCount, 1, 'u_spy cc'); args = i_spy.getCall(0).args; assert.equal(args[0], div, 'u_spy div == node') assert.equal(args[1](), 0xDEADBEEF, 'valueAccessor') // args[2] == allBindings assert.deepEqual(args[3], { x: 0xDEADBEEF }, 'view model') }) }) describe('all bindings', function () { beforeEach(function () { options.bindingProviderInstance = new DataBindProvider() options.bindingProviderInstance.bindingHandlers.set(coreBindings.bindings) }) it('binds Text with data-bind', function () { var div = document.createElement('div'); div.setAttribute('data-bind', 'text: obs') applyBindings({ obs: observable('a towel') }, div) assert.equal(div.textContent || div.innerText, 'a towel') }) it('sets attributes to constants', function () { var div = document.createElement('div'), context = { aTitle: 'petunia plant' }; div.setAttribute('data-bind', 'attr: { title: aTitle }') applyBindings(context, div) assert.equal(div.getAttribute('title'), context.aTitle) }) it('sets attributes to observables in objects', function () { var div = document.createElement('div'), context = { aTitle: observable('petunia plant') }; div.setAttribute('data-bind', 'attr: { title: aTitle }') applyBindings(context, div) assert.equal(div.getAttribute('title'), context.aTitle()) }) it('registers a click event', function () { var div = document.createElement('div'), called = false, context = { cb: function () { called = true; } }; div.setAttribute('data-bind', 'click: cb') applyBindings(context, div) assert.equal(called, false, 'not called') div.click() assert.equal(called, true) }) it('sets an input `value` binding ', function () { var input = document.createElement('input'), context = { vobs: observable('273-9164') }; input.setAttribute('data-bind', 'value: vobs') applyBindings(context, input) assert.equal(input.value, '273-9164') context.vobs('Area code 415') assert.equal(input.value, 'Area code 415') }) it('reads an input `value` binding', function () { var input = document.createElement('input'), evt = new CustomEvent('change'), context = { vobs: observable() }; input.setAttribute('data-bind', 'value: vobs') applyBindings(context, input) input.value = '273-9164' input.dispatchEvent(evt) assert.equal(context.vobs(), '273-9164') }) it('reads an input `value` binding for a defineProperty', function () { // see https://github.com/brianmhunt/knockout-secure-binding/issues/23 // and http://stackoverflow.com/questions/21580173 var input = document.createElement('input'), evt = new CustomEvent('change'), obs = observable(), context = {}; Object.defineProperty(context, 'pobs', { configurable: true, enumerable: true, get: obs, set: obs }); input.setAttribute('data-bind', 'value: pobs') applyBindings(context, input) input.value = '273-9164' input.dispatchEvent(evt) assert.equal(context.pobs, '273-9164') }) it('writes an input `value` binding for a defineProperty', function () { var input = document.createElement('input'), // evt = new CustomEvent("change"), obs = observable(), context = {}; Object.defineProperty(context, 'pobs', { configurable: true, enumerable: true, get: obs, set: obs }); input.setAttribute('data-bind', 'value: pobs') context.pobs = '273-9164' applyBindings(context, input) assert.equal(context.pobs, obs()) assert.equal(input.value, context.pobs) context.pobs = '415-273-9164' assert.equal(input.value, context.pobs) assert.equal(input.value, '415-273-9164') }) it('writes an input object defineProperty', function () { var input = document.createElement('input'), // evt = new CustomEvent("change"), obs = observable(), context = { obj: {} }; Object.defineProperty(context.obj, 'sobs', { configurable: true, enumerable: true, get: obs, set: obs }); // apply the binding with a value input.setAttribute('data-bind', 'value: obj.sobs') context.obj.sobs = '273-9164' applyBindings(context, input) // make sure the element is updated assert.equal(context.obj.sobs, obs()) assert.equal(input.value, context.obj.sobs) // update the observable and check the input values context.obj.sobs = '415-273-9164' assert.equal(input.value, context.obj.sobs) assert.equal(input.value, '415-273-9164') }) it('writes nested defineProperties', function () { var input = document.createElement('input'), // evt = new CustomEvent("change"), obs = observable(), context = {}, obj = {}, oo = observable(obj); // es5 wraps obj in an observable Object.defineProperty(context, 'obj', { configurable: true, enumerable: true, get: oo, set: oo }) Object.defineProperty(context.obj, 'ddobs', { configurable: true, enumerable: true, get: obs, set: obs }) input.setAttribute('data-bind', 'value: obj.ddobs') context.obj.ddobs = '555-2368' // who ya gonna call? applyBindings(context, input) assert.equal(context.obj.ddobs, obs()) assert.equal(input.value, context.obj.ddobs) context.obj.ddobs = '646-555-2368' assert.equal(input.value, '646-555-2368') }) it('reads a nested defineProperty', function () { var input = document.createElement('input'), evt = new CustomEvent('change'), obs = observable(), oo = observable({}), context = {}; Object.defineProperty(context, 'obj', { configurable: true, enumerable: true, get: oo, set: oo }) Object.defineProperty(oo(), 'drobs', { configurable: true, enumerable: true, get: obs, set: obs }) input.setAttribute('data-bind', 'value: obj.drobs') applyBindings(context, input) input.value = '273.9164' input.dispatchEvent(evt) assert.equal(context.obj.drobs, '273.9164') }) it('reads a multi-nested defineProperty', function () { var input = document.createElement('input'), evt = new CustomEvent('change'), o0 = observable({}), o1 = observable({}), o2 = observable({}), context = {}; Object.defineProperty(context, 'o0', { configurable: true, enumerable: true, get: o0, set: o0 }) Object.defineProperty(o0(), 'o1', { configurable: true, enumerable: true, get: o1, set: o1 }) Object.defineProperty(o1(), 'o2', { configurable: true, enumerable: true, get: o1, set: o1 }) Object.defineProperty(o2(), 'oN', { configurable: true, enumerable: true, get: o1, set: o1 }) input.setAttribute('data-bind', 'value: o0.o1.o2.oN') applyBindings(context, input) input.value = '1.7724' input.dispatchEvent(evt) assert.equal(context.o0.o1.o2.oN, '1.7724') }) }) describe('The lookup of variables (get_lookup_root)', function () { function makeBindings (binding, context, globals, node) { const ctx = new bindingContext(context) return new Parser().parse(binding, ctx, globals, node) } it('accesses the context', function () { var binding = 'a: x', context = { x: 'y' }, bindings = makeBindings(binding, context) assert.equal(bindings.a(), 'y'); }) it('accesses the globals', function () { var binding = 'a: z', globals = { z: 'ZZ' }, bindings = makeBindings(binding, {}, globals) assert.equal(bindings.a(), globals.z) }) it('accesses $data.value and value', function () { var binding = 'x: $data.value, y: value', context = { value: 42 }, bindings = makeBindings(binding, context) assert.equal(bindings.x(), 42) assert.equal(bindings.y(), 42) }) it('ignores spaces', function () { var binding = 'x: $data . value, y: $data\n\t\r . \t\r\nvalue', context = { value: 42 }, bindings = makeBindings(binding, context) assert.equal(bindings.x(), 42) assert.equal(bindings.y(), 42) }) it('looks up nested elements in objects', function () { var binding = 'x: { y: { z: a.b.c } }', context = { 'a': { b: { c: 11 } } }, bindings = makeBindings(binding, context) assert.equal(bindings.x().y.z, 11) }) it('can be denied access to `window` globals', function () { var binding = 'x: window, y: global, z: document', context = {}, bindings = makeBindings(binding, context) assert.throws(bindings.x, 'not found') assert.throws(bindings.y, 'not found') assert.throws(bindings.z, 'not found') }) it('only returns explicitly from $context', function () { var binding = 'x: $context.$data.value, y: $context.value, z: value', context = { value: 42 }, bindings = makeBindings(binding, context) assert.equal(bindings.x(), 42) assert.equal(bindings.y(), undefined) assert.equal(bindings.z(), 42) }) it('recognizes $element', function () { var binding = 'x: $element.id', node = { id: 42 }, bindings = makeBindings(binding, {}, {}, node) assert.equal(bindings.x(), node.id) }) it('accesses $data before $context', function () { const binding = 'x: value' const outerContext = new bindingContext({ value: 21 }) const innerContext = outerContext.createChildContext({ value: 42 }) const bindings = new Parser().parse(binding, innerContext) assert.equal(bindings.x(), 42) }) it('accesses $context before globals', function () { var binding = 'a: z', context = { z: 42 }, globals = { z: 84 }, bindings = makeBindings(binding, context, globals) assert.equal(bindings.a(), 42) }) it('accesses properties created with defineProperty', function () { // style of e.g. knockout-es5 var binding = 'a: z', context = {}, bindings = makeBindings(binding, context), obs = observable(); Object.defineProperty(context, 'z', { configurable: true, enumerable: true, get: obs, set: obs }); assert.equal(bindings.a(), undefined) context.z = '142' assert.equal(bindings.a(), 142) }) it('does not bleed globals', function () { var binding = 'a: z', globals_1 = { z: 168 }, globals_2 = { z: undefined }, context = {}, bindings_1 = makeBindings(binding, context, globals_1), bindings_2 = makeBindings(binding, context, globals_2) assert.equal(bindings_1.a(), 168) assert.equal(bindings_2.a(), undefined) }) })
the_stack
module TDev { export class RecordDefProperties extends CodeView implements KindBoxModel { private theRecord:AST.RecordDef; constructor() { super() this.recordnamediv = div("varHalf", div("formHint", lf("record name:")), this.recordName); this.kindContainer = VariableProperties.mkKindContainer(this); this.recordName.addEventListener("change", () => this.nameUpdated()) } private recordName = HTML.mkTextInputWithOk("text", lf("Enter a name")); private description = HTML.mkTextArea("description"); private recordnamediv:HTMLElement; private formRoot = div("varProps"); private recordType = div(null); private kindContainer:HTMLElement; private fields = div(null); private renderer = new TDev.EditorRenderer(); private mkKey = div("inline-block"); private mkVal = div("inline-block"); private mkAct = div("inline-block"); private exported: HTMLElement; public getTick() { return Ticks.viewRecordInit; } public nodeType() { return "recordDef"; } public init(e:Editor) { super.init(e); this.recordName.id = "renameBox2"; this.description.className = "variableDesc"; this.exported = HTML.mkTickCheckBox( Ticks.recordExported, lf("exported from this library"), (checked: boolean) => { this.theRecord._isExported = checked; } ); } private isActive() { return !!this.theRecord; } public kindBoxHeader() { return lf("decorator target"); } public editedStmt():AST.Stmt { return this.theRecord ? this.theRecord.values : null; } public syncAll(tc:boolean, origtype:AST.RecordType = undefined) { this.theRecord.fixupFields(origtype); this.recordName.value = this.theRecord.getCoreName(); this.description.value = this.theRecord.description; if (tc) { AST.TypeChecker.tcApp(Script); TheEditor.queueNavRefresh(); } if (this.theRecord.recordType === AST.RecordType.Decorator) this.recordnamediv.setChildren([div("varHalf", [div("formHint", lf("target kind:")), this.kindContainer])]); else this.recordnamediv.setChildren(<any[]>[div("formHint", lf("record name:")), this.recordName]); this.mkKey.setChildren([this.mkField(true)]); this.mkVal.setChildren([this.mkField(false)]); this.mkAct.setChildren([this.mkAction()]); this.recordType.setChildren([ this.mkTypeBox( this.theRecord.recordType, this.theRecord.getRecordPersistence() ) ]); HTML.setCheckboxValue(this.exported, this.theRecord.isExported()); (<any>this.kindContainer).refresh(); this.fields.setChildren([this.renderer.declDiv(this.theRecord)]); this.renderer.attachHandlers(); var rt = this.theRecord.recordType; this.exported.style.display = rt == AST.RecordType.Object && Script.isLibrary ? "block" : "none"; this.theRecord.notifyChange(); // just in case if (tc) TheEditor.updateTutorial() } private mkAction() { if (this.theRecord.recordType != AST.RecordType.Object) return null; var b = HTML.mkButtonTick(lf("add function"), Ticks.recordAddAction,() => { this.commit(); // create fresh action var decl = this.editor.freshAsyncAction(); this.editor.addNode(decl); // add this parameter var header = decl.header; var blk = header.inParameters; var empt = blk.emptyStmt("this", this.theRecord.entryKind); this.editor.initIds(empt, true) var newCh = blk.stmts.concat([empt]); blk.setChildren(newCh); decl.notifyChange(); this.editor.typeCheckNow(); this.editor.refreshDecl(); this.editor.queueNavRefresh(); }); return b; } private mkField(key:boolean) { var terminology = (key ? this.theRecord.getKeyTerminology() : this.theRecord.getValueTerminology()); if (!terminology) return null; var b = HTML.mkButtonTick(lf("add {0}", terminology), key ? Ticks.recordAddKey : Ticks.recordAddValue, () => { this.commit(); var blk = key ? this.theRecord.keys : this.theRecord.values; var stmt = blk.emptyStmt() if (!stmt) { var x = this.theRecord.cloudEnabled ? lf("replicated tables") : this.theRecord.persistent ? lf("persistent tables") : lf("tables"); TDev.ModalDialog.info(lf("No can do"), lf("Links have to lead to other {0}. You don't have any other {0} defined at the moment.", x)); return; } var newCh = blk.stmts.concat([stmt]); blk.setChildren(newCh); this.syncAll(true); // Jump directly into the field definition and edit its name. TheEditor.editNode(stmt); TheEditor.calculator.inlineEdit(TheEditor.calculator.expr.tokens[0]); }); return b; } public mkTypeBox(rt:AST.RecordType, cloud?:AST.RecordPersistence) { var pers = (cloud !== undefined && (rt == AST.RecordType.Index || rt == AST.RecordType.Table)) ? AST.RecordDef.recordPersistenceToString(cloud, Script.isCloud) + " " : ""; var e = new DeclEntry(pers + AST.RecordDef.recordTypeToString(rt).toLowerCase()); e.icon = DeclRender.colorByPersistence(AST.RecordDef.GetIcon(rt), cloud !== undefined ? cloud : AST.RecordPersistence.Temporary); e.description = RecordDefProperties.GetDescription(rt, cloud, Script.isCloud); var d = e.mkBox(); d.className += " recordTypeDescription"; return d; } static GetPersistenceDescription(thing: string, pers: AST.RecordPersistence, service: boolean): string { if (!service) { if (pers == AST.RecordPersistence.Temporary) return lf("A temporary {0} is not saved between runs.", thing); else if (pers == AST.RecordPersistence.Local) return lf("A local {0} is automatically saved to local storage, but never shared with other devices.", thing); else if (pers == AST.RecordPersistence.Cloud) return lf("A replicated {0} is automatically saved in the cloud and shared between devices.", thing); else return ""; } else { if (pers == AST.RecordPersistence.Temporary) return lf("A temporary {0} is local to the connection, and discarded when the connection ends.", thing); else if (pers == AST.RecordPersistence.Local) return lf("A server-local {0} is saved in cloud storage, and never cached on clients.", thing); else if (pers == AST.RecordPersistence.Cloud) return lf("A fully replicated {0} is saved in cloud storage, and fully cached on clients.", thing); else if (pers == AST.RecordPersistence.Partial) return lf("A partially replicated {0} is saved in cloud storage, and fully cached on clients.", thing); else return ""; } } static GetDescription(rt: AST.RecordType, pers:AST.RecordPersistence, service:boolean): string { switch (rt) { case AST.RecordType.Object: return "Objects store data values in fields. \nYou can create new objects at any time. \nObjects are automatically disposed of if you don't store them anywhere. \nObjects can be stored in data variables, in records, or in object collections."; case AST.RecordType.Table: var desc = "A table stores records as rows, with data values appearing in columns. \n"; if (pers !== undefined) return desc + RecordDefProperties.GetPersistenceDescription("table", pers, service); else return desc + "You can add new rows, and you can iterate over rows. \n" + "Rows remain in the table until you delete them, or until you delete a linked row. \n"; case AST.RecordType.Decorator: return "A decorator attaches extra fields to target objects."; case AST.RecordType.Index: var desc = "An index stores records that are indexed by key fields. \n"; if (pers !== undefined) return desc + RecordDefProperties.GetPersistenceDescription("index", pers, service); else return desc + "There is always exactly one index entry for each key combination. \n" + "You need not create entries before using them. \nTo remove an entry, clear all of its fields. \n"; default: Util.die(); } } // kind container methods public getContexts():KindContext { return KindContext.GcKey; } public getKind() { var theKey = <AST.RecordField> this.theRecord.keys.stmts[0]; return (theKey) ? theKey.dataKind : api.getKind("Sprite"); } public immutableReason():string { return null; } public setKind(k:Kind) { var theKey = new AST.RecordField("target", k, true); this.theRecord.keys.setChildren([theKey]); this.syncAll(true); } public nodeTap(s:AST.Stmt) { if (s instanceof AST.RecordField) { // Clear the error message because we don't re-render the record // at this stage... var recordFieldStmt = s.renderedAs.parentNode.parentNode; var node = (<HTMLElement>recordFieldStmt).getElementsByClassName("errorMessage")[0]; if (node) node.parentNode.removeChild(node); // ... then let the calculator do its job. return false; } // Clicking on the [RecordKind] shows up the [RecordEditor], this is // handled by editor's [nodeTap]. All other cases handled by the // calculator. return false; } public renderCore(a:AST.Decl) { return this.load(<AST.RecordDef>a); } static cloudstatePersistenceLabels = [{ name: "temporary", tick: Ticks.recordPersTemporary }, { name: "local", tick: Ticks.recordPersLocal }, { name: "replicated", tick: Ticks.recordPersCloud }]; static servicePersistenceLabels = [{ name: "temporary", tick: Ticks.recordPersTemporary }, { name: "server-local", tick: Ticks.recordPersLocal }]; static cloudlibraryPersistenceLabels = [{ name: "temporary", tick: Ticks.recordPersTemporary }, { name: "server-local", tick: Ticks.recordPersLocal }, { name: "fully replicated", tick: Ticks.recordPersCloud } /*, { name: "partially replicated", tick: Ticks.recordPersPartial } */]; static cloudlibraryVarPersistenceLabels = [{ name: "temporary", tick: Ticks.recordPersTemporary }, { name: "server-local", tick: Ticks.recordPersLocal }, { name: "replicated", tick: Ticks.recordPersCloud }]; private load(a:AST.RecordDef) :void { this.theRecord = null; TheEditor.dismissSidePane(); this.theRecord = a; this.formRoot.className += " recordProperties"; this.formRoot.setChildren([ Editor.mkHelpLink("records"), this.exported, this.fields, this.mkKey, this.mkVal, this.mkAct, div("varLabel", lf("description")), this.description, ]); this.editor.displayLeft([this.formRoot]); this.syncAll(false); } private nameUpdated() { if (this.theRecord.getCoreName() != this.recordName.value) { this.theRecord.setName(Script.freshName(this.recordName.value)); this.syncAll(true) } } public commit() { if (!this.theRecord || !Script) return; if (this.theRecord.getCoreName() != this.recordName.value) this.theRecord.setName(Script.freshName(this.recordName.value)); this.theRecord._isExported = HTML.getCheckboxValue(this.exported); this.theRecord.description = this.description.value; Script.notifyChangeAll(); TheEditor.queueNavRefresh(); } } }
the_stack
import * as vscode from 'vscode'; import { Position } from '../src/common/motion/position'; import { TextEditor } from '../src/textEditor'; import { VimSettings } from './vimSettings'; import { NvUtil } from './nvUtil'; import { Vim } from '../extension'; export class Cell { v: string; highlight: any; constructor(v: string) { this.v = v; this.highlight = {}; } } interface ScreenSize { width: number; height: number; } export interface IgnoredKeys { all: string[]; normal: string[]; insert: string[]; visual: string[]; } export interface HighlightGroup { name: string; decorator?: vscode.TextEditorDecorationType; } export class Screen { OFFSET_COLOR = 1; term: Array<Array<Cell>> = []; cursX: number; cursY: number; size: ScreenSize; highlighter: any; cmdline: vscode.StatusBarItem; wildmenu: vscode.StatusBarItem[]; wildmenuItems: string[]; highlightGroups: HighlightGroup[]; scrollRegion: { top: number; bottom: number; left: number; right: number; }; resize(size: ScreenSize) { this.size = size; for (let i = 0; i < this.size.height; i++) { this.term[i] = []; for (let j = 0; j < this.size.width; j++) { this.term[i][j] = new Cell(' '); } } this.scrollRegion = { top: 0, bottom: this.size.height, left: 0, right: this.size.width, }; } clear() { this.resize(this.size); } scroll(deltaY: number) { const { top, bottom, left, right } = this.scrollRegion; const width = right - left; const height = bottom - top; let yi = [top, bottom]; if (deltaY < 0) { yi = [bottom, top - 1]; } for (let y = yi[0]; y !== yi[1]; y = y + Math.sign(deltaY)) { if (top <= y + deltaY && y + deltaY < bottom) { for (let x = left; x < right; x++) { this.term[y][x] = this.term[y + deltaY][x]; } } else { for (let x = left; x < right; x++) { this.term[y][x] = new Cell(' '); this.term[y][x].highlight = this.highlighter; } } } } constructor(size: { width: number; height: number }) { this.size = size; this.resize(this.size); this.cursX = 0; this.cursY = 0; this.highlighter = {}; this.cmdline = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 10001); this.wildmenu = []; for (let i = 0; i < 10; i++) { this.wildmenu.push( vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 10000 - i) ); // this.wildmenu[i].show(); } // todo(chilli): Offer some way of binding these from the client side. this.highlightGroups = [ { name: 'IncSearch', decorator: vscode.window.createTextEditorDecorationType({ backgroundColor: new vscode.ThemeColor('editor.findMatchBackground'), }), }, { name: 'Search', decorator: vscode.window.createTextEditorDecorationType({ backgroundColor: new vscode.ThemeColor('editor.findMatchHighlightBackground'), }), }, { name: 'multiple_cursors_visual', decorator: vscode.window.createTextEditorDecorationType({ backgroundColor: new vscode.ThemeColor('editor.selectionBackground'), }), }, { name: 'multiple_cursors_cursor', decorator: vscode.window.createTextEditorDecorationType({ backgroundColor: new vscode.ThemeColor('editorCursor.foreground'), }), }, { name: 'EasyMotionTarget', decorator: vscode.window.createTextEditorDecorationType({ backgroundColor: 'black', textDecoration: 'none;color: red', }), }, { name: 'EasyMotionShade', decorator: vscode.window.createTextEditorDecorationType({ textDecoration: 'none;opacity: 0.3', }), }, ]; for (let i = 0; i < this.highlightGroups.length; i++) { Vim.nv.command( `highlight ${this.highlightGroups[i].name} guibg='#00000${i + this.OFFSET_COLOR}'` ); } } private async handleModeChange(mode: [string, number]) { if (mode[0] === 'insert') { await NvUtil.setSettings(await VimSettings.insertModeSettings()); } else { await NvUtil.updateMode(); await NvUtil.copyTextFromNeovim(); await NvUtil.changeSelectionFromMode(Vim.mode.mode); await NvUtil.setSettings(VimSettings.normalModeSettings); } // todo(chilli): Do this in a smarter way that generalizes to more categories ... const ignoreKeys: IgnoredKeys = vscode.workspace .getConfiguration('vim') .get('ignoreKeys') as IgnoredKeys; if (mode[0] === 'insert') { for (const key of ignoreKeys.visual.concat(ignoreKeys.normal)) { vscode.commands.executeCommand('setContext', `vim.use_${key}`, true); } for (const key of ignoreKeys.insert) { vscode.commands.executeCommand('setContext', `vim.use_${key}`, false); } } else if (mode[0] === 'visual') { for (const key of ignoreKeys.normal.concat(ignoreKeys.insert)) { vscode.commands.executeCommand('setContext', `vim.use_${key}`, true); } for (const key of ignoreKeys.visual) { vscode.commands.executeCommand('setContext', `vim.use_${key}`, false); } } else { // I assume normal is just all "other" modes. for (const key of ignoreKeys.visual.concat(ignoreKeys.insert)) { vscode.commands.executeCommand('setContext', `vim.use_${key}`, true); } for (const key of ignoreKeys.normal) { vscode.commands.executeCommand('setContext', `vim.use_${key}`, false); } } for (const key of ignoreKeys.all) { vscode.commands.executeCommand('setContext', `vim.use_${key}`, false); } } async redraw(changes: Array<any>) { let highlightsChanged = false; for (let change of changes) { change = change as Array<any>; const name = change[0]; const args = change.slice(1); if (name === 'cursor_goto') { this.cursY = args[0][0]; this.cursX = args[0][1]; } else if (name === 'eol_clear') { for (let i = 0; i < this.size.width - this.cursX; i++) { this.term[this.cursY][this.cursX + i].v = ' '; this.term[this.cursY][this.cursX + i].highlight = {}; } highlightsChanged = true; } else if (name === 'put') { for (const cs of args) { for (const c of cs) { this.term[this.cursY][this.cursX].v = c; this.term[this.cursY][this.cursX].highlight = this.highlighter; this.cursX += 1; } } highlightsChanged = true; } else if (name === 'highlight_set') { this.highlighter = args[args.length - 1][0]; } else if (name === 'mode_change') { this.handleModeChange(args[0]); } else if (name === 'set_scroll_region') { this.scrollRegion = { top: args[0][0], bottom: args[0][1] + 1, left: args[0][2], right: args[0][3] + 1, }; } else if (name === 'resize') { this.resize({ width: args[0][0], height: args[0][1] }); } else if (name === 'scroll') { this.scroll(args[0][0]); } else if (name === 'cmdline_show') { let text = ''; for (let hlText of args[0][0]) { text += hlText[1]; } this.cmdline.text = args[0][2] + args[0][3] + ' '.repeat(args[0][4]) + text.slice(0, args[0][1]) + '|' + text.slice(args[0][1]); this.cmdline.text += ' '.repeat(30 - this.cmdline.text.length % 30); this.cmdline.show(); } else if (name === 'cmdline_hide') { this.cmdline.hide(); } else if ( [ 'cmdline_pos', 'cmdline_special_char', 'cmdline_block_show', 'cmdline_block_append', 'cmdline_block_hide', ].indexOf(name) !== -1 ) { // console.log(name); // console.log(args); } else if (name === 'wildmenu_show') { this.wildmenuItems = args[0][0]; } else if (name === 'wildmenu_hide') { for (const i of this.wildmenu) { i.hide(); } } else if (name === 'wildmenu_select') { // There's logic in here to "batch" wildmenu items into groups of 5 each. const selectIndex = args[0][0]; const NUM_ITEMS_TO_SHOW = 5; const startIndex = selectIndex - selectIndex % NUM_ITEMS_TO_SHOW; const endIndex = selectIndex + 5 - selectIndex % NUM_ITEMS_TO_SHOW; let offset = startIndex > 0 ? 1 : 0; if (offset) { this.wildmenu[0].text = '<'; } for (let i = 0; i < NUM_ITEMS_TO_SHOW; i++) { this.wildmenu[i + offset].text = this.wildmenuItems[startIndex + i]; if (startIndex + i === selectIndex) { this.wildmenu[i + offset].color = new vscode.ThemeColor( 'statusBarItem.prominentBackground' ); } else { this.wildmenu[i + offset].color = undefined; } this.wildmenu[i + offset].show(); } if (endIndex < this.wildmenuItems.length - 1) { this.wildmenu[offset + NUM_ITEMS_TO_SHOW].text = '>'; this.wildmenu[offset + NUM_ITEMS_TO_SHOW].show(); } for (let i = offset + NUM_ITEMS_TO_SHOW + 1; i < this.wildmenu.length; i++) { this.wildmenu[i].hide(); } } else { // console.log(name); // console.log(args); } } // If nvim is connected to a TUI, then we can't get external ui for cmdline/wildmenu. if (Vim.DEBUG) { this.cmdline.text = this.term[this.size.height - 1].map(x => x.v).join(''); this.cmdline.show(); const wildmenuText = this.term[this.size.height - 2] .map(x => x.v) .join('') .replace(/\s+$/, ''); let wildmenu: string[] = wildmenuText.split(/\s+/); // Doesn't always work, who cares??? What a pain in the ass. I don't want to not use regex. let wildmenuIdx = wildmenu.map(x => wildmenuText.indexOf(x)); if (wildmenu[0] === '<' || wildmenu[wildmenu.length - 1] === '>') { for (let i = 0; i < wildmenu.length; i++) { this.wildmenu[i].text = wildmenu[i]; this.wildmenu[i].show(); if ( this.term[this.size.height - 2][wildmenuIdx[i]].highlight.hasOwnProperty('foreground') ) { this.wildmenu[i].color = 'red'; } else { this.wildmenu[i].color = 'white'; } } for (let i = wildmenu.length; i < this.wildmenu.length; i++) { this.wildmenu[i].hide(); } } else { for (let i = 0; i < this.wildmenu.length; i++) { this.wildmenu[i].hide(); } } } if (!vscode.workspace.getConfiguration('vim').get('enableHighlights') || !highlightsChanged) { return; } let curPos = await NvUtil.getCursorPos(); let yOffset = curPos.line - ((await Vim.nv.call('winline')) - 1); let xOffset = curPos.character - ((await Vim.nv.call('wincol')) - 1); let hlDecorations: vscode.Range[][] = []; for (let i = 0; i < this.highlightGroups.length; i++) { hlDecorations.push([]); } let curVimColor = -1; for (let i = 0; i < this.size.height; i++) { let isRange = false; let start = 0; for (let j = 0; j < this.size.width; j++) { if (isRange && !(this.term[i][j].highlight.background === curVimColor)) { isRange = false; hlDecorations[curVimColor - this.OFFSET_COLOR].push( new vscode.Range( new vscode.Position(i + yOffset, start + xOffset), new vscode.Position(i + yOffset, j + xOffset) ) ); curVimColor = -1; } const cellColor = this.term[i][j].highlight.background - this.OFFSET_COLOR; if (!isRange && cellColor >= 0 && cellColor < hlDecorations.length) { start = j; isRange = true; curVimColor = this.term[i][j].highlight.background; } } } for (let i = 0; i < hlDecorations.length; i++) { if (!(this.highlightGroups[i].decorator && vscode.window.activeTextEditor)) { continue; } vscode.window.activeTextEditor!.setDecorations( this.highlightGroups[i].decorator!, hlDecorations[i] ); } } }
the_stack
import { $BuiltinFunction, $Function, $GetPrototypeFromConstructor, } from '../types/function.js'; import { Realm, ExecutionContext, } from '../realm.js'; import { $AnyNonEmpty, $AnyNonEmptyNonError, CompletionType, } from '../types/_shared.js'; import { $Error, $TypeError, } from '../types/error.js'; import { $Undefined, } from '../types/undefined.js'; import { $Object, } from '../types/object.js'; import { $ObjectPrototype, } from './object.js'; import { $List, } from '../types/list.js'; import { $Call, $HostEnsureCanCompileStrings, $DefinePropertyOrThrow, } from '../operations.js'; import { $String, } from '../types/string.js'; import { createSourceFile, ScriptTarget, FunctionDeclaration, } from 'typescript'; import { $FunctionDeclaration, } from '../ast/functions.js'; import { $ESModule, } from '../ast/modules.js'; import { Context, FunctionKind, } from '../ast/_shared.js'; import { $Boolean, } from '../types/boolean.js'; import { $PropertyDescriptor, } from '../types/property-descriptor.js'; import { $Number, } from '../types/number.js'; // http://www.ecma-international.org/ecma-262/#sec-function-objects // 19.2 Function Objects // http://www.ecma-international.org/ecma-262/#sec-function-constructor // 19.2.1 The Function Constructor export class $FunctionConstructor extends $BuiltinFunction<'%Function%'> { // http://www.ecma-international.org/ecma-262/#sec-function.length // 19.2.2.1 Function.length public get length(): $Number<1> { return this.getProperty(this.realm['[[Intrinsics]]'].length)['[[Value]]'] as $Number<1>; } public set length(value: $Number<1>) { this.setDataProperty(this.realm['[[Intrinsics]]'].length, value); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype // 19.2.2.2 Function.prototype public get $prototype(): $FunctionPrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $FunctionPrototype; } public set $prototype(value: $FunctionPrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } public constructor( realm: Realm, functionPrototype: $FunctionPrototype, ) { super(realm, '%Function%', functionPrototype); } // http://www.ecma-international.org/ecma-262/#sec-function-p1-p2-pn-body // 19.2.1.1 Function ( p1 , p2 , … , pn , body ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, argumentsList: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { // 1. Let C be the active function object. // 2. Let args be the argumentsList that was passed to this function by [[Call]] or [[Construct]]. // 3. Return ? CreateDynamicFunction(C, NewTarget, "normal", args). return $CreateDynamicFunction(ctx, this, NewTarget, FunctionKind.normal, argumentsList); } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-function-prototype-object // 19.2.3 Properties of the Function Prototype Object export class $FunctionPrototype extends $Object<'%FunctionPrototype%'> { // http://www.ecma-international.org/ecma-262/#sec-function.prototype.apply // 19.2.3.1 Function.prototype.apply ( thisArg , argArray ) public get $apply(): $FunctionPrototype_apply { return this.getProperty(this.realm['[[Intrinsics]]'].$apply)['[[Value]]'] as $FunctionPrototype_apply; } public set $apply(value: $FunctionPrototype_apply) { this.setDataProperty(this.realm['[[Intrinsics]]'].$apply, value); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype.bind // 19.2.3.2 Function.prototype.bind ( thisArg , ... args ) public get $bind(): $FunctionPrototype_bind { return this.getProperty(this.realm['[[Intrinsics]]'].$bind)['[[Value]]'] as $FunctionPrototype_bind; } public set $bind(value: $FunctionPrototype_bind) { this.setDataProperty(this.realm['[[Intrinsics]]'].$bind, value); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype.call // 19.2.3.3 Function.prototype.call ( thisArg , ... args ) public get $call(): $FunctionPrototype_call { return this.getProperty(this.realm['[[Intrinsics]]'].$call)['[[Value]]'] as $FunctionPrototype_call; } public set $call(value: $FunctionPrototype_call) { this.setDataProperty(this.realm['[[Intrinsics]]'].$call, value); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype.constructor // 19.2.3.4 Function.prototype.constructor public get $constructor(): $FunctionConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $FunctionConstructor; } public set $constructor(value: $FunctionConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype.tostring // 19.2.3.5 Function.prototype.toString ( ) public get $toString(): $FunctionPrototype_toString { return this.getProperty(this.realm['[[Intrinsics]]'].$toString)['[[Value]]'] as $FunctionPrototype_toString; } public set $toString(value: $FunctionPrototype_toString) { this.setDataProperty(this.realm['[[Intrinsics]]'].$toString, value); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype-@@hasinstance // 19.2.3.6 Function.prototype [ @@hasInstance ] ( V ) public get '@@hasInstance'(): $FunctionPrototype_hasInstance { return this.getProperty(this.realm['[[Intrinsics]]']['@@hasInstance'])['[[Value]]'] as $FunctionPrototype_hasInstance; } public set '@@hasInstance'(value: $FunctionPrototype_hasInstance) { this.setDataProperty(this.realm['[[Intrinsics]]']['@@hasInstance'], value); } public constructor( realm: Realm, objectPrototype: $ObjectPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%FunctionPrototype%', objectPrototype, CompletionType.normal, intrinsics.empty); } } export class $FunctionPrototype_apply extends $BuiltinFunction<'Function.prototype.apply'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, 'Function.prototype.apply', proto); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype.apply // 19.2.3.1 Function.prototype.apply ( thisArg , argArray ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [thisArg, argArray]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (thisArg === void 0) { thisArg = intrinsics.undefined; } // 1. Let func be the this value. // 2. If IsCallable(func) is false, throw a TypeError exception. // 3. If argArray is undefined or null, then // 3. a. Perform PrepareForTailCall(). // 3. b. Return ? Call(func, thisArg). // 4. Let argList be ? CreateListFromArrayLike(argArray). // 5. Perform PrepareForTailCall(). // 6. Return ? Call(func, thisArg, argList). throw new Error('Method not implemented.'); } } export class $FunctionPrototype_bind extends $BuiltinFunction<'Function.prototype.bind'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, 'Function.prototype.bind', proto); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype.bind // 19.2.3.2 Function.prototype.bind ( thisArg , ... args ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [thisArg, ...args]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (thisArg === void 0) { thisArg = intrinsics.undefined; } // 1. Let Target be the this value. // 2. If IsCallable(Target) is false, throw a TypeError exception. // 3. Let args be a new (possibly empty) List consisting of all of the argument values provided after thisArg in order. // 4. Let F be ? BoundFunctionCreate(Target, thisArg, args). // 5. Let targetHasLength be ? HasOwnProperty(Target, "length"). // 6. If targetHasLength is true, then // 6. a. Let targetLen be ? Get(Target, "length"). // 6. b. If Type(targetLen) is not Number, let L be 0. // 6. c. Else, // 6. c. i. Set targetLen to ! ToInteger(targetLen). // 6. c. ii. Let L be the larger of 0 and the result of targetLen minus the number of elements of args. // 7. Else, let L be 0. // 8. Perform ! SetFunctionLength(F, L). // 9. Let targetName be ? Get(Target, "name"). // 10. If Type(targetName) is not String, set targetName to the empty string. // 11. Perform SetFunctionName(F, targetName, "bound"). // 12. Return F. throw new Error('Method not implemented.'); } } export class $FunctionPrototype_call extends $BuiltinFunction<'Function.prototype.call'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, 'Function.prototype.call', proto); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype.call // 19.2.3.3 Function.prototype.call ( thisArg , ... args ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [thisArg, ...args]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (thisArg === void 0) { thisArg = intrinsics.undefined; } // 1. Let func be the this value. const func = thisArgument; // 2. If IsCallable(func) is false, throw a TypeError exception. if (!func.isFunction) { return new $TypeError(realm, `Function.prototype.call called on ${func}, but expected a callable function`); } // 3. Let argList be a new empty List. const argList = new $List<$AnyNonEmpty>(); // 4. If this method was called with more than one argument, then in left to right order, starting with the second argument, append each argument as the last element of argList. if (args.length > 0) { argList.push(...args); } // 5. Perform PrepareForTailCall(). ctx.suspend(); realm.stack.pop(); // 6. Return ? Call(func, thisArg, argList). return $Call(realm.stack.top, func as $Function, thisArg as $AnyNonEmptyNonError, argList); } } export class $FunctionPrototype_toString extends $BuiltinFunction<'Function.prototype.toString'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, 'Function.prototype.toString', proto); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype.tostring // 19.2.3.5 Function.prototype.toString ( ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [thisArg, ...args]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; if (thisArg === void 0) { thisArg = intrinsics.undefined; } // 1. Let func be the this value. // 2. If func is a Bound Function exotic object or a built-in function object, then return an implementation-dependent String source code representation of func. The representation must have the syntax of a NativeFunction. Additionally, if func is a Well-known Intrinsic Object and is not identified as an anonymous function, the portion of the returned String that would be matched by PropertyName must be the initial value of the name property of func. // 3. If Type(func) is Object and func has a [[SourceText]] internal slot and Type(func.[[SourceText]]) is String and ! HostHasSourceTextAvailable(func) is true, then return func.[[SourceText]]. // 4. If Type(func) is Object and IsCallable(func) is true, then return an implementation-dependent String source code representation of func. The representation must have the syntax of a NativeFunction. // 5. Throw a TypeError exception. throw new Error('Method not implemented.'); } } export class $FunctionPrototype_hasInstance extends $BuiltinFunction<'Function.prototype.hasInstance'> { public constructor( realm: Realm, proto: $FunctionPrototype, ) { super(realm, 'Function.prototype.hasInstance', proto); } // http://www.ecma-international.org/ecma-262/#sec-function.prototype-@@hasinstance // 19.2.3.6 Function.prototype [ @@hasInstance ] ( V ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [V]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Let F be the this value. // 2. Return ? OrdinaryHasInstance(F, V). throw new Error('Method not implemented.'); } } // http://www.ecma-international.org/ecma-262/#sec-createdynamicfunction // 19.2.1.1.1 Runtime Semantics: CreateDynamicFunction ( constructor , newTarget , kind , args ) export function $CreateDynamicFunction( ctx: ExecutionContext, constructor: $Function, newTarget: $Function | $Undefined, kind: FunctionKind.normal | FunctionKind.generator | FunctionKind.async | FunctionKind.asyncGenerator, args: $List<$AnyNonEmpty>, ): $Function | $Error { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; const stack = realm.stack; // 1. Assert: The execution context stack has at least two elements. // 2. Let callerContext be the second to top element of the execution context stack. const callerContext = stack[stack.length - 2]; // 3. Let callerRealm be callerContext's Realm. const callerRealm = callerContext.Realm; // 4. Let calleeRealm be the current Realm Record. const calleeRealm = realm; // 5. Perform ? HostEnsureCanCompileStrings(callerRealm, calleeRealm). const $HostEnsureCanCompileStringsResult = $HostEnsureCanCompileStrings(ctx, callerRealm, calleeRealm); if ($HostEnsureCanCompileStringsResult.isAbrupt) { return $HostEnsureCanCompileStringsResult; } // 6. If newTarget is undefined, set newTarget to constructor. if (newTarget.isUndefined) { newTarget = constructor; } let $yield: boolean; let $await: boolean; let prefix: 'function' | 'function*' | 'async function' | 'async function*'; let fallbackProto: '%FunctionPrototype%' | '%Generator%' | '%AsyncFunctionPrototype%' | '%AsyncGenerator%'; switch (kind) { // 7. If kind is "normal", then case FunctionKind.normal: // 7. a. Let goal be the grammar symbol FunctionBody[~Yield, ~Await]. // 7. b. Let parameterGoal be the grammar symbol FormalParameters[~Yield, ~Await]. prefix = 'function'; // 7. c. Let fallbackProto be "%FunctionPrototype%". fallbackProto = '%FunctionPrototype%'; break; // 8. Else if kind is "generator", then case FunctionKind.generator: // 8. a. Let goal be the grammar symbol GeneratorBody. // 8. b. Let parameterGoal be the grammar symbol FormalParameters[+Yield, ~Await]. prefix = 'function*'; // 8. c. Let fallbackProto be "%Generator%". fallbackProto = '%Generator%'; break; // 9. Else if kind is "async", then case FunctionKind.async: // 9. a. Let goal be the grammar symbol AsyncFunctionBody. // 9. b. Let parameterGoal be the grammar symbol FormalParameters[~Yield, +Await]. prefix = 'async function'; // 9. c. Let fallbackProto be "%AsyncFunctionPrototype%". fallbackProto = '%AsyncFunctionPrototype%'; break; // 10. Else, case FunctionKind.asyncGenerator: // 10. a. Assert: kind is "async generator". // 10. b. Let goal be the grammar symbol AsyncGeneratorBody. // 10. c. Let parameterGoal be the grammar symbol FormalParameters[+Yield, +Await]. prefix = 'async function*'; // 10. d. Let fallbackProto be "%AsyncGenerator%". fallbackProto = '%AsyncGenerator%'; break; } // 11. Let argCount be the number of elements in args. const argCount = args.length; // 12. Let P be the empty String. let P: $String = intrinsics['']; let $bodyText: $AnyNonEmpty ; let bodyText: $String; // 13. If argCount = 0, let bodyText be the empty String. if (argCount === 0) { $bodyText = intrinsics['']; } // 14. Else if argCount = 1, let bodyText be args[0]. else if (argCount === 1) { $bodyText = args[0]; } // 15. Else argCount > 1, else { // 15. a. Let firstArg be args[0]. const firstArg = args[0]; // 15. b. Set P to ? ToString(firstArg). const $P = firstArg.ToString(ctx); if ($P.isAbrupt) { return $P; } P = $P; // 15. c. Let k be 1. let k = 1; // 15. d. Repeat, while k < argCount - 1 while (k < argCount - 1) { // 15. d. i. Let nextArg be args[k]. const nextArg = args[k]; // 15. d. ii. Let nextArgString be ? ToString(nextArg). const nextArgString = nextArg.ToString(ctx); if (nextArgString.isAbrupt) { return nextArgString; } // 15. d. iii. Set P to the string-concatenation of the previous value of P, "," (a comma), and nextArgString. P = new $String(realm, `${P['[[Value]]']},${nextArgString['[[Value]]']}`); // 15. d. iv. Increase k by 1. ++k; } // 15. e. Let bodyText be args[k]. $bodyText = args[k]; } // 16. Set bodyText to ? ToString(bodyText). $bodyText = $bodyText.ToString(ctx); if ($bodyText.isAbrupt) { return $bodyText; } // eslint-disable-next-line prefer-const bodyText = $bodyText; // 41. Let sourceText be the string-concatenation of prefix, " anonymous(", P, 0x000A (LINE FEED), ") {", 0x000A (LINE FEED), bodyText, 0x000A (LINE FEED), and "}". // NOTE: we bring this step up here for parsing a proper function with TS (since TS doesn't expose an api for parsing just functions). // The exact same text is then later set as [[SourceText]] const sourceText = `${prefix} anonymous(${P['[[Value]]']}\n) {\n${bodyText['[[Value]]']}\n}`; // 17. Let parameters be the result of parsing P, interpreted as UTF-16 encoded Unicode text as described in 6.1.4, using parameterGoal as the goal symbol. Throw a SyntaxError exception if the parse fails. // 18. Let body be the result of parsing bodyText, interpreted as UTF-16 encoded Unicode text as described in 6.1.4, using goal as the goal symbol. Throw a SyntaxError exception if the parse fails. const node = createSourceFile( '', sourceText, ScriptTarget.Latest, ).statements[0] as FunctionDeclaration; const ScriptOrModule = callerContext.ScriptOrModule as $ESModule; const $functionDeclaration = new $FunctionDeclaration( node, ScriptOrModule, Context.Dynamic, -1, ScriptOrModule, calleeRealm, 1, ScriptOrModule.logger, `${ScriptOrModule.path}[Dynamic].FunctionDeclaration`, ); // 19. Let strict be ContainsUseStrict of body. const strict = $functionDeclaration.ContainsUseStrict; // TODO: revisit whether we need to implement these early errors. See what 262 tests fail, if any, etc. // 20. If any static semantics errors are detected for parameters or body, throw a SyntaxError or a ReferenceError exception, depending on the type of the error. If strict is true, the Early Error rules for UniqueFormalParameters:FormalParameters are applied. Parsing and early error detection may be interweaved in an implementation-dependent manner. // 21. If strict is true and IsSimpleParameterList of parameters is false, throw a SyntaxError exception. // 22. If any element of the BoundNames of parameters also occurs in the LexicallyDeclaredNames of body, throw a SyntaxError exception. // 23. If body Contains SuperCall is true, throw a SyntaxError exception. // 24. If parameters Contains SuperCall is true, throw a SyntaxError exception. // 25. If body Contains SuperProperty is true, throw a SyntaxError exception. // 26. If parameters Contains SuperProperty is true, throw a SyntaxError exception. // 27. If kind is "generator" or "async generator", then // 27. a. If parameters Contains YieldExpression is true, throw a SyntaxError exception. // 28. If kind is "async" or "async generator", then // 28. a. If parameters Contains AwaitExpression is true, throw a SyntaxError exception. // 29. If strict is true, then // 29. a. If BoundNames of parameters contains any duplicate elements, throw a SyntaxError exception. // 30. Let proto be ? GetPrototypeFromConstructor(newTarget, fallbackProto). const proto = $GetPrototypeFromConstructor(ctx, newTarget, fallbackProto); if (proto.isAbrupt) { return proto; } // 31. Let F be FunctionAllocate(proto, strict, kind). const F = $Function.FunctionAllocate(ctx, proto, new $Boolean(realm, strict), kind); // 32. Let realmF be F.[[Realm]]. const realmF = F['[[Realm]]']; // 33. Let scope be realmF.[[GlobalEnv]]. const scope = realmF['[[GlobalEnv]]']; // 34. Perform FunctionInitialize(F, Normal, parameters, body, scope). $Function.FunctionInitialize(ctx, F, 'normal', $functionDeclaration, scope); // 35. If kind is "generator", then if (kind === FunctionKind.generator) { // 35. a. Let prototype be ObjectCreate(%GeneratorPrototype%). const prototype = new $Object( realm, 'anonymous generator', intrinsics['%GeneratorPrototype%'], CompletionType.normal, intrinsics.empty, ); // 35. b. Perform DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). $DefinePropertyOrThrow( ctx, F, intrinsics.$prototype, new $PropertyDescriptor( realm, intrinsics.$prototype, { '[[Value]]': prototype, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.false, }, ), ); } // 36. Else if kind is "async generator", then else if (kind === FunctionKind.asyncGenerator) { // 36. a. Let prototype be ObjectCreate(%AsyncGeneratorPrototype%). const prototype = new $Object( realm, 'anonymous async generator', intrinsics['%AsyncGeneratorPrototype%'], CompletionType.normal, intrinsics.empty, ); // 36. b. Perform DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }). $DefinePropertyOrThrow( ctx, F, intrinsics.$prototype, new $PropertyDescriptor( realm, intrinsics.$prototype, { '[[Value]]': prototype, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.false, }, ), ); } // 37. Else if kind is "normal", perform MakeConstructor(F). else if (kind === FunctionKind.normal) { F.MakeConstructor(ctx); } // 38. NOTE: Async functions are not constructable and do not have a [[Construct]] internal method or a "prototype" property. // 39. Perform SetFunctionName(F, "anonymous"). F.SetFunctionName(ctx, new $String(realm, 'anonymous')); // 40. Let prefix be the prefix associated with kind in Table 47. // 41. Let sourceText be the string-concatenation of prefix, " anonymous(", P, 0x000A (LINE FEED), ") {", 0x000A (LINE FEED), bodyText, 0x000A (LINE FEED), and "}". // 42. Set F.[[SourceText]] to sourceText. F['[[SourceText]]'] = new $String(realm, sourceText); // 43. Return F. return F; }
the_stack
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { ListOfSetsOfTranslatableHtmlContentIdsEditorComponent } from './list-of-sets-of-translatable-html-content-ids-editor.component'; describe('ListOfSetsOfTranslatableHtmlContentIdsEditorComponent', () => { let component: ListOfSetsOfTranslatableHtmlContentIdsEditorComponent; let fixture: ComponentFixture<ListOfSetsOfTranslatableHtmlContentIdsEditorComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ListOfSetsOfTranslatableHtmlContentIdsEditorComponent], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed .createComponent(ListOfSetsOfTranslatableHtmlContentIdsEditorComponent); component = fixture.componentInstance; // Here the items are arranged such that choice 1 is on top, with choice 2 // and 3 in the middle and choice 4 in the bottom. component.initArgs = { choices: [ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '3', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '4', val: 'ca_choices_4' } ] }; component.value = [ [ 'ca_choices_1' ], [ 'ca_choices_2' ], [ 'ca_choices_3' ], [ 'ca_choices_4' ] ]; }); it('should initialise component when user adds response', () => { spyOn(component.valueChanged, 'emit'); component.value = [undefined]; component.ngOnInit(); expect(component.choices).toEqual([ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '3', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '4', val: 'ca_choices_4' } ]); expect(component.value).toEqual( [['ca_choices_1'], ['ca_choices_2'], ['ca_choices_3'], ['ca_choices_4']]); expect(component.initValues).toEqual([1, 2, 3, 4]); expect(component.valueChanged.emit).toHaveBeenCalledWith(component.value); expect(component.valueChanged.emit).toHaveBeenCalledTimes(2); }); it('should initialise component when user edits response', () => { component.initArgs.choices[2].selectedRank = '2'; component.initArgs.choices[3].selectedRank = '3'; component.value = [ [ 'ca_choices_1' ], [ 'ca_choices_2', 'ca_choices_3' ], [ 'ca_choices_4' ] ]; component.ngOnInit(); expect(component.choices).toEqual([ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '2', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '3', val: 'ca_choices_4' } ]); expect(component.value).toEqual( [['ca_choices_1'], ['ca_choices_2', 'ca_choices_3'], ['ca_choices_4']]); expect(component.initValues).toEqual([1, 2, 2, 3]); }); it('should rearrage choices when user changes position of choices', () => { component.choices = [ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '3', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '3', val: 'ca_choices_4' } ]; expect(component.value).toEqual([ [ 'ca_choices_1' ], [ 'ca_choices_2' ], [ 'ca_choices_3' ], [ 'ca_choices_4' ] ]); component.selectItem(3); expect(component.value).toEqual( [['ca_choices_1'], ['ca_choices_2'], ['ca_choices_3', 'ca_choices_4']]); }); it('should add choiceId to selected rank that is undefined when user' + ' adds a choice to a new position', () => { component.choices = [ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '3', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '4', val: 'ca_choices_4' } ]; component.value[2] = [ 'ca_choices_3', 'ca_choices_4' ]; component.value[3] = undefined; component.selectItem(3); expect(component.value).toEqual( [['ca_choices_1'], ['ca_choices_2'], ['ca_choices_3'], ['ca_choices_4']]); }); it('should add choice as a subitem of another choice when user allots' + ' two choices the same positoin', () => { component.choices = [ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '2', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '3', val: 'ca_choices_4' } ]; component.value[2] = [ 'ca_choices_3', 'ca_choices_4' ]; component.value = [ [ 'ca_choices_1' ], [ 'ca_choices_2' ], [ 'ca_choices_3', 'ca_choices_4' ] ]; component.selectItem(2); expect(component.value).toEqual( [['ca_choices_1'], ['ca_choices_2', 'ca_choices_3'], ['ca_choices_4']]); }); it('should add choice when usser assigns the choice a position', () => { component.choices = [ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '3', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '4', val: 'ca_choices_4' } ]; component.value[3] = []; component.selectItem(3); }); it('should add empty arrays in between when user skips positions', () => { component.choices = [ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '4', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '4', val: 'ca_choices_4' } ]; component.value = [ [ 'ca_choices_1' ], [ 'ca_choices_2' ] ]; component.selectItem(3); expect(component.value) .toEqual([['ca_choices_1'], ['ca_choices_2'], [], ['ca_choices_4']]); }); it('should warn user when none of the choices are in position 1', () => { spyOn(component.eventBusGroup, 'emit'); component.choices = [ { id: '<p>choice1</p>', selectedRank: '2', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '3', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '4', val: 'ca_choices_4' } ]; component.errorMessage = ''; component.validOrdering = true; component.validateOrdering(); expect(component.errorMessage) .toBe('Please assign some choice at position 1.'); expect(component.eventBusGroup.emit).toHaveBeenCalled(); expect(component.validOrdering).toBeFalse(); }); it('should warn user when one of the positions in the middle are not' + ' occupied by a choice', () => { spyOn(component.eventBusGroup, 'emit'); component.choices = [ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '3', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '3', val: 'ca_choices_3' }, { id: '<p>choice4</p>', selectedRank: '4', val: 'ca_choices_4' } ]; component.errorMessage = ''; component.validOrdering = true; component.validateOrdering(); expect(component.errorMessage) .toBe('Please assign some choice at position 2.'); expect(component.eventBusGroup.emit).toHaveBeenCalled(); expect(component.validOrdering).toBeFalse(); }); it('should return the choices to be displayed in the add ' + 'response editor', () => { component.choices = [ { id: '<p>choice1</p>', selectedRank: '1', val: 'ca_choices_1' }, { id: '<p>choice2</p>', selectedRank: '2', val: 'ca_choices_2' }, { id: '<p>choice3</p>', selectedRank: '3', val: 'ca_choices_3' } ]; let choices = component.allowedChoices(); for (var i = 1; i <= choices.length; i++) { expect(choices[i - 1]).toBe(i); } }); });
the_stack
import FormKit from '../src/FormKit' import { plugin } from '../src/plugin' import defaultConfig from '../src/defaultConfig' import { mount } from '@vue/test-utils' import { nextTick } from 'vue' import { getNode } from '@formkit/core' import { token } from '@formkit/utils' const global: Record<string, Record<string, any>> = { global: { plugins: [[plugin, defaultConfig]], }, } describe('single checkbox', () => { it('can render a single checkbox', () => { const wrapper = mount(FormKit, { props: { type: 'checkbox', }, ...global, }) expect(wrapper.html()).toContain('<input type="checkbox"') }) it('can check a single checkbox with a true value', () => { const wrapper = mount(FormKit, { props: { type: 'checkbox', value: true, }, ...global, }) expect(wrapper.find('input').element.checked).toBe(true) }) it('can uncheck a single checkbox with a false value', () => { const wrapper = mount(FormKit, { props: { type: 'checkbox', value: false, }, ...global, }) expect(wrapper.find('input').element.checked).toBe(false) }) it('can check/uncheck single checkbox with v-model', async () => { const wrapper = mount( { data() { return { value: false, } }, template: '<FormKit :delay="0" type="checkbox" v-model="value" />', }, { ...global, } ) const checkbox = wrapper.find('input') expect(checkbox.element.checked).toBe(false) wrapper.setData({ value: true }) await nextTick() expect(checkbox.element.checked).toBe(true) checkbox.element.checked = false checkbox.trigger('input') await new Promise((r) => setTimeout(r, 5)) expect(wrapper.vm.value).toBe(false) }) it('can use custom on-value and off-value', async () => { const wrapper = mount( { data() { return { value: 'foo', } }, template: '<FormKit :delay="0" type="checkbox" on-value="foo" off-value="bar" v-model="value" />', }, { ...global, } ) const checkbox = wrapper.find('input') expect(checkbox.element.checked).toBe(true) wrapper.setData({ value: 'bar' }) await nextTick() expect(checkbox.element.checked).toBe(false) checkbox.element.checked = true checkbox.trigger('input') await new Promise((r) => setTimeout(r, 5)) expect(wrapper.vm.value).toBe('foo') }) it('can use an object as an on-value and off-value', () => { const wrapper = mount( { template: '<FormKit :delay="0" type="checkbox" :on-value="{ a: 123 }" :off-value="{ b: 456 }" :value="{ a: 123 }" />', }, { ...global, } ) const checkbox = wrapper.find('input') expect(checkbox.element.checked).toBe(true) }) it('outputs a data-disabled on the wrapper', () => { const wrapper = mount(FormKit, { props: { type: 'checkbox', disabled: true, value: false, }, ...global, }) expect(wrapper.find('.formkit-wrapper[data-disabled]').exists()).toBe(true) }) }) describe('multiple checkboxes', () => { it('can render multiple checkboxes with semantic markup', () => { const wrapper = mount(FormKit, { props: { id: 'my-id', type: 'checkbox', label: 'All checkboxes', help: 'help-text', name: 'mybox', options: ['foo', 'bar', 'baz'], }, ...global, }) expect(wrapper.html()) .toBe(`<div class="formkit-outer" data-type="checkbox"> <fieldset id="my-id" class="formkit-fieldset" aria-describedby="help-my-id"> <legend class="formkit-legend">All checkboxes</legend> <div id="help-my-id" class="formkit-help">help-text</div> <ul class="formkit-options"> <li class="formkit-option"><label class="formkit-wrapper"> <div class="formkit-inner"> <!----><input type="checkbox" class="formkit-input" name="mybox" id="mybox-option-foo" value="foo"><span class="formkit-decorator" aria-hidden="true"></span> <!----> </div><span class="formkit-label">foo</span> </label> <!----> </li> <li class="formkit-option"><label class="formkit-wrapper"> <div class="formkit-inner"> <!----><input type="checkbox" class="formkit-input" name="mybox" id="mybox-option-bar" value="bar"><span class="formkit-decorator" aria-hidden="true"></span> <!----> </div><span class="formkit-label">bar</span> </label> <!----> </li> <li class="formkit-option"><label class="formkit-wrapper"> <div class="formkit-inner"> <!----><input type="checkbox" class="formkit-input" name="mybox" id="mybox-option-baz" value="baz"><span class="formkit-decorator" aria-hidden="true"></span> <!----> </div><span class="formkit-label">baz</span> </label> <!----> </li> </ul> </fieldset> <!----> </div>`) }) it('multi-checkboxes set array values immediately', () => { mount(FormKit, { props: { id: 'my-id', type: 'checkbox', options: ['foo', 'bar', 'baz'], }, ...global, }) const node = getNode('my-id') expect(node?.value).toEqual([]) }) it('can check and uncheck boxes via v-model', async () => { const wrapper = mount( { data() { return { values: ['foo', 'baz'], } }, template: '<FormKit :delay="0" type="checkbox" v-model="values" :options="[\'foo\', \'bar\', \'baz\']" />', }, { ...global } ) // TODO - Remove the .get() here when @vue/test-utils > rc.19 const inputs = wrapper.get('fieldset').findAll('input') expect(inputs[0].element.checked).toBe(true) expect(inputs[1].element.checked).toBe(false) expect(inputs[2].element.checked).toBe(true) inputs[0].element.checked = false inputs[0].trigger('input') await new Promise((r) => setTimeout(r, 5)) expect(wrapper.vm.values).toEqual(['baz']) wrapper.setData({ values: ['foo', 'bar'] }) await nextTick() expect(inputs[0].element.checked).toBe(true) expect(inputs[1].element.checked).toBe(true) expect(inputs[2].element.checked).toBe(false) }) it('can render options from an array of objects with ids and help text', () => { const wrapper = mount(FormKit, { props: { type: 'checkbox', name: 'countries', options: [ { value: 'it', label: 'Italy', id: 'italy', help: 'Good food here', attrs: { disabled: true }, }, { value: 'de', label: 'Germany', id: 'germany', help: 'Good cars here', }, { value: 'fr', label: 'France', id: 'france', help: 'Crickets' }, ], }, ...global, }) expect(wrapper.find('li').html()).toBe( `<li class="formkit-option" data-disabled="true"><label class="formkit-wrapper"> <div class="formkit-inner"> <!----><input type="checkbox" class="formkit-input" name="countries" disabled="" id="countries-option-it" aria-describedby="help-countries-option-it" value="it"><span class="formkit-decorator" aria-hidden="true"></span> <!----> </div><span class="formkit-label">Italy</span> </label> <div id="help-countries-option-it" class="formkit-option-help">Good food here</div> </li>` ) }) it('can set the default value from a v-modeled form', () => { const wrapper = mount( { data() { return { values: { letters: ['A', 'C'], }, } }, template: ` <FormKit type="form" v-model="values"> <FormKit type="checkbox" :options="['A', 'B', 'C']" name="letters" /> </FormKit>`, }, { ...global, } ) // TODO - Remove the .get() here when @vue/test-utils > rc.19 const checkboxes = wrapper.get('form').findAll('input') const values = checkboxes.map((box) => box.element.checked) expect(values).toEqual([true, false, true]) expect(wrapper.vm.values).toEqual({ letters: ['A', 'C'] }) }) it('can have no label and still render its checkbox labels', () => { const wrapper = mount(FormKit, { props: { type: 'checkbox', options: ['A', 'B', 'C'], }, ...global, }) expect(wrapper.find('legend').exists()).toBeFalsy() // TODO - Remove the .get() here when @vue/test-utils > rc.19 expect(wrapper.get('fieldset').findAll('label').length).toBe(3) expect(wrapper.html()).toContain('<span class="formkit-label">A</span>') }) }) describe('non string values for checkboxes', () => { it('can have numbers as values', async () => { const id = token() const wrapper = mount(FormKit, { props: { id, delay: 0, type: 'checkbox', value: [2, 3], options: [ { value: 1, label: 'One' }, { value: 2, label: 'Two' }, { value: 3, label: 'Three' }, ], }, ...global, }) const checkboxes = wrapper.find('div').findAll('input') expect(checkboxes.map((input) => input.element.checked)).toEqual([ false, true, true, ]) checkboxes[0].element.checked = false checkboxes[0].trigger('input') await new Promise((r) => setTimeout(r, 10)) expect(checkboxes.map((input) => input.element.checked)).toEqual([ true, true, true, ]) expect(getNode(id)!.value).toEqual([2, 3, 1]) }) it('can have objects as values', async () => { const id = token() const wrapper = mount(FormKit, { props: { id, delay: 0, type: 'checkbox', value: [{ zip: '02108' }], options: [ { value: null, label: 'Atlanta' }, { value: { zip: '02108' }, label: 'Boston' }, { value: { zip: '80014' }, label: 'Denver' }, ], }, ...global, }) const checkboxes = wrapper.find('div').findAll('input') expect(checkboxes.map((input) => input.element.checked)).toEqual([ false, true, false, ]) checkboxes[0].element.checked = false checkboxes[0].trigger('input') await new Promise((r) => setTimeout(r, 10)) expect(checkboxes.map((input) => input.element.checked)).toEqual([ true, true, false, ]) expect(getNode(id)!.value).toEqual([{ zip: '02108' }, null]) }) })
the_stack
import * as DynamoDb from 'aws-sdk/clients/dynamodb' import { organization1CreatedAt, organization1Employee1CreatedAt, organization1Employee2CreatedAt, organization1LastUpdated, organizationFromDb, } from '../../test/data/organization-dynamodb.data' import { productFromDb } from '../../test/data/product-dynamodb.data' import { Birthday, Employee, Gift, Id, ModelWithDefaultValue, ModelWithCustomMapperModel, ModelWithDateAsHashKey, ModelWithDateAsIndexHashKey, ModelWithNonDecoratedEnum, ModelWithoutCustomMapper, ModelWithoutCustomMapperOnIndex, Organization, OrganizationEvent, Product, ProductNested, SimpleModel, SimpleWithCompositePartitionKeyModel, SimpleWithPartitionKeyModel, SimpleWithRenamedCompositePartitionKeyModel, SimpleWithRenamedPartitionKeyModel, StringType, Type, ModelWithCustomMapperAndDefaultValue, MyProp, } from '../../test/models' import { IdMapper } from '../../test/models/model-with-custom-mapper.model' import { ModelWithEmptyValues } from '../../test/models/model-with-empty-values' import { ModelWithNestedModelWithCustomMapper, NestedModelWithCustomMapper, } from '../../test/models/model-with-nested-model-with-custom-mapper.model' import { NestedComplexModel } from '../../test/models/nested-complex.model' import { metadataForModel } from '../decorator/metadata/metadata-for-model.function' import { PropertyMetadata } from '../decorator/metadata/property-metadata.model' import { createKeyAttributes, createToKeyFn, fromDb, fromDbOne, toDb, toDbOne, toKey } from './mapper' import { Attribute, Attributes, BooleanAttribute, ListAttribute, MapAttribute, NullAttribute, NumberAttribute, StringAttribute, StringSetAttribute, } from './type/attribute.type' describe('Mapper', () => { describe('should map single values', () => { describe('to db', () => { it('string', () => { const attrValue = <StringAttribute>toDbOne('foo')! expect(attrValue).toBeDefined() expect(attrValue.S).toBeDefined() expect(attrValue.S).toBe('foo') }) it('string (empty)', () => { const attrValue = <StringAttribute>toDbOne('')! expect(attrValue.S).toStrictEqual('') }) it('number', () => { const attrValue = <NumberAttribute>toDbOne(3)! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('N') expect(attrValue.N).toBe('3') }) it('number (NaN)', () => { const attrValue = <NumberAttribute>toDbOne(NaN)! expect(attrValue).toBeNull() }) it('boolean', () => { const attrValue = <BooleanAttribute>toDbOne(false)! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('BOOL') expect(attrValue.BOOL).toBe(false) }) it('null', () => { const attrValue = <NullAttribute>toDbOne(null)! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('NULL') expect(attrValue.NULL).toBe(true) }) it('enum (number)', () => { const attrValue = <NumberAttribute>toDbOne(Type.FirstType)! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('N') expect(attrValue.N).toBe('0') }) it('enum (string)', () => { const attrValue = <StringAttribute>toDbOne(StringType.FirstType)! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('S') expect(attrValue.S).toBe('first') }) it('enum (propertyMetadata -> no enum decorator)', () => { const attrValue: Attribute = <MapAttribute>toDbOne(Type.FirstType, <any>{ typeInfo: { type: Object }, })! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('M') expect(attrValue.M).toEqual({}) }) it('array -> L(ist) (no explicit type)', () => { const attrValue = <ListAttribute<StringAttribute>>toDbOne(['foo', 'bar'])! expect(attrValue).toEqual({ L: [{ S: 'foo' }, { S: 'bar' }] }) }) it('array -> L(ist) (homogeneous, no duplicates, explicit type)', () => { const propertyMetadata = <Partial<PropertyMetadata<any>>>{ isSortedCollection: true, typeInfo: { type: Array, }, } const attrValue = <ListAttribute<StringAttribute>>toDbOne(['foo', 'bar'], <any>propertyMetadata)! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('L') expect(keyOf(attrValue.L[0])).toBe('S') expect(attrValue.L[0].S).toBe('foo') expect(keyOf(attrValue.L[1])).toBe('S') expect(attrValue.L[1].S).toBe('bar') }) it('array -> L(ist) (heterogeneous, no duplicates)', () => { const attrValue = <ListAttribute>toDbOne(['foo', 56, true])! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('L') expect(attrValue.L).toBeDefined() expect(attrValue.L.length).toBe(3) const foo = <StringAttribute>attrValue.L[0] expect(foo).toBeDefined() expect(keyOf(foo)).toBe('S') expect(foo.S).toBe('foo') const no = <NumberAttribute>attrValue.L[1] expect(no).toBeDefined() expect(keyOf(no)).toBe('N') expect(no.N).toBe('56') const bool = <BooleanAttribute>attrValue.L[2] expect(bool).toBeDefined() expect(keyOf(bool)).toBe('BOOL') expect(bool.BOOL).toBe(true) }) it('array -> L(ist) (homogeneous, complex type)', () => { const attrValue = <ListAttribute>toDbOne([ { name: 'max', age: 25, sortedSet: null }, { name: 'anna', age: 65, sortedSet: null }, ])! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('L') const employee1 = <MapAttribute<Employee>>attrValue.L[0] expect(employee1).toBeDefined() expect(keyOf(employee1)).toBe('M') expect(Object.keys(employee1.M).length).toBe(2) expect(employee1.M.name).toBeDefined() expect(keyOf(employee1.M.name)).toBe('S') expect((<StringAttribute>employee1.M.name).S).toBe('max') expect(employee1.M.age).toBeDefined() expect(keyOf(employee1.M.age)).toBe('N') expect((<NumberAttribute>employee1.M.age).N).toBe('25') }) it('heterogenous Set without decorator should throw', () => { expect(() => toDbOne(new Set(['foo', 'bar', 25]))).toThrow() }) it('heterogenous Set with decorator to L(ist)', () => { const meta: PropertyMetadata<any, any> = <any>{ typeInfo: { type: Set, }, } const attrValue = toDbOne(new Set(['foo', 'bar', 25]), meta) expect(attrValue).toEqual({ L: [{ S: 'foo' }, { S: 'bar' }, { N: '25' }] }) }) it('Set (empty) -> null', () => { const attrValue = <NullAttribute>toDbOne(new Set())! expect(attrValue).toBeNull() }) it('Set of objects without decorator should throw', () => { expect(() => toDbOne( new Set([ { name: 'foo', age: 7 }, { name: 'bar', age: 42 }, ]), ), ).toThrow() }) it('Set of objects with decorator -> L(ist)', () => { const meta: PropertyMetadata<any> = <any>{ typeInfo: { type: Set, }, } const attrValue = <ListAttribute>toDbOne( new Set([ { name: 'foo', age: 7 }, { name: 'bar', age: 42 }, ]), meta, ) expect(attrValue).toEqual({ L: [{ M: { name: { S: 'foo' }, age: { N: '7' } } }, { M: { name: { S: 'bar' }, age: { N: '42' } } }], }) }) it('simple object', () => { const attrValue = <MapAttribute<{ name: StringAttribute; age: NumberAttribute }>>( toDbOne({ name: 'foo', age: 56 })! ) expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('M') // name expect(attrValue.M.name).toBeDefined() expect(keyOf(attrValue.M.name)).toBe('S') expect((<StringAttribute>attrValue.M.name).S).toBe('foo') // age expect(attrValue.M.age).toBeDefined() expect(keyOf(attrValue.M.age)).toBe('N') expect((<NumberAttribute>attrValue.M.age).N).toBe('56') }) it('complex object', () => { interface ObjType { name: StringAttribute age: NumberAttribute children: ListAttribute } const attrValue = <MapAttribute<ObjType>>toDbOne({ name: 'Max', age: 35, children: [ { name: 'Anna', age: 5 }, { name: 'Hans', age: 7 }, ], })! expect(attrValue).toBeDefined() expect(keyOf(attrValue)).toBe('M') const nameAttr = <StringAttribute>attrValue.M.name // name expect(nameAttr).toBeDefined() expect(keyOf(nameAttr)).toBe('S') expect(nameAttr.S).toBe('Max') // age expect(attrValue.M.age).toBeDefined() expect(keyOf(attrValue.M.age)).toBe('N') expect((<NumberAttribute>attrValue.M.age).N).toBe('35') // children expect(attrValue.M.children).toBeDefined() expect(keyOf(attrValue.M.children)).toBe('L') expect((<ListAttribute>attrValue.M.children).L.length).toBe(2) expect(keyOf((<ListAttribute>attrValue.M.children).L[0])).toBe('M') expect(keyOf((<ListAttribute>attrValue.M.children).L[1])).toBe('M') const firstChild = <MapAttribute<ObjType>>(<ListAttribute>attrValue.M.children).L[0] // first child expect(firstChild.M.name).toBeDefined() expect(keyOf(firstChild.M.name)).toBe('S') expect((<StringAttribute>firstChild.M.name).S).toBe('Anna') expect(firstChild.M.age).toBeDefined() expect(keyOf(firstChild.M.age)).toBe('N') expect((<NumberAttribute>firstChild.M.age).N).toBe('5') const secondChild: MapAttribute<ObjType> = <MapAttribute<ObjType>>(<ListAttribute>attrValue.M.children).L[1] // second child expect(secondChild.M.name).toBeDefined() expect(keyOf(secondChild.M.name)).toBe('S') expect((<StringAttribute>secondChild.M.name).S).toBe('Hans') expect(secondChild.M.age).toBeDefined() expect(keyOf(secondChild.M.age)).toBe('N') expect((<NumberAttribute>secondChild.M.age).N).toBe('7') }) }) describe('from db', () => { it('S -> String', () => { const attrValue = { S: 'foo' } expect(fromDbOne(attrValue)).toBe('foo') }) it('N -> Number', () => { const attrValue = { N: '56' } expect(fromDbOne(attrValue)).toBe(56) }) it('BOOL -> Boolean', () => { const attrValue = { BOOL: true } expect(fromDbOne(attrValue)).toBe(true) }) it('NULL -> null', () => { const attrValue = { NULL: true } expect(fromDbOne(attrValue)).toBe(null) }) it('SS -> set', () => { const attrValue = { SS: ['foo', 'bar'] } const set: Set<string> = fromDbOne(attrValue) // noinspection SuspiciousInstanceOfGuard expect(set instanceof Set).toBeTruthy() expect([...set]).toEqual(['foo', 'bar']) }) it('SS -> array', () => { const propertyMetadata = <Partial<PropertyMetadata<any>>>{ typeInfo: { type: Array }, } const attrValue = { SS: ['foo', 'bar'] } const arr = fromDbOne<string[]>(attrValue, <any>propertyMetadata) expect(Array.isArray(arr)).toBeTruthy() expect(arr).toEqual(['foo', 'bar']) }) it('NS -> set', () => { const attrValue = { NS: ['45', '2'] } const set = fromDbOne<Set<number>>(attrValue) // noinspection SuspiciousInstanceOfGuard expect(set instanceof Set).toBeTruthy() expect(set.size).toBe(2) expect(Array.from(set)[0]).toBe(45) expect(Array.from(set)[1]).toBe(2) }) it('NS -> array', () => { const propertyMetadata = <Partial<PropertyMetadata<any>>>{ typeInfo: { type: Array }, } const attrValue = { NS: ['45', '2'] } const arr = fromDbOne<number[]>(attrValue, <any>propertyMetadata) expect(Array.isArray(arr)).toBeTruthy() expect(arr.length).toBe(2) expect(arr[0]).toBe(45) expect(arr[1]).toBe(2) }) it('L -> array', () => { const attrValue = { L: [{ S: 'foo' }, { N: '45' }, { BOOL: true }] } const arr: any[] = fromDbOne<any[]>(attrValue) expect(Array.isArray(arr)).toBeTruthy() expect(arr.length).toBe(3) expect(arr[0]).toBe('foo') expect(arr[1]).toBe(45) expect(arr[2]).toBe(true) }) it('L -> set', () => { const propertyMetadata = <Partial<PropertyMetadata<any>>>{ typeInfo: { type: Set }, } const attrValue = { L: [{ S: 'foo' }, { N: '45' }, { BOOL: true }] } const set = fromDbOne<Set<any>>(attrValue, <any>propertyMetadata) // noinspection SuspiciousInstanceOfGuard expect(set instanceof Set).toBeTruthy() expect(set.size).toBe(3) expect(Array.from(set)[0]).toBe('foo') expect(Array.from(set)[1]).toBe(45) expect(Array.from(set)[2]).toBe(true) }) it('M', () => { const attrValue = { M: { name: { S: 'name' }, age: { N: '56' }, active: { BOOL: true }, siblings: { SS: ['hans', 'andi', 'dora'] }, }, } const obj = fromDbOne<any>(attrValue) expect(obj.name).toBe('name') expect(obj.age).toBe(56) expect(obj.active).toBe(true) expect(obj.siblings).toBeDefined() expect(obj.siblings instanceof Set).toBeTruthy() expect(obj.siblings.size).toBe(3) expect(Array.from(obj.siblings)[0]).toBe('hans') expect(Array.from(obj.siblings)[1]).toBe('andi') expect(Array.from(obj.siblings)[2]).toBe('dora') }) }) }) describe('should map model', () => { describe('to db', () => { describe('model class created with new', () => { let organization: Organization let organizationAttrMap: Attributes<Organization> let createdAt: Date let lastUpdated: Date let createdAtDateEmployee1: Date let createdAtDateEmployee2: Date let birthday1Date: Date let birthday2Date: Date beforeEach(() => { organization = new Organization() organization.id = 'myId' organization.name = 'shiftcode GmbH' createdAt = new Date() organization.createdAtDate = createdAt lastUpdated = new Date('2017-03-21') organization.lastUpdated = lastUpdated organization.active = true organization.count = 52 organization.domains = ['shiftcode.ch', 'shiftcode.io', 'shiftcode.it'] organization.randomDetails = ['sample', 26, true] createdAtDateEmployee1 = new Date('2017-03-05') createdAtDateEmployee2 = new Date() organization.employees = [ new Employee('max', 50, createdAtDateEmployee1, []), new Employee('anna', 27, createdAtDateEmployee2, []), ] organization.cities = new Set(['zürich', 'bern']) birthday1Date = new Date('1975-03-05') birthday2Date = new Date('1987-07-07') organization.birthdays = new Set([ new Birthday(birthday1Date, 'ticket to rome', 'camper van'), new Birthday(birthday2Date, 'car', 'gin'), ]) organization.awards = new Set(['good, better, shiftcode', 'just kiddin']) const events = new Set() events.add(new OrganizationEvent('shift the web', 1520)) organization.events = events organization.transient = 'the value which is marked as transient' organizationAttrMap = toDb(organization, Organization) }) describe('creates correct attribute map', () => { it('all properties are mapped', () => { expect(Object.keys(organizationAttrMap).length).toBe(13) }) it('id', () => { expect(organizationAttrMap.id).toEqual({ S: 'myId' }) }) it('createdAtDate', () => { expect(organizationAttrMap.createdAtDate).toBeDefined() expect((<StringAttribute>organizationAttrMap.createdAtDate).S).toBeDefined() expect((<StringAttribute>organizationAttrMap.createdAtDate).S).toBe(createdAt.toISOString()) }) it('lastUpdated', () => { expect(organizationAttrMap.lastUpdated).toBeDefined() expect((<StringAttribute>organizationAttrMap.lastUpdated).S).toBeDefined() expect((<StringAttribute>organizationAttrMap.lastUpdated).S).toBe(lastUpdated.toISOString()) }) it('active', () => { expect(organizationAttrMap.active).toBeDefined() expect((<BooleanAttribute>organizationAttrMap.active).BOOL).toBeDefined() expect((<BooleanAttribute>organizationAttrMap.active).BOOL).toBe(true) }) it('count', () => { expect(organizationAttrMap.count).toEqual({ N: '52' }) }) it('domains', () => { expect(organizationAttrMap.domains).toEqual({ L: ['shiftcode.ch', 'shiftcode.io', 'shiftcode.it'].map((v) => ({ S: v })), }) }) it('random details', () => { expect(organizationAttrMap.randomDetails).toBeDefined() const randomDetails = (<ListAttribute>organizationAttrMap.randomDetails).L expect(randomDetails).toBeDefined() expect(randomDetails.length).toBe(3) expect(keyOf(randomDetails[0])).toBe('S') expect((<StringAttribute>randomDetails[0]).S).toBe('sample') expect(keyOf(randomDetails[1])).toBe('N') expect((<NumberAttribute>randomDetails[1]).N).toBe('26') expect(keyOf(randomDetails[2])).toBe('BOOL') expect((<BooleanAttribute>randomDetails[2]).BOOL).toBe(true) }) it('employees', () => { expect(organizationAttrMap.employees).toBeDefined() const employeesL = (<ListAttribute>organizationAttrMap.employees).L expect(employeesL).toBeDefined() expect(employeesL.length).toBe(2) expect(employeesL[0]).toBeDefined() expect((<MapAttribute>employeesL[0]).M).toBeDefined() // test employee1 const employee1 = (<MapAttribute<Employee>>employeesL[0]).M expect(employee1.name).toBeDefined() expect((<StringAttribute>employee1.name).S).toBeDefined() expect((<StringAttribute>employee1.name).S).toBe('max') expect(employee1['age']).toBeDefined() expect((<NumberAttribute>employee1.age).N).toBeDefined() expect((<NumberAttribute>employee1.age).N).toBe('50') expect(employee1['createdAt']).toBeDefined() expect((<StringAttribute>employee1.createdAt).S).toBeDefined() expect((<StringAttribute>employee1.createdAt).S).toBe(createdAtDateEmployee1.toISOString()) // test employee2 const employee2: DynamoDb.MapAttributeValue = (<MapAttribute>employeesL[1]).M expect(employee2['name']).toBeDefined() expect(employee2['name'].S).toBeDefined() expect(employee2['name'].S).toBe('anna') expect(employee2['age']).toBeDefined() expect(employee2['age'].N).toBeDefined() expect(employee2['age'].N).toBe('27') expect(employee2['createdAt']).toBeDefined() expect(employee2['createdAt'].S).toBeDefined() expect(employee2['createdAt'].S).toBe(createdAtDateEmployee2.toISOString()) }) it('cities', () => { expect(organizationAttrMap.cities).toBeDefined() const citiesSS = (<StringSetAttribute>organizationAttrMap.cities).SS expect(citiesSS).toBeDefined() expect(citiesSS.length).toBe(2) expect(citiesSS[0]).toBe('zürich') expect(citiesSS[1]).toBe('bern') }) it('birthdays', () => { expect(organizationAttrMap.birthdays).toBeDefined() const birthdays = (<ListAttribute>organizationAttrMap.birthdays).L expect(birthdays).toBeDefined() expect(birthdays.length).toBe(2) expect(keyOf(birthdays[0])).toBe('M') // birthday 1 const birthday1 = (<MapAttribute<Birthday>>birthdays[0]).M expect(birthday1['date']).toBeDefined() expect(keyOf(birthday1.date)).toBe('S') expect((<StringAttribute>birthday1['date']).S).toBe(birthday1Date.toISOString()) expect(birthday1.presents).toBeDefined() expect(keyOf(birthday1.presents)).toBe('L') expect((<ListAttribute>birthday1.presents).L.length).toBe(2) expect(keyOf((<ListAttribute>birthday1.presents).L[0])).toBe('M') expect(keyOf((<ListAttribute>birthday1.presents).L[0])).toBe('M') const birthday1gift1 = (<MapAttribute<Gift>>(<ListAttribute>birthday1.presents).L[0]).M expect(birthday1gift1.description).toBeDefined() expect(keyOf(birthday1gift1.description)).toBe('S') expect((<StringAttribute>birthday1gift1.description).S).toBe('ticket to rome') const birthday1gift2 = (<MapAttribute<Gift>>(<ListAttribute>birthday1.presents).L[1]).M expect(birthday1gift2.description).toBeDefined() expect(keyOf(birthday1gift2.description)).toBe('S') expect((<StringAttribute>birthday1gift2.description).S).toBe('camper van') // birthday 2 const birthday2 = (<MapAttribute<Birthday>>birthdays[1]).M expect(birthday2.date).toBeDefined() expect(keyOf(birthday2.date)).toBe('S') expect((<StringAttribute>birthday2.date).S).toBe(birthday2Date.toISOString()) expect(birthday2.presents).toBeDefined() expect(keyOf(birthday2.presents)).toBe('L') expect((<ListAttribute>birthday2.presents).L.length).toBe(2) expect(keyOf((<ListAttribute>birthday2.presents).L[0])).toBe('M') expect(keyOf((<ListAttribute>birthday2.presents).L[0])).toBe('M') const birthday2gift1 = (<MapAttribute<Gift>>(<ListAttribute>birthday2.presents).L[0]).M expect(birthday2gift1.description).toBeDefined() expect(keyOf(birthday2gift1.description)).toBe('S') expect((<StringAttribute>birthday2gift1.description).S).toBe('car') const birthday2gift2 = (<MapAttribute<Gift>>(<ListAttribute>birthday2.presents).L[1]).M expect(birthday2gift2.description).toBeDefined() expect(keyOf(birthday2gift2.description)).toBe('S') expect((<StringAttribute>birthday2gift2.description).S).toBe('gin') }) it('awards', () => { expect(organizationAttrMap.awards).toBeDefined() const awards = (<ListAttribute>organizationAttrMap.awards).L expect(awards).toBeDefined() expect(awards.length).toBe(2) expect(keyOf(awards[0])).toBe('S') expect((<StringAttribute>awards[0]).S).toBe('good, better, shiftcode') expect(keyOf(awards[1])).toBe('S') expect((<StringAttribute>awards[1]).S).toBe('just kiddin') }) it('events', () => { expect(organizationAttrMap.events).toBeDefined() const events = (<ListAttribute>organizationAttrMap.events).L expect(events).toBeDefined() expect(events.length).toBe(1) const event = <MapAttribute<OrganizationEvent>>events[0] const eventValue = event.M expect(keyOf(event)).toBe('M') expect(eventValue.name).toBeDefined() expect(keyOf(eventValue.name)).toBe('S') expect((<StringAttribute>eventValue.name).S).toBe('shift the web') expect(eventValue.participantCount).toBeDefined() expect(keyOf(eventValue.participantCount)).toBe('N') expect((<NumberAttribute>eventValue.participantCount).N).toBe('1520') }) it('transient', () => { expect(organizationAttrMap.transient).toBeUndefined() }) // an empty set is not a valid attribute value to be persisted it('emptySet', () => { expect(organizationAttrMap.emptySet).toBeUndefined() // expect(organizationAttrMap.emptySet).toEqual({ NULL: true }) }) }) }) describe('model with custom mapper', () => { it('should map using the custom mapper', () => { const model = new ModelWithCustomMapperModel() model.id = new Id(20, 2017) const toDbVal: Attributes<ModelWithCustomMapperModel> = toDb(model, ModelWithCustomMapperModel) expect(toDbVal.id).toBeDefined() expect(keyOf(toDbVal.id)).toBe('S') expect((<StringAttribute>toDbVal.id).S).toBe('00202017') }) }) describe('model with autogenerated value for id', () => { it('should create an id', () => { const toDbVal = toDb(new ModelWithDefaultValue(), ModelWithDefaultValue) expect(toDbVal.id).toBeDefined() expect(keyOf(toDbVal.id)).toBe('S') expect((<StringAttribute>toDbVal.id).S).toMatch(/^generated-id-\d{1,3}$/) }) }) describe('model with default value provider AND custom mapper', () => { it('should create correct value', () => { const toDbVal = toDb(new ModelWithCustomMapperAndDefaultValue(), ModelWithCustomMapperAndDefaultValue) expect(toDbVal.myProp).toBeDefined() expect(keyOf(toDbVal.myProp)).toBe('S') expect((<StringAttribute>toDbVal.myProp).S).toBe(MyProp.default().toString()) }) }) describe('model with combined decorators', () => { const toDbValue: SimpleWithRenamedPartitionKeyModel = { id: 'idValue', age: 30 } const mapped = toDb(toDbValue, SimpleWithRenamedPartitionKeyModel) expect(mapped).toEqual({ custom_id: { S: 'idValue' }, age: { N: '30' } }) }) describe('model with non string/number/binary keys', () => { it('should accept date as HASH or RANGE key', () => { const now = new Date() const toDbVal: DynamoDb.AttributeMap = toDb(new ModelWithDateAsHashKey(now), ModelWithDateAsHashKey) expect(toDbVal.startDate.S).toBeDefined() expect(toDbVal.startDate.S).toEqual(now.toISOString()) }) it('should accept date as HASH or RANGE key on GSI', () => { const now = new Date() const toDbVal: DynamoDb.AttributeMap = toDb( new ModelWithDateAsIndexHashKey(0, now), ModelWithDateAsIndexHashKey, ) expect(toDbVal.creationDate.S).toBeDefined() expect(toDbVal.creationDate.S).toEqual(now.toISOString()) }) it('should throw error when no custom mapper was defined', () => { expect(() => { toDb(new ModelWithoutCustomMapper('key', 'value', 'otherValue'), ModelWithoutCustomMapper) }).toThrow() expect(() => { toDb(new ModelWithoutCustomMapperOnIndex('id', 'key', 'value'), ModelWithoutCustomMapperOnIndex) }).toThrow() }) }) describe('model with complex property values (decorators)', () => { let toDbVal: Attributes<Product> beforeEach(() => { toDbVal = toDb(new Product(), Product) }) it('nested value', () => { const nested = <MapAttribute<NestedComplexModel>>toDbVal.nestedValue expect(toDbVal.nestedValue).toBeDefined() expect(nested.M).toBeDefined() expect(Object.keys(nested.M).length).toBe(1) expect(nested.M.sortedSet).toBeDefined() expect(keyOf(nested.M.sortedSet)).toBe('L') }) it('list', () => { const list = <ListAttribute>toDbVal.list expect(list).toBeDefined() expect(keyOf(list)).toBe('L') expect(list.L.length).toBe(1) expect(keyOf(list.L[0])).toBe('M') // expect(Object.keys(toDb.list.L[0].M).length).toBe(1); const productNested = (<MapAttribute<ProductNested>>list.L[0]).M expect(productNested.collection).toBeDefined() expect(keyOf(productNested.collection)).toBe('L') }) }) describe('model with nested model with custom mapper', () => { const object = new ModelWithNestedModelWithCustomMapper() const toDbVal: Attributes<ModelWithNestedModelWithCustomMapper> = toDb( object, ModelWithNestedModelWithCustomMapper, ) it('custom mapper', () => { expect(toDbVal).toBeDefined() expect(toDbVal.nestedModel).toBeDefined() const nestedModel = <MapAttribute<NestedModelWithCustomMapper>>toDbVal.nestedModel expect(nestedModel.M.id).toEqual(IdMapper.toDb(object.nestedModel.id)) }) }) describe('model with enums', () => { const object = new ModelWithNonDecoratedEnum() object.id = 'myId' object.type = Type.FirstType object.strType = StringType.FirstType const toDbVal: Attributes<ModelWithNonDecoratedEnum> = toDb(object, ModelWithNonDecoratedEnum) it('should map all properties', () => { expect(toDbVal).toBeDefined() expect(toDbVal.id).toBeDefined() expect((<StringAttribute>toDbVal.id).S).toBe('myId') expect(toDbVal.type).toBeDefined() expect((<NumberAttribute>toDbVal.type).N).toBe('0') expect(toDbVal.strType).toBeDefined() expect((<StringAttribute>toDbVal.strType).S).toBe('first') }) }) describe('model with empty values', () => { const model: ModelWithEmptyValues = { // OK id: 'myId', // x -> empty strings are valid name: '', // x -> empty set is not valid roles: new Set(), // OK ->empty L(ist) is valid lastNames: [], // OK -> depending on mapper createdAt: new Date(), // OK -> empty M(ap) is valid details: {}, } const toDbValue = toDb(model, ModelWithEmptyValues) // expect(Object.keys(toDbValue).length).toBe(4) expect(toDbValue.id).toBeDefined() expect(keyOf(toDbValue.id)).toBe('S') expect(toDbValue.name).toBeDefined() expect(keyOf(toDbValue.name)).toBe('S') expect(toDbValue.roles).toBeUndefined() expect(toDbValue.lastNames).toBeDefined() expect(keyOf(toDbValue.lastNames)).toBe('L') expect(toDbValue.createdAt).toBeDefined() expect(toDbValue.details).toBeDefined() expect(keyOf(toDbValue.details)).toBe('M') }) }) describe('from db', () => { describe('model with complex property values (decorators)', () => { let product: Product beforeEach(() => { product = fromDb(productFromDb, Product) }) it('nested value', () => { expect(product.nestedValue).toBeDefined() expect(Object.getOwnPropertyNames(product.nestedValue).length).toBe(1) expect(product.nestedValue.sortedSet).toBeDefined() expect(product.nestedValue.sortedSet instanceof Set).toBeTruthy() expect(product.nestedValue.sortedSet.size).toBe(2) }) }) describe('model', () => { let organization: Organization beforeEach(() => { organization = fromDb(organizationFromDb, Organization) }) it('id', () => { expect(organization.id).toBe('myId') }) it('createdAtDate', () => { expect(organization.createdAtDate).toBeDefined() expect(organization.createdAtDate instanceof Date).toBeTruthy() expect(isNaN(<any>organization.createdAtDate)).toBeFalsy() expect(organization.createdAtDate.toISOString()).toEqual(organization1CreatedAt.toISOString()) }) it('lastUpdated', () => { expect(organization.lastUpdated).toBeDefined() expect(organization.lastUpdated instanceof Date).toBeTruthy() expect(isNaN(<any>organization.lastUpdated)).toBeFalsy() expect(organization.lastUpdated.toISOString()).toEqual(organization1LastUpdated.toISOString()) }) it('employees', () => { expect(organization.employees).toBeDefined() expect(Array.isArray(organization.employees)).toBeTruthy() expect(organization.employees.length).toBe(2) // first employee expect(organization.employees[0].name).toBe('max') expect(organization.employees[0].age).toBe(50) expect(organization.employees[0].createdAt instanceof Date).toBeTruthy() expect(isNaN(<any>organization.employees[0].createdAt)).toBeFalsy() expect((<Date>organization.employees[0].createdAt).toISOString()).toEqual( organization1Employee1CreatedAt.toISOString(), ) // set is mapped to set but would expect list, should not work without extra @Sorted() decorator expect(organization.employees[0].sortedSet).toBeDefined() expect(organization.employees[0].sortedSet instanceof Set).toBeTruthy() // second employee expect(organization.employees[1].name).toBe('anna') expect(organization.employees[1].age).toBe(27) expect(organization.employees[1].createdAt instanceof Date).toBeTruthy() expect(isNaN(<any>organization.employees[1].createdAt)).toBeFalsy() expect(organization.employees[1].createdAt).toEqual(organization1Employee2CreatedAt) expect(organization.employees[1].sortedSet).toBeDefined() expect(organization.employees[1].sortedSet instanceof Set).toBeTruthy() }) it('active', () => { expect(organization.active).toBe(true) }) it('count', () => { expect(organization.count).toBe(52) }) it('cities', () => { expect(organization.cities).toBeDefined() expect(organization.cities instanceof Set).toBeTruthy() const cities: Set<string> = organization.cities expect(cities.size).toBe(2) expect(Array.from(cities)[0]).toBe('zürich') expect(Array.from(cities)[1]).toBe('bern') }) it('birthdays', () => { expect(organization.birthdays).toBeDefined() expect(organization.birthdays instanceof Set).toBeTruthy() const birthdays: Set<Birthday> = organization.birthdays expect(birthdays.size).toBe(1) const birthday: Birthday = Array.from(birthdays)[0] expect(birthday).toBeDefined() expect(birthday.date).toEqual(new Date('1958-04-13')) expect(Array.isArray(birthday.presents)).toBeTruthy() }) it('awards', () => { expect(organization.awards).toBeDefined() expect(organization.awards instanceof Set).toBeTruthy() const awards = organization.awards expect(awards.size).toBe(1) const award = Array.from(awards)[0] expect(award).toBeDefined() expect(award).toBe('Best of Swiss Web') }) it('events', () => { expect(organization.events).toBeDefined() expect(organization.events instanceof Set).toBeTruthy() const events = organization.events expect(events.size).toBe(1) const event = Array.from(events)[0] expect(event).toBeDefined() expect(typeof event).toBe('object') expect(event.name).toBe('yearly get together') expect(event.participants).toBe(125) }) }) describe('model with enums', () => { const attributes: Attributes<ModelWithNonDecoratedEnum> = { id: { S: 'myId' }, type: { N: Type.FirstType.toString() }, strType: { S: StringType.FirstType }, } const fromDbVal: ModelWithNonDecoratedEnum = fromDb(attributes, ModelWithNonDecoratedEnum) it('should map all properties', () => { expect(fromDbVal).toBeDefined() expect(fromDbVal.id).toBeDefined() expect(fromDbVal.id).toBe('myId') expect(fromDbVal.type).toBeDefined() expect(fromDbVal.type).toBe(Type.FirstType) expect(fromDbVal.strType).toBeDefined() expect(fromDbVal.strType).toBe(StringType.FirstType) }) }) }) }) describe('createKeyAttributes', () => { it('PartitionKey only', () => { const attrs = createKeyAttributes(metadataForModel(SimpleWithPartitionKeyModel), 'myId') expect(attrs).toEqual({ id: { S: 'myId' }, }) }) it('PartitionKey only (custom db name)', () => { const attrs = createKeyAttributes(metadataForModel(SimpleWithRenamedPartitionKeyModel), 'myId') expect(attrs).toEqual({ custom_id: { S: 'myId' }, }) }) it('PartitionKey + SortKey', () => { const now = new Date() const attrs = createKeyAttributes(metadataForModel(SimpleWithCompositePartitionKeyModel), 'myId', now) expect(attrs).toEqual({ id: { S: 'myId' }, creationDate: { S: now.toISOString() }, }) }) it('PartitionKey + SortKey (custom db name)', () => { const now = new Date() const attrs = createKeyAttributes(metadataForModel(SimpleWithRenamedCompositePartitionKeyModel), 'myId', now) expect(attrs).toEqual({ custom_id: { S: 'myId' }, custom_date: { S: now.toISOString() }, }) }) it('should throw when required sortKey is missing', () => { expect(() => createKeyAttributes(metadataForModel(SimpleWithCompositePartitionKeyModel), 'myId')).toThrow() }) }) describe('createToKeyFn, toKey', () => { it('should throw when model has no defined properties', () => { expect(() => createToKeyFn(SimpleModel)).toThrow() }) it('should throw when given partial has undefined key properties', () => { expect(() => toKey({}, SimpleWithPartitionKeyModel)).toThrow() expect(() => toKey({ id: 'myId' }, SimpleWithCompositePartitionKeyModel)).toThrow() expect(() => toKey({ creationDate: new Date() }, SimpleWithCompositePartitionKeyModel)).toThrow() }) it('should create key attributes of simple key', () => { const key = toKey({ id: 'myId' }, SimpleWithPartitionKeyModel) expect(key).toEqual({ id: { S: 'myId' }, }) }) it('should create key attributes of simple key (custom db name)', () => { const key = toKey({ id: 'myId' }, SimpleWithRenamedPartitionKeyModel) expect(key).toEqual({ custom_id: { S: 'myId' }, }) }) it('should create key attributes of composite key', () => { const partial: Partial<SimpleWithCompositePartitionKeyModel> = { id: 'myId', creationDate: new Date() } const key = toKey(partial, SimpleWithCompositePartitionKeyModel) expect(key).toEqual({ id: { S: partial.id! }, creationDate: { S: partial.creationDate!.toISOString() }, }) }) it('should create key attributes of composite key (custom db name)', () => { const partial: Partial<SimpleWithRenamedCompositePartitionKeyModel> = { id: 'myId', creationDate: new Date() } const key = toKey(partial, SimpleWithRenamedCompositePartitionKeyModel) expect(key).toEqual({ custom_id: { S: partial.id! }, custom_date: { S: partial.creationDate!.toISOString() }, }) }) it('should create key with custom mapper', () => { const partial: ModelWithCustomMapperModel = { id: new Id(7, 2018) } const key = toKey(partial, ModelWithCustomMapperModel) expect(key).toEqual({ id: { S: Id.unparse(partial.id) }, }) }) }) }) function keyOf(attributeValue: Attribute): string | null { if (attributeValue && Object.keys(attributeValue).length) { return Object.keys(attributeValue)[0] } else { return null } }
the_stack
import { Knex } from 'knex'; import { Database } from 'src/dbconfig'; import { Image } from 'src/entity/image'; import { List, ListItem, ListPrivacy, ListSortBy, ListSortOrder, } from 'src/entity/list'; import { MediaItemItemsResponse, MediaType } from 'src/entity/mediaItem'; import { Seen } from 'src/entity/seen'; import { TvEpisode } from 'src/entity/tvepisode'; import { TvSeason } from 'src/entity/tvseason'; import { UserRating } from 'src/entity/userRating'; import { repository } from 'src/repository/repository'; import { randomSlugId, toSlug } from 'src/slug'; export type ListDetailsResponse = Omit<List, 'userId'> & { totalRuntime: number; user: { id: number; username: string; slug: string; }; }; export type ListItemsResponse = { rank: number; id: number; listedAt: string; type: MediaType | 'season' | 'episode'; mediaItem: MediaItemItemsResponse; season?: TvSeason; episode?: TvEpisode; }[]; class ListRepository extends repository<List>({ tableName: 'list', primaryColumnName: 'id', }) { public async update(args: { name: string; description?: string; privacy?: ListPrivacy; sortBy?: ListSortBy; sortOrder?: ListSortOrder; id: number; userId: number; }): Promise<List> { const { userId, name, description, privacy, sortBy, sortOrder, id } = args; if (id == undefined || userId == undefined) { throw new Error('id and userId are required params'); } if (name?.trim().length === 0) { return; } const updatedAt = new Date().getTime(); const slug = toSlug(name); return await Database.knex.transaction(async (trx) => { const list = await trx<List>('list').where('id', id).first(); if (!list) { return; } if (list.userId !== userId) { return; } const listWithTheSameName = await trx<List>('list') .where('userId', userId) .where('name', name) .whereNot('id', id) .first(); if (listWithTheSameName) { return; } await trx<List>('list') .update({ ...(list.isWatchlist ? {} : { name: name }), privacy: privacy, description: description, updatedAt: updatedAt, sortBy: sortBy, sortOrder: sortOrder, // displayNumbers: args.displayNumbers || false, // allowComments: args.allowComments || false, slug: Database.knex.raw( `(CASE WHEN (${Database.knex<List>('list') .count() .where('userId', userId) .where('slug', slug) .whereNot('id', id) .toQuery()}) = 0 THEN '${slug}' ELSE '${slug}-${randomSlugId()}' END)` ), }) .where('id', id); return await trx<List>('list').where('id', id).first(); }); } public async create(args: { name: string; description?: string; privacy?: ListPrivacy; sortBy?: ListSortBy; sortOrder?: ListSortOrder; userId: number; isWatchlist?: boolean; }): Promise<List> { const { userId, name, description, privacy, sortBy, sortOrder, isWatchlist, } = args; if (name.trim().length === 0) { return; } const createdAt = new Date().getTime(); const slug = toSlug(name); const [res] = await Database.knex<List>('list').insert( { userId: userId, name: name, privacy: privacy || 'private', description: description, sortBy: sortBy || 'recently-watched', sortOrder: sortOrder || 'desc', createdAt: createdAt, updatedAt: createdAt, isWatchlist: isWatchlist || false, rank: Database.knex.raw( `(${Database.knex<List>('list') .count() .where('userId', args.userId) .toQuery()})` ), slug: Database.knex.raw( `(CASE WHEN (${Database.knex<List>('list') .count() .where('userId', args.userId) .where('slug', slug) .toQuery()}) = 0 THEN '${slug}' ELSE '${slug}-${randomSlugId()}' END)` ), }, '*' ); return { ...res, displayNumbers: Boolean(res.displayNumbers), allowComments: Boolean(res.allowComments), }; } public async delete(args: { listId: number; userId: number; }): Promise<number> { const { listId, userId } = args; return await Database.knex.transaction(async (trx) => { const list = await trx<List>('list') .where('userId', userId) .where('id', listId) .where('isWatchlist', false) .first(); if (!list) { return 0; } await trx<ListItem>('listItem').delete().where('listId', listId); return await trx<ListItem>('list').delete().where('id', listId); }); } public async details(args: { listId: number; userId: number; }): Promise<ListDetailsResponse> { const { listId, userId } = args; const res = await Database.knex('list') .select('list.*', 'user.name AS user.name', 'user.slug AS user.slug') .where('list.id', listId) .where((qb) => qb.where('list.userId', userId).orWhere('list.privacy', 'public') ) .select({ totalRuntime: Database.knex('list') .leftJoin('listItem', 'listItem.listId', 'list.id') .leftJoin('mediaItem', 'mediaItem.id', 'listItem.mediaItemId') .leftJoin('episode', 'episode.id', 'listItem.episodeId') .leftJoin( (qb) => qb .select('seasonId') .sum({ runtime: Database.knex.raw(` CASE WHEN "episode"."runtime" IS NOT NULL THEN "episode"."runtime" ELSE "mediaItem"."runtime" END`), }) .from('season') .leftJoin('mediaItem', 'mediaItem.id', 'season.tvShowId') .leftJoin('episode', 'episode.seasonId', 'season.id') .groupBy('seasonId') .as('seasonRuntime'), 'seasonRuntime.seasonId', 'listItem.seasonId' ) .leftJoin( (qb) => qb .select('tvShowId') .sum({ runtime: Database.knex.raw(` CASE WHEN "episode"."runtime" IS NOT NULL THEN "episode"."runtime" ELSE "mediaItem"."runtime" END`), }) .from('episode') .leftJoin('mediaItem', 'mediaItem.id', 'episode.tvShowId') .groupBy('tvShowId') .as('showRuntime'), 'showRuntime.tvShowId', 'listItem.mediaItemId' ) .sum({ totalRuntime: Database.knex.raw(` CASE WHEN "listItem"."episodeId" IS NOT NULL THEN CASE WHEN "episode"."runtime" IS NOT NULL THEN "episode"."runtime" ELSE "mediaItem"."runtime" END WHEN "listItem"."seasonId" IS NOT NULL THEN "seasonRuntime"."runtime" ELSE CASE WHEN "mediaItem"."mediaType" = 'tv' THEN "showRuntime"."runtime" ELSE "mediaItem"."runtime" END END`), }) .where('list.id', listId), }) .leftJoin('user', 'user.id', 'list.userId') .first(); if (!res) { return; } return { id: res.id, createdAt: res.createdAt, isWatchlist: Boolean(res.isWatchlist), allowComments: Boolean(res.allowComments), displayNumbers: Boolean(res.displayNumbers), name: res.name, privacy: res.privacy, slug: res.slug, totalRuntime: res.totalRuntime, updatedAt: res.updatedAt, description: res.description, sortBy: res.sortBy, sortOrder: res.sortOrder, user: { id: res.userId, username: res['user.name'], slug: res['user.slug'], }, }; } public async items(args: { listId: number; userId: number; }): Promise<ListItemsResponse> { const { listId, userId } = args; const { id: watchlistId } = await Database.knex('list') .select('id') .where('userId', userId) .where('isWatchlist', true) .first(); const currentDateString = new Date().toISOString(); const res = await Database.knex<ListItem>('listItem') .select({ 'episode.episodeNumber': 'episode.episodeNumber', 'episode.imdbId': 'episode.imdbId', 'episode.isSpecialEpisode': 'episode.isSpecialEpisode', 'episode.lastSeenAt': 'episodeLastSeen.lastSeenAt', 'episode.releaseDate': 'episode.releaseDate', 'episode.progress': 'episodeProgress.progress', 'episode.seasonNumber': 'episode.seasonNumber', 'episode.seasonAndEpisodeNumber': 'episode.seasonAndEpisodeNumber', 'episode.title': 'episode.title', 'episode.runtime': 'episode.runtime', 'episode.tmdbId': 'episode.tmdbId', 'episode.traktId': 'episode.traktId', 'episode.tvdbId': 'episode.tvdbId', 'episode.userRating.date': 'episodeRating.date', 'episode.userRating.rating': 'episodeRating.rating', 'episode.watchlist.id': 'episodeWatchlist.id', 'listItem.addedAt': 'listItem.addedAt', 'listItem.episodeId': 'listItem.episodeId', 'listItem.id': 'listItem.id', 'listItem.mediaItemId': 'listItem.mediaItemId', 'listItem.rank': 'listItem.rank', 'listItem.seasonId': 'listItem.seasonId', 'mediaItem.airedEpisodesCount': 'mediaItemAiredEpisodes.count', 'mediaItem.backdrop.id': 'mediaItemBackdrop.id', 'mediaItem.firstUnwatchedEpisode.description': 'mediaItemFirstUnwatchedEpisode.description', 'mediaItem.firstUnwatchedEpisode.episodeNumber': 'mediaItemFirstUnwatchedEpisode.episodeNumber', 'mediaItem.firstUnwatchedEpisode.id': 'mediaItemFirstUnwatchedEpisode.id', 'mediaItem.firstUnwatchedEpisode.imdbId': 'mediaItemFirstUnwatchedEpisode.imdbId', 'mediaItem.firstUnwatchedEpisode.isSpecialEpisode': 'mediaItemFirstUnwatchedEpisode.isSpecialEpisode', 'mediaItem.firstUnwatchedEpisode.releaseDate': 'mediaItemFirstUnwatchedEpisode.releaseDate', 'mediaItem.firstUnwatchedEpisode.runtime': 'mediaItemFirstUnwatchedEpisode.runtime', 'mediaItem.firstUnwatchedEpisode.seasonId': 'mediaItemFirstUnwatchedEpisode.seasonId', 'mediaItem.firstUnwatchedEpisode.seasonNumber': 'mediaItemFirstUnwatchedEpisode.seasonNumber', 'mediaItem.firstUnwatchedEpisode.title': 'mediaItemFirstUnwatchedEpisode.title', 'mediaItem.firstUnwatchedEpisode.tmdbId': 'mediaItemFirstUnwatchedEpisode.tmdbId', 'mediaItem.firstUnwatchedEpisode.traktId': 'mediaItemFirstUnwatchedEpisode.traktId', 'mediaItem.firstUnwatchedEpisode.tvdbId': 'mediaItemFirstUnwatchedEpisode.tvdbId', 'mediaItem.firstUnwatchedEpisode.tvShowId': 'mediaItemFirstUnwatchedEpisode.tvShowId', 'mediaItem.lastAiredEpisode.id': 'mediaItemLastAiredEpisode.id', 'mediaItem.lastAiredEpisode.description': 'mediaItemLastAiredEpisode.description', 'mediaItem.lastAiredEpisode.episodeNumber': 'mediaItemLastAiredEpisode.episodeNumber', 'mediaItem.lastAiredEpisode.imdbId': 'mediaItemLastAiredEpisode.imdbId', 'mediaItem.lastAiredEpisode.isSpecialEpisode': 'mediaItemLastAiredEpisode.isSpecialEpisode', 'mediaItem.lastAiredEpisode.releaseDate': 'mediaItemLastAiredEpisode.releaseDate', 'mediaItem.lastAiredEpisode.runtime': 'mediaItemLastAiredEpisode.runtime', 'mediaItem.lastAiredEpisode.seasonId': 'mediaItemLastAiredEpisode.seasonId', 'mediaItem.lastAiredEpisode.seasonNumber': 'mediaItemLastAiredEpisode.seasonNumber', 'mediaItem.lastAiredEpisode.title': 'mediaItemLastAiredEpisode.title', 'mediaItem.lastAiredEpisode.tmdbId': 'mediaItemLastAiredEpisode.tmdbId', 'mediaItem.lastAiredEpisode.traktId': 'mediaItemLastAiredEpisode.traktId', 'mediaItem.lastAiredEpisode.tvdbId': 'mediaItemLastAiredEpisode.tvdbId', 'mediaItem.upcomingEpisode.id': 'mediaItemUpcomingEpisode.id', 'mediaItem.upcomingEpisode.description': 'mediaItemUpcomingEpisode.description', 'mediaItem.upcomingEpisode.episodeNumber': 'mediaItemUpcomingEpisode.episodeNumber', 'mediaItem.upcomingEpisode.imdbId': 'mediaItemUpcomingEpisode.imdbId', 'mediaItem.upcomingEpisode.isSpecialEpisode': 'mediaItemUpcomingEpisode.isSpecialEpisode', 'mediaItem.upcomingEpisode.releaseDate': 'mediaItemUpcomingEpisode.releaseDate', 'mediaItem.upcomingEpisode.runtime': 'mediaItemUpcomingEpisode.runtime', 'mediaItem.upcomingEpisode.seasonId': 'mediaItemUpcomingEpisode.seasonId', 'mediaItem.upcomingEpisode.seasonNumber': 'mediaItemUpcomingEpisode.seasonNumber', 'mediaItem.upcomingEpisode.title': 'mediaItemUpcomingEpisode.title', 'mediaItem.upcomingEpisode.tmdbId': 'mediaItemUpcomingEpisode.tmdbId', 'mediaItem.upcomingEpisode.traktId': 'mediaItemUpcomingEpisode.traktId', 'mediaItem.upcomingEpisode.tvdbId': 'mediaItemUpcomingEpisode.tvdbId', 'mediaItem.genres': 'mediaItem.genres', 'mediaItem.id': 'mediaItem.id', 'mediaItem.imdbId': 'mediaItem.imdbId', 'mediaItem.lastSeenAt': 'mediaItemLastSeen.lastSeenAt', 'mediaItem.lastSeen.mediaItemId': 'mediaItemLastSeen.mediaItemId', 'mediaItem.lastTimeUpdated': 'mediaItem.lastTimeUpdated', 'mediaItem.mediaType': 'mediaItem.mediaType', 'mediaItem.network': 'mediaItem.network', 'mediaItem.overview': 'mediaItem.overview', 'mediaItem.poster.id': 'mediaItemPoster.id', 'mediaItem.progress': 'mediaItemProgress.progress', 'mediaItem.releaseDate': 'mediaItem.releaseDate', 'mediaItem.runtime': 'mediaItem.runtime', 'mediaItem.seenEpisodesCount': 'mediaItemSeenEpisodes.seenEpisodesCount', 'mediaItem.slug': 'mediaItem.slug', 'mediaItem.status': 'mediaItem.status', 'mediaItem.source': 'mediaItem.source', 'mediaItem.title': 'mediaItem.title', 'mediaItem.tmdbId': 'mediaItem.tmdbId', 'mediaItem.totalRuntime': 'mediaItemTotalRuntime.totalRuntime', 'mediaItem.traktId': 'mediaItem.traktId', 'mediaItem.tvdbId': 'mediaItem.tvdbId', 'mediaItem.url': 'mediaItem.url', 'mediaItem.userRating.date': 'mediaItemRating.date', 'mediaItem.userRating.rating': 'mediaItemRating.rating', 'mediaItem.watchlist.id': 'mediaItemWatchlist.id', 'season.airedEpisodesCount': 'seasonAiredEpisodes.count', 'season.firstUnwatchedEpisode.description': 'seasonFirstUnwatchedEpisode.description', 'season.firstUnwatchedEpisode.episodeNumber': 'seasonFirstUnwatchedEpisode.episodeNumber', 'season.firstUnwatchedEpisode.id': 'seasonFirstUnwatchedEpisode.id', 'season.firstUnwatchedEpisode.imdbId': 'seasonFirstUnwatchedEpisode.imdbId', 'season.firstUnwatchedEpisode.isSpecialEpisode': 'seasonFirstUnwatchedEpisode.isSpecialEpisode', 'season.firstUnwatchedEpisode.releaseDate': 'seasonFirstUnwatchedEpisode.releaseDate', 'season.firstUnwatchedEpisode.runtime': 'seasonFirstUnwatchedEpisode.runtime', 'season.firstUnwatchedEpisode.seasonId': 'seasonFirstUnwatchedEpisode.seasonId', 'season.firstUnwatchedEpisode.seasonNumber': 'seasonFirstUnwatchedEpisode.seasonNumber', 'season.firstUnwatchedEpisode.title': 'seasonFirstUnwatchedEpisode.title', 'season.firstUnwatchedEpisode.tmdbId': 'seasonFirstUnwatchedEpisode.tmdbId', 'season.firstUnwatchedEpisode.traktId': 'seasonFirstUnwatchedEpisode.traktId', 'season.firstUnwatchedEpisode.tvdbId': 'seasonFirstUnwatchedEpisode.tvdbId', 'season.firstUnwatchedEpisode.tvShowId': 'seasonFirstUnwatchedEpisode.tvShowId', 'season.lastAiredEpisode.id': 'seasonLastAiredEpisode.id', 'season.lastAiredEpisode.description': 'seasonLastAiredEpisode.description', 'season.lastAiredEpisode.episodeNumber': 'seasonLastAiredEpisode.episodeNumber', 'season.lastAiredEpisode.imdbId': 'seasonLastAiredEpisode.imdbId', 'season.lastAiredEpisode.isSpecialEpisode': 'seasonLastAiredEpisode.isSpecialEpisode', 'season.lastAiredEpisode.releaseDate': 'seasonLastAiredEpisode.releaseDate', 'season.lastAiredEpisode.runtime': 'seasonLastAiredEpisode.runtime', 'season.lastAiredEpisode.seasonId': 'seasonLastAiredEpisode.seasonId', 'season.lastAiredEpisode.seasonNumber': 'seasonLastAiredEpisode.seasonNumber', 'season.lastAiredEpisode.title': 'seasonLastAiredEpisode.title', 'season.lastAiredEpisode.tmdbId': 'seasonLastAiredEpisode.tmdbId', 'season.lastAiredEpisode.traktId': 'seasonLastAiredEpisode.traktId', 'season.lastAiredEpisode.tvdbId': 'seasonLastAiredEpisode.tvdbId', 'season.isSpecialSeason': 'season.isSpecialSeason', 'season.lastSeenAt': 'seasonLastSeen.lastSeenAt', 'season.releaseDate': 'season.releaseDate', 'season.seasonNumber': 'season.seasonNumber', 'season.seenEpisodesCount': 'seasonSeenEpisodes.seenEpisodesCount', 'season.title': 'season.title', 'season.tmdbId': 'season.tmdbId', 'season.traktId': 'season.traktId', 'season.tvdbId': 'season.tvdbId', 'season.userRating.date': 'seasonRating.date', 'season.userRating.rating': 'seasonRating.rating', 'season.totalRuntime': 'seasonTotalRuntime.totalRuntime', 'season.watchlist.id': 'seasonWatchlist.id', }) .where('listItem.listId', listId) .leftJoin('mediaItem', 'mediaItem.id', 'listItem.mediaItemId') .leftJoin('season', 'season.id', 'listItem.seasonId') .leftJoin('episode', 'episode.id', 'listItem.episodeId') // MediaItem: watchlist .leftJoin<ListItem>( (qb) => qb .from('listItem') .whereNull('listItem.seasonId') .whereNull('listItem.episodeId') .where('listItem.listId', watchlistId) .as('mediaItemWatchlist'), 'mediaItemWatchlist.mediaItemId', 'listItem.mediaItemId' ) // Season: watchlist .leftJoin<ListItem>( (qb) => qb .from('listItem') .whereNotNull('listItem.seasonId') .whereNull('listItem.episodeId') .where('listItem.listId', watchlistId) .as('seasonWatchlist'), 'seasonWatchlist.seasonId', 'listItem.seasonId' ) // Episode: watchlist .leftJoin<ListItem>( (qb) => qb .from('listItem') .whereNotNull('listItem.episodeId') .where('listItem.listId', watchlistId) .as('episodeWatchlist'), 'episodeWatchlist.episodeId', 'listItem.episodeId' ) // Episode: last seen at .leftJoin( (qb) => qb .select('episodeId') .max('date', { as: 'lastSeenAt' }) .from('seen') .where('userId', userId) .where('type', 'seen') .groupBy('episodeId') .as('episodeLastSeen'), 'episodeLastSeen.episodeId', 'listItem.episodeId' ) // Season: last seen at .leftJoin( (qb) => qb .select({ episode_seasonId: 'episode.seasonId' }) .max('date', { as: 'lastSeenAt' }) .from('seen') .leftJoin('episode', 'episode.id', 'seen.episodeId') .where('userId', userId) .where('type', 'seen') .groupBy('episode_seasonId') .as('seasonLastSeen'), 'seasonLastSeen.episode_seasonId', 'listItem.seasonId' ) // MediaItem: last seen at .leftJoin( (qb) => qb .select('mediaItemId') .max('date', { as: 'lastSeenAt' }) .from('seen') .where('userId', userId) .where('type', 'seen') .groupBy('mediaItemId') .as('mediaItemLastSeen'), 'mediaItemLastSeen.mediaItemId', 'listItem.mediaItemId' ) // MediaItem: total runtime .leftJoin( (qb) => qb .select('tvShowId') .leftJoin('mediaItem', 'mediaItem.id', 'tvShowId') .sum({ totalRuntime: Database.knex.raw(` CASE WHEN "episode"."runtime" IS NOT NULL THEN "episode"."runtime" ELSE "mediaItem"."runtime" END`), }) .from('episode') .groupBy('tvShowId') .where('episode.releaseDate', '<', currentDateString) .where('episode.isSpecialEpisode', false) .as('mediaItemTotalRuntime'), 'mediaItemTotalRuntime.tvShowId', 'listItem.mediaItemId' ) // Season: total runtime .leftJoin( (qb) => qb .select('seasonId') .leftJoin('mediaItem', 'mediaItem.id', 'tvShowId') .sum({ totalRuntime: Database.knex.raw(` CASE WHEN "episode"."runtime" IS NOT NULL THEN "episode"."runtime" ELSE "mediaItem"."runtime" END`), }) .from('episode') .groupBy('seasonId') .where('episode.isSpecialEpisode', false) .where('episode.releaseDate', '<', currentDateString) .as('seasonTotalRuntime'), 'seasonTotalRuntime.seasonId', 'listItem.seasonId' ) // MediaItem: aired episodes count .leftJoin( (qb) => qb .select('tvShowId') .count({ count: '*' }) .from('episode') .groupBy('tvShowId') .where('episode.isSpecialEpisode', false) .where('releaseDate', '<', currentDateString) .as('mediaItemAiredEpisodes'), 'mediaItemAiredEpisodes.tvShowId', 'listItem.mediaItemId' ) // Season: aired episodes count .leftJoin( (qb) => qb .select('seasonId') .count({ count: '*' }) .from('episode') .groupBy('seasonId') .where('episode.isSpecialEpisode', false) .where('releaseDate', '<', currentDateString) .as('seasonAiredEpisodes'), 'seasonAiredEpisodes.seasonId', 'listItem.seasonId' ) // MediaItem: posterId .leftJoin<Image>( (qb) => qb .from('image') .where('type', 'poster') .whereNull('seasonId') .as('mediaItemPoster'), 'mediaItemPoster.mediaItemId', 'listItem.mediaItemId' ) // MediaItem: backdropId .leftJoin<Image>( (qb) => qb .from('image') .where('type', 'backdrop') .whereNull('seasonId') .as('mediaItemBackdrop'), 'mediaItemBackdrop.mediaItemId', 'listItem.mediaItemId' ) // MediaItem: user rating .leftJoin<UserRating>( (qb) => qb .from('userRating') .whereNotNull('userRating.rating') .orWhereNotNull('userRating.review') .as('mediaItemRating'), (qb) => qb .on('mediaItemRating.mediaItemId', 'listItem.mediaItemId') .andOnVal('mediaItemRating.userId', userId) .andOnNull('mediaItemRating.episodeId') .andOnNull('mediaItemRating.seasonId') ) // Season: user rating .leftJoin<UserRating>( (qb) => qb .from('userRating') .whereNotNull('userRating.rating') .orWhereNotNull('userRating.review') .as('seasonRating'), (qb) => qb .andOnVal('seasonRating.userId', userId) .andOnNull('seasonRating.episodeId') .andOn('seasonRating.seasonId', 'listItem.seasonId') ) // Episode: user rating .leftJoin<UserRating>( (qb) => qb .from('userRating') .whereNotNull('userRating.rating') .orWhereNotNull('userRating.review') .as('episodeRating'), (qb) => qb .andOnVal('episodeRating.userId', userId) .andOn('episodeRating.episodeId', 'listItem.episodeId') .andOnNull('episodeRating.seasonId') ) // MediaItem: seen episodes count .leftJoin<Seen>( (qb) => qb .select('mediaItemId') .count('*', { as: 'seenEpisodesCount' }) .from((qb: Knex.QueryBuilder) => qb .select('mediaItemId') .from<Seen>('seen') .where('type', 'seen') .where('userId', userId) .whereNotNull('episodeId') .groupBy('mediaItemId', 'episodeId') .leftJoin('episode', 'episode.id', 'seen.episodeId') .where('episode.isSpecialEpisode', false) .as('seen') ) .groupBy('mediaItemId') .as('mediaItemSeenEpisodes'), 'mediaItemSeenEpisodes.mediaItemId', 'listItem.mediaItemId' ) // Season: seen episodes count .leftJoin<Seen>( (qb) => qb .select('mediaItemId') .count('*', { as: 'seenEpisodesCount' }) .from((qb: Knex.QueryBuilder) => qb .select('mediaItemId') .from<Seen>('seen') .where('type', 'seen') .where('userId', userId) .whereNotNull('episodeId') .groupBy('mediaItemId', 'episodeId') .leftJoin('episode', 'episode.id', 'seen.episodeId') .where('episode.isSpecialEpisode', false) .as('seen') ) .groupBy('mediaItemId') .as('seasonSeenEpisodes'), 'seasonSeenEpisodes.mediaItemId', 'listItem.mediaItemId' ) // MediaItem: first unwatched episode .leftJoin( (qb) => qb .from('episode') .select('tvShowId') .min('seasonAndEpisodeNumber', { as: 'seasonAndEpisodeNumber', }) .leftJoin('seen', (qb) => qb .on('seen.episodeId', 'episode.id') .andOnVal('seen.type', 'seen') ) .where('episode.isSpecialEpisode', false) .andWhereNot('episode.releaseDate', '') .andWhereNot('episode.releaseDate', null) .andWhere('episode.releaseDate', '<=', currentDateString) .andWhere((qb) => { qb.where('seen.userId', '<>', userId).orWhereNull('seen.userId'); }) .groupBy('tvShowId') .as('mediaItemFirstUnwatchedEpisodeHelper'), 'mediaItemFirstUnwatchedEpisodeHelper.tvShowId', 'listItem.mediaItemId' ) .leftJoin( Database.knex.ref('episode').as('mediaItemFirstUnwatchedEpisode'), (qb) => qb .on( 'mediaItemFirstUnwatchedEpisode.tvShowId', 'listItem.mediaItemId' ) .andOn( 'mediaItemFirstUnwatchedEpisode.seasonAndEpisodeNumber', 'mediaItemFirstUnwatchedEpisodeHelper.seasonAndEpisodeNumber' ) ) // Season: first unwatched episode .leftJoin( (qb) => qb .from('episode') .select('seasonId') .min('seasonAndEpisodeNumber', { as: 'seasonAndEpisodeNumber', }) .leftJoin('seen', (qb) => qb .on('seen.episodeId', 'episode.id') .andOnVal('seen.type', 'seen') ) .where('episode.isSpecialEpisode', false) .andWhereNot('episode.releaseDate', '') .andWhereNot('episode.releaseDate', null) .andWhere('episode.releaseDate', '<=', currentDateString) .andWhere((qb) => { qb.where('seen.userId', '<>', userId).orWhereNull('seen.userId'); }) .groupBy('seasonId') .as('seasonFirstUnwatchedEpisodeHelper'), 'seasonFirstUnwatchedEpisodeHelper.seasonId', 'listItem.seasonId' ) .leftJoin( Database.knex.ref('episode').as('seasonFirstUnwatchedEpisode'), (qb) => qb .on('seasonFirstUnwatchedEpisode.seasonId', 'listItem.seasonId') .andOn( 'seasonFirstUnwatchedEpisode.seasonAndEpisodeNumber', 'seasonFirstUnwatchedEpisodeHelper.seasonAndEpisodeNumber' ) ) // MediaItem: progress .leftJoin<Seen>( (qb) => qb .from<Seen>('seen') .select('mediaItemId') .max('date', { as: 'progressDate' }) .whereNull('episodeId') .where('type', 'progress') .where('userId', userId) .groupBy('mediaItemId') .as('mediaItemProgressHelper'), 'mediaItemProgressHelper.mediaItemId', 'listItem.mediaItemId' ) .leftJoin<Seen>( (qb) => qb .from<Seen>('seen') .select('date') .max('progress', { as: 'progress' }) .groupBy('date') .where('type', 'progress') .where('userId', userId) .whereNot('progress', 1) .as('mediaItemProgress'), (qb) => qb .on('mediaItemProgressHelper.mediaItemId', 'listItem.mediaItemId') .andOn( 'mediaItemProgressHelper.progressDate', 'mediaItemProgress.date' ) ) // Episode: progress .leftJoin<Seen>( (qb) => qb .from<Seen>('seen') .select('episodeId') .max('date', { as: 'progressDate' }) .whereNotNull('episodeId') .where('type', 'progress') .where('userId', userId) .groupBy('episodeId') .as('episodeProgressHelper'), 'episodeProgressHelper.episodeId', 'listItem.episodeId' ) .leftJoin<Seen>( (qb) => qb .from<Seen>('seen') .select('date') .max('progress', { as: 'progress' }) .groupBy('date') .where('type', 'progress') .where('userId', userId) .whereNot('progress', 1) .as('episodeProgress'), (qb) => qb .on('episodeProgressHelper.episodeId', 'listItem.episodeId') .andOn('episodeProgressHelper.progressDate', 'episodeProgress.date') ) // MediaItem: last aired episode .leftJoin<TvEpisode>( (qb) => qb .from<TvEpisode>('episode') .select('tvShowId') .max('seasonAndEpisodeNumber', { as: 'seasonAndEpisodeNumber', }) .where('isSpecialEpisode', false) .where('releaseDate', '<', currentDateString) .groupBy('tvShowId') .as('mediaItemLastAiredEpisodeHelper'), 'mediaItemLastAiredEpisodeHelper.tvShowId', 'listItem.mediaItemId' ) .leftJoin<TvEpisode>( Database.knex.ref('episode').as('mediaItemLastAiredEpisode'), (qb) => qb .on('mediaItemLastAiredEpisode.tvShowId', 'listItem.mediaItemId') .andOn( 'mediaItemLastAiredEpisode.seasonAndEpisodeNumber', 'mediaItemLastAiredEpisodeHelper.seasonAndEpisodeNumber' ) ) // Season: last aired episode .leftJoin<TvEpisode>( (qb) => qb .from<TvEpisode>('episode') .select('tvShowId') .max('seasonAndEpisodeNumber', { as: 'seasonAndEpisodeNumber', }) .where('isSpecialEpisode', false) .where('releaseDate', '<', currentDateString) .groupBy('tvShowId') .as('seasonLastAiredEpisodeHelper'), 'seasonLastAiredEpisodeHelper.tvShowId', 'listItem.mediaItemId' ) .leftJoin<TvEpisode>( Database.knex.ref('episode').as('seasonLastAiredEpisode'), (qb) => qb .on('seasonLastAiredEpisode.tvShowId', 'listItem.mediaItemId') .andOn( 'seasonLastAiredEpisode.seasonAndEpisodeNumber', 'seasonLastAiredEpisodeHelper.seasonAndEpisodeNumber' ) ) // MediaItem: upcoming episode .leftJoin<TvEpisode>( (qb) => qb .from<TvEpisode>('episode') .select('tvShowId') .min('seasonAndEpisodeNumber', { as: 'seasonAndEpisodeNumber', }) .where('isSpecialEpisode', false) .where('releaseDate', '>=', currentDateString) .groupBy('tvShowId') .as('mediaItemUpcomingEpisodeHelper'), 'mediaItemUpcomingEpisodeHelper.tvShowId', 'listItem.mediaItemId' ) .leftJoin<TvEpisode>( Database.knex.ref('episode').as('mediaItemUpcomingEpisode'), (qb) => qb .on('mediaItemUpcomingEpisode.tvShowId', 'listItem.mediaItemId') .andOn( 'mediaItemUpcomingEpisode.seasonAndEpisodeNumber', 'mediaItemUpcomingEpisodeHelper.seasonAndEpisodeNumber' ) ) .orderBy('listItem.rank', 'asc'); return res.map((listItem) => ({ rank: Number(listItem['listItem.rank']), id: Number(listItem['listItem.id']), listedAt: new Date(listItem['listItem.addedAt']).toISOString(), type: listItem['listItem.seasonId'] ? 'season' : listItem['listItem.episodeId'] ? 'episode' : listItem['mediaItem.mediaType'], mediaItem: { airedEpisodesCount: listItem['mediaItem.airedEpisodesCount'], backdrop: listItem['mediaItem.backdrop.id'] ? `/img/${listItem['mediaItem.backdrop.id']}` : undefined, genres: listItem['mediaItem.genres']?.split(',')?.sort(), id: listItem['listItem.mediaItemId'], imdbId: listItem['mediaItem.imdbId'], lastTimeUpdated: listItem['mediaItem.lastTimeUpdated'], mediaType: listItem['mediaItem.mediaType'], network: listItem['mediaItem.network'], overview: listItem['mediaItem.overview'], poster: listItem['mediaItem.poster.id'] ? `/img/${listItem['mediaItem.poster.id']}` : undefined, posterSmall: listItem['mediaItem.poster.id'] ? `/img/${listItem['mediaItem.poster.id']}?size=small` : undefined, releaseDate: listItem['mediaItem.releaseDate'], runtime: listItem['mediaItem.runtime'] || null, slug: listItem['mediaItem.slug'], source: listItem['mediaItem.source'], progress: listItem['mediaItem.progress'], status: listItem['mediaItem.status']?.toLowerCase(), title: listItem['mediaItem.title'], tmdbId: listItem['mediaItem.tmdbId'], traktId: listItem['mediaItem.traktId'], tvdbId: listItem['mediaItem.tvdbId'], url: listItem['mediaItem.url'], userRating: listItem['mediaItem.userRating.rating'] ? { mediaItemId: listItem['listItem.mediaItemId'], date: listItem['mediaItem.userRating.date'], rating: listItem['mediaItem.userRating.rating'], userId: userId, } : undefined, lastSeenAt: listItem['mediaItem.lastSeenAt'], totalRuntime: (listItem['mediaItem.mediaType'] === 'tv' ? listItem['mediaItem.totalRuntime'] : listItem['mediaItem.runtime']) || null, seen: listItem['mediaItem.mediaType'] === 'tv' ? listItem['mediaItem.airedEpisodesCount'] - listItem['mediaItem.seenEpisodesCount'] === 0 : Boolean(listItem['mediaItem.lastSeen.mediaItemId']), seenEpisodesCount: listItem['mediaItem.seenEpisodesCount'], unseenEpisodesCount: listItem['mediaItem.mediaType'] === 'tv' && listItem['mediaItem.airedEpisodesCount'] ? listItem['mediaItem.airedEpisodesCount'] - listItem['mediaItem.seenEpisodesCount'] : undefined, onWatchlist: Boolean(listItem['mediaItem.watchlist.id']), firstUnwatchedEpisode: listItem['mediaItem.firstUnwatchedEpisode.id'] !== null ? { description: listItem['mediaItem.firstUnwatchedEpisode.description'], episodeNumber: listItem['mediaItem.firstUnwatchedEpisode.episodeNumber'], id: listItem['mediaItem.firstUnwatchedEpisode.id'], imdbId: listItem['mediaItem.firstUnwatchedEpisode.imdbId'], isSpecialEpisode: Boolean( listItem['mediaItem.firstUnwatchedEpisode.isSpecialEpisode'] ), releaseDate: listItem['mediaItem.firstUnwatchedEpisode.releaseDate'], runtime: listItem['mediaItem.firstUnwatchedEpisode.runtime'] || null, seasonId: listItem['mediaItem.firstUnwatchedEpisode.seasonId'], seasonNumber: listItem['mediaItem.firstUnwatchedEpisode.seasonNumber'], title: listItem['mediaItem.firstUnwatchedEpisode.title'], tmdbId: listItem['mediaItem.firstUnwatchedEpisode.tmdbId'], traktId: listItem['mediaItem.firstUnwatchedEpisode.traktId'], tvdbId: listItem['mediaItem.firstUnwatchedEpisode.tvdbId'], tvShowId: listItem['listItem.mediaItemId'], } : undefined, lastAiredEpisode: listItem['mediaItem.lastAiredEpisode.id'] !== null ? { description: listItem['mediaItem.lastAiredEpisode.description'], episodeNumber: listItem['mediaItem.lastAiredEpisode.episodeNumber'], id: listItem['mediaItem.lastAiredEpisode.id'], imdbId: listItem['mediaItem.lastAiredEpisode.imdbId'], isSpecialEpisode: Boolean( listItem['mediaItem.lastAiredEpisode.isSpecialEpisode'] ), releaseDate: listItem['mediaItem.lastAiredEpisode.releaseDate'], runtime: listItem['mediaItem.lastAiredEpisode.runtime'] || null, seasonId: listItem['mediaItem.lastAiredEpisode.seasonId'], seasonNumber: listItem['mediaItem.lastAiredEpisode.seasonNumber'], title: listItem['mediaItem.lastAiredEpisode.title'], tmdbId: listItem['mediaItem.lastAiredEpisode.tmdbId'], traktId: listItem['mediaItem.lastAiredEpisode.traktId'], tvdbId: listItem['mediaItem.lastAiredEpisode.tvdbId'], tvShowId: listItem['listItem.mediaItemId'], } : undefined, upcomingEpisode: listItem['mediaItem.upcomingEpisode.id'] !== null ? { description: listItem['mediaItem.upcomingEpisode.description'], episodeNumber: listItem['mediaItem.upcomingEpisode.episodeNumber'], id: listItem['mediaItem.upcomingEpisode.id'], imdbId: listItem['mediaItem.upcomingEpisode.imdbId'], isSpecialEpisode: Boolean( listItem['mediaItem.upcomingEpisode.isSpecialEpisode'] ), releaseDate: listItem['mediaItem.upcomingEpisode.releaseDate'], runtime: listItem['mediaItem.upcomingEpisode.runtime'] || null, seasonId: listItem['mediaItem.upcomingEpisode.seasonId'], seasonNumber: listItem['mediaItem.upcomingEpisode.seasonNumber'], title: listItem['mediaItem.upcomingEpisode.title'], tmdbId: listItem['mediaItem.upcomingEpisode.tmdbId'], traktId: listItem['mediaItem.upcomingEpisode.traktId'], tvdbId: listItem['mediaItem.upcomingEpisode.tvdbId'], tvShowId: listItem['listItem.mediaItemId'], } : undefined, }, ...(listItem['listItem.seasonId'] ? { season: { id: listItem['listItem.seasonId'], isSpecialSeason: Boolean(listItem['season.isSpecialSeason']), airedEpisodesCount: listItem['season.airedEpisodesCount'], seenEpisodesCount: listItem['season.seenEpisodesCount'], unseenEpisodesCount: listItem['season.airedEpisodesCount'] ? listItem['season.airedEpisodesCount'] - listItem['season.seenEpisodesCount'] : undefined, seen: listItem['season.airedEpisodesCount'] - listItem['season.seenEpisodesCount'] === 0, releaseDate: listItem['season.releaseDate'], seasonNumber: listItem['season.seasonNumber'], title: listItem['season.title'], tmdbId: listItem['season.tmdbId'], traktId: listItem['season.traktId'], tvdbId: listItem['season.tvdbId'], tvShowId: listItem['listItem.mediaItemId'], totalRuntime: listItem['season.totalRuntime'] || null, userRating: listItem['season.userRating.rating'] ? { mediaItemId: listItem['listItem.mediaItemId'], seasonId: listItem['listItem.seasonId'], date: listItem['season.userRating.date'], rating: listItem['season.userRating.rating'], userId: userId, } : undefined, onWatchlist: Boolean(listItem['season.watchlist.id']), lastSeenAt: listItem['season.lastSeenAt'], firstUnwatchedEpisode: listItem[ 'season.firstUnwatchedEpisode.episodeNumber' ] ? { description: listItem['season.firstUnwatchedEpisode.description'], episodeNumber: listItem['season.firstUnwatchedEpisode.episodeNumber'], id: listItem['season.firstUnwatchedEpisode.id'], imdbId: listItem['season.firstUnwatchedEpisode.imdbId'], isSpecialEpisode: Boolean( listItem['season.firstUnwatchedEpisode.isSpecialEpisode'] ), releaseDate: listItem['season.firstUnwatchedEpisode.releaseDate'], runtime: listItem['season.firstUnwatchedEpisode.runtime'] || null, seasonId: listItem['season.firstUnwatchedEpisode.seasonId'], seasonNumber: listItem['season.firstUnwatchedEpisode.seasonNumber'], title: listItem['season.firstUnwatchedEpisode.title'], tmdbId: listItem['season.firstUnwatchedEpisode.tmdbId'], traktId: listItem['season.firstUnwatchedEpisode.traktId'], tvdbId: listItem['season.firstUnwatchedEpisode.tvdbId'], tvShowId: listItem['season.firstUnwatchedEpisode.tvShowId'], } : undefined, lastAiredEpisode: listItem['season.lastAiredEpisode.id'] !== null ? { description: listItem['season.lastAiredEpisode.description'], episodeNumber: listItem['season.lastAiredEpisode.episodeNumber'], id: listItem['season.lastAiredEpisode.id'], imdbId: listItem['season.lastAiredEpisode.imdbId'], isSpecialEpisode: Boolean( listItem['season.lastAiredEpisode.isSpecialEpisode'] ), releaseDate: listItem['season.lastAiredEpisode.releaseDate'], runtime: listItem['season.lastAiredEpisode.runtime'] || null, seasonId: listItem['season.lastAiredEpisode.seasonId'], seasonNumber: listItem['season.lastAiredEpisode.seasonNumber'], title: listItem['season.lastAiredEpisode.title'], tmdbId: listItem['season.lastAiredEpisode.tmdbId'], traktId: listItem['season.lastAiredEpisode.traktId'], tvdbId: listItem['season.lastAiredEpisode.tvdbId'], tvShowId: listItem['listItem.mediaItemId'], } : undefined, }, } : {}), ...(listItem['listItem.episodeId'] ? { episode: { episodeNumber: listItem['episode.episodeNumber'], id: listItem['listItem.episodeId'], imdbId: listItem['episode.imdbId'], isSpecialEpisode: Boolean(listItem['episode.isSpecialEpisode']), releaseDate: listItem['episode.releaseDate'], seasonNumber: listItem['episode.seasonNumber'], title: listItem['episode.title'], tmdbId: listItem['episode.tmdbId'], traktId: listItem['episode.traktId'], tvdbId: listItem['episode.tvdbId'], tvShowId: listItem['listItem.mediaItemId'], seasonAndEpisodeNumber: listItem['episode.seasonAndEpisodeNumber'], progress: listItem['episode.progress'], runtime: listItem['episode.runtime'] || null, userRating: listItem['episode.userRating.rating'] ? { mediaItemId: listItem['listItem.mediaItemId'], episodeId: listItem['listItem.episodeId'], date: listItem['episode.userRating.date'], rating: listItem['episode.userRating.rating'], userId: userId, } : undefined, onWatchlist: Boolean(listItem['episode.watchlist.id']), lastSeenAt: listItem['episode.lastSeenAt'], seen: Boolean(listItem['episode.lastSeenAt']), }, } : {}), })); } } export const listRepository = new ListRepository();
the_stack
import { matchLeft, matchRight, matchLeftIncl, matchRightIncl, } from "string-match-left-right"; import clone from "lodash.clonedeep"; import { left, right } from "string-left-right"; import { isAttrClosing } from "is-html-attribute-closing"; import { allHtmlAttribs } from "html-all-known-attributes"; import { isAttrNameChar } from "is-char-suitable-for-html-attr-name"; import getWholeEspTagLumpOnTheRight from "./util/getWholeEspTagLumpOnTheRight"; import startsHtmlComment from "./util/startsHtmlComment"; import startsCssComment from "./util/startsCssComment"; import matchLayerLast from "./util/matchLayerLast"; import startsTag from "./util/startsTag"; import startsEsp from "./util/startsEsp"; import getLastEspLayerObjIdx from "./util/getLastEspLayerObjIdx"; import { charSuitableForTagName, isTagNameRecognised, xBeforeYOnTheRight, espLumpBlacklist, isLatinLetter, veryEspChars, flipEspTag, espChars, isObj, Token, voidTags, inlineTags, BACKTICK, charsThatEndCSSChunks, SOMEQUOTE, attrNameRegexp, Attrib, TokenType, TextToken, RuleToken, CommentToken, CharacterToken, TagToken, Property, LayerType, LayerSimple, LayerEsp, EspToken, Layer, LayerKindAt, Opts, TokenCb, CharCb, } from "./util/util"; import { version as v } from "../package.json"; const version: string = v; const importantStartsRegexp = /^\s*!?\s*[a-zA-Z0-9]+(?:[\s;}<>'"]|$)/gm; const defaults: Opts = { tagCb: null, tagCbLookahead: 0, charCb: null, charCbLookahead: 0, reportProgressFunc: null, reportProgressFuncFrom: 0, reportProgressFuncTo: 100, }; interface Res { timeTakenInMilliseconds: number; } /** * HTML and CSS lexer aimed at code with fatal errors, accepts mixed coding languages */ function tokenizer(str: string, originalOpts?: Partial<Opts>): Res { const start = Date.now(); // // // // // // // // INSURANCE // --------------------------------------------------------------------------- if (typeof str !== "string") { if (str === undefined) { throw new Error( "codsen-tokenizer: [THROW_ID_01] the first input argument is completely missing! It should be given as string." ); } else { throw new Error( `codsen-tokenizer: [THROW_ID_02] the first input argument must be string! It was given as "${typeof str}", equal to:\n${JSON.stringify( str, null, 4 )}` ); } } if (originalOpts && !isObj(originalOpts)) { throw new Error( `codsen-tokenizer: [THROW_ID_03] the second input argument, an options object, should be a plain object but it was given as type ${typeof originalOpts}, equal to ${JSON.stringify( originalOpts, null, 4 )}` ); } if ( originalOpts && isObj(originalOpts) && originalOpts.tagCb && typeof originalOpts.tagCb !== "function" ) { throw new Error( `codsen-tokenizer: [THROW_ID_04] the opts.tagCb, callback function, should be a function but it was given as type ${typeof originalOpts.tagCb}, equal to ${JSON.stringify( originalOpts.tagCb, null, 4 )}` ); } if ( originalOpts && isObj(originalOpts) && originalOpts.charCb && typeof originalOpts.charCb !== "function" ) { throw new Error( `codsen-tokenizer: [THROW_ID_05] the opts.charCb, callback function, should be a function but it was given as type ${typeof originalOpts.charCb}, equal to ${JSON.stringify( originalOpts.charCb, null, 4 )}` ); } if ( originalOpts && isObj(originalOpts) && originalOpts.reportProgressFunc && typeof originalOpts.reportProgressFunc !== "function" ) { throw new Error( `codsen-tokenizer: [THROW_ID_06] the opts.reportProgressFunc, callback function, should be a function but it was given as type ${typeof originalOpts.reportProgressFunc}, equal to ${JSON.stringify( originalOpts.reportProgressFunc, null, 4 )}` ); } // // // // // // // // OPTS // --------------------------------------------------------------------------- const opts: Opts = { ...defaults, ...originalOpts }; // // // // // // // // VARS // --------------------------------------------------------------------------- let currentPercentageDone = 0; let lastPercentage = 0; const len = str.length; const midLen = Math.floor(len / 2); let doNothing = 0; // index until where to do nothing let withinScript = false; // marks a state of being between <script> and </script> let withinStyle = false; // flag used to instruct content after <style> to toggle type="css" let withinStyleComment = false; // opts.*CbLookahead allows to request "x"-many tokens "from the future" // to be reported upon each token. You can check what's coming next. // To implement this, we need to stash "x"-many tokens and only when enough // have been gathered, array.shift() the first one and ping the callback // with it, along with "x"-many following tokens. Later, in the end, // we clean up stashes and report only as many as we have. // The stashes will be LIFO (last in first out) style arrays: const tagStash: Token[] = []; const charStash: CharacterToken[] = []; // when we compile the token, we fill this object: let token: Token = {} as Token; function tokenReset() { // object-assign is basically cloning - objects are passed by reference, // we can't risk mutating the default object: console.log( `202 ${`\u001b[${36}m${`██ tokenReset():`}\u001b[${39}m`} tokenReset() called` ); token = { type: null, start: null, end: null, value: null, } as any; attribReset(); } // same for attributes: const attribDefaults: Attrib = { attribName: "", attribNameRecognised: false, attribNameStartsAt: null as any, attribNameEndsAt: null as any, attribOpeningQuoteAt: null, attribClosingQuoteAt: null, attribValueRaw: null as any, attribValue: [], attribValueStartsAt: null, attribValueEndsAt: null, attribStarts: null as any, attribEnds: null as any, attribLeft: null as any, }; let attrib: Attrib = { ...attribDefaults }; function attribReset() { // object-assign is basically cloning - objects are passed by reference, // we can't risk mutating the default object: console.log( `234 ${`\u001b[${36}m${`██ attribReset():`}\u001b[${39}m`} attribReset() called` ); attrib = clone(attribDefaults); } function attribPush(tokenObj: TextToken | CommentToken | Property): void { console.log(`240`); // 1. clean up any existing tokens first /* istanbul ignore else */ if ( attrib.attribValue.length && attrib.attribValue[~-attrib.attribValue.length].start && !attrib.attribValue[~-attrib.attribValue.length].end ) { attrib.attribValue[~-attrib.attribValue.length].end = tokenObj.start; attrib.attribValue[~-attrib.attribValue.length].value = str.slice( attrib.attribValue[~-attrib.attribValue.length].start as number, tokenObj.start as number ); console.log( `254 complete previous attr, ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); } attrib.attribValue.push(tokenObj); console.log( `264 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} to ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} now = ${JSON.stringify( attrib, null, 4 )}` ); } // same for property const propertyDefault: Property = { start: null as any, // a convenience value, mirroring "propertyStarts" end: null as any, // a convenience value, mirroring whatever was last property: null, propertyStarts: null, propertyEnds: null, value: null as any, valueStarts: null, valueEnds: null, important: null, importantStarts: null, importantEnds: null, colon: null, semi: null, }; let property: Property = { ...propertyDefault }; function propertyReset() { property = { ...propertyDefault }; } // The CSS properties can be in <style> blocks or inline, <div style="">. // When we process the code, we have to address both places. This "push" // is used in handful of places so we DRY'ed it to a function. function pushProperty(p: Property | TextToken) { // push and init and patch up to resume if (attrib && attrib.attribName === "style") { console.log(`299 push property`); console.log( `301 FIY, ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); console.log( `308 FIY, ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValue, null, 4 )}` ); attrib.attribValue.push({ ...p }); } else if (token && Array.isArray((token as RuleToken).properties)) { console.log(`316 push property`); (token as RuleToken).properties.push({ ...p }); } } // Initial resets: tokenReset(); // --------------------------------------------------------------------------- let selectorChunkStartedAt; // For example: // // <style type="text/css"> // .unused1[z].unused2, .used[z] {a:1;} // | | // <-selector chunk -> // // // --------------------------------------------------------------------------- let parentTokenToBackup; // We use it for nested ESP tags - for example, <td{% z %}> // The esp tag {% z %} is nested among the tag's attributes: // { // type: "tag", // start: 0, // end: 11, // value: `<td{% z %}>`, // attribs: [ // { // type: "esp", // start: 3, // end: 10, // value: "{% z %}", // head: "{%", // tail: "%}", // kind: null, // }, // ], // } // // to allow this, we have to save the current, parent token, in case above, // <td...> and then initiate the ESP token, which later will get nested let attribToBackup; // We use it when ESP tag is inside the attribute: // <a b="{{ c }}d"> // // we need to back up both tag and attrib objects, assemble esp tag, then // restore both and stick it inside the "attrib"'s array "attribValue": // // attribValue: [ // { // type: "esp", // start: 6, // end: 13, // value: "{{ c }}", // head: "{{", // tail: "}}", // }, // { // type: "text", // start: 13, // end: 14, // value: "d", // }, // ], let lastNonWhitespaceCharAt = null; // --------------------------------------------------------------------------- // // // // // // // // INNER FUNCTIONS // --------------------------------------------------------------------------- // When we enter the double quotes or any other kind of "layer", we need to // ignore all findings until the "layer" is exited. Here we keep note of the // closing strings which exit the current "layer". There can be many of them, // nested and escaped and so on. const layers: Layer[] = []; // example of contents: // [ // { // type: "simple", // value: "'", // }, // { // type: "esp", // guessedClosingLump: "%}" // } // ] // there can be two types of layer values: simple strings to match html/css // token types and complex, to match esp tokens heuristically, where we don't // know exact ESP tails but we know set of characters that suspected "tail" // should match. // function lastLayerIs(something: LayerType): boolean { return !!( Array.isArray(layers) && layers.length && layers[~-layers.length].type === something ); } // processes closing comment - it's DRY'ed here because it's in multiple places // considering broken code like stray closing inline css comment blocks etc. function closingComment(i: number): void { console.log( `433 closingComment(): ${`\u001b[${32}m${`closing comment`}\u001b[${39}m`}` ); const end = (right(str, i) || i) + 1; attribPush({ type: "comment", start: i, end, value: str.slice(i, end), // think of broken cases with whitespace, / * closing: true, kind: "block", language: "css", }); // skip next character doNothing = end; console.log( `449 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); // pop the block comment layer if (lastLayerIs("block")) { layers.pop(); console.log( `460 ${`\u001b[${31}m${`POP`}\u001b[${39}m`} layers, now = ${JSON.stringify( layers, null, 4 )}` ); } } function reportFirstFromStash( stash: (CharacterToken | Token)[], cb: null | CharCb | TokenCb, lookaheadLength: number ) { console.time("reportFirstFromStash()"); console.log( `476 ${`\u001b[${35}m${`reportFirstFromStash()`}\u001b[${39}m`}: ██ ${`\u001b[${33}m${`START`}\u001b[${39}m`}` ); // start to assemble node we're report to the callback cb1() const currentElem = stash.shift(); // ^ shift removes it from stash // now we need the "future" nodes, as many as "lookahead" of them // that's the container where they'll sit: const next = []; for (let i = 0; i < lookaheadLength; i++) { console.log(`i = ${i}`); // we want as many as "lookaheadLength" from stash but there might be // not enough there if (stash[i]) { next.push(clone(stash[i])); console.log(`492`); } else { console.log( `495 ${`\u001b[${35}m${`reportFirstFromStash()`}\u001b[${39}m`}: ${`\u001b[${31}m${`STOP`}\u001b[${39}m`} - there are not enough elements in stash` ); break; } } // finally, ping the callback with assembled element: console.log( `503 ${`\u001b[${35}m${`reportFirstFromStash()`}\u001b[${39}m`}: ${`\u001b[${32}m${`PING CB`}\u001b[${39}m`} with ${JSON.stringify( currentElem, null, 4 )}` ); if (typeof cb === "function") { cb(currentElem as any, next as any[]); } console.timeEnd("reportFirstFromStash()"); } function pingCharCb(incomingToken: CharacterToken) { console.time("pingCharCb()"); // no cloning, no reset if (opts.charCb) { // if there were no stashes, we'd call the callback like this: // opts.charCb(incomingToken); // 1. push to stash charStash.push(incomingToken); // 2. is there are enough tokens in the stash, ping the first-one console.log( `527 ${ charStash.length > opts.charCbLookahead ? `${`\u001b[${36}m${`pingCharCb()`}\u001b[${39}m`}: ${`\u001b[${32}m${`ENOUGH VALUES IN CHAR STASH`}\u001b[${39}m`}` : `${`\u001b[${36}m${`pingCharCb()`}\u001b[${39}m`}: ${`\u001b[${31}m${`NOT ENOUGH VALUES IN CHAR STASH, MOVE ON`}\u001b[${39}m`}` }` ); if (charStash.length > opts.charCbLookahead) { reportFirstFromStash(charStash, opts.charCb, opts.charCbLookahead); console.log( `536 ${`\u001b[${90}m${`██ charStash`}\u001b[${39}m`} = ${JSON.stringify( charStash, null, 4 )}` ); } } console.timeEnd("pingCharCb()"); } function pingTagCb(incomingToken: Token) { console.time("pingTagCb()"); if (opts.tagCb) { // console.log( // `419 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} tagCb() with ${JSON.stringify( // incomingToken, // null, // 4 // )}` // ); // opts.tagCb(clone(incomingToken)); // 1. push to stash tagStash.push(incomingToken); // 2. is there are enough tokens in the stash, ping the first-one console.log( `564 ${ tagStash.length > opts.tagCbLookahead ? `${`\u001b[${36}m${`pingTagCb()`}\u001b[${39}m`}: ${`\u001b[${32}m${`ENOUGH VALUES IN TAG STASH`}\u001b[${39}m`}` : `${`\u001b[${36}m${`pingTagCb()`}\u001b[${39}m`}: ${`\u001b[${31}m${`NOT ENOUGH VALUES IN TAG STASH, MOVE ON`}\u001b[${39}m`}` }` ); if (tagStash.length > opts.tagCbLookahead) { reportFirstFromStash(tagStash, opts.tagCb, opts.tagCbLookahead); console.log( `573 pingTagCb(): ${`\u001b[${90}m${`██ tagStash`}\u001b[${39}m`} = ${JSON.stringify( tagStash, null, 4 )}` ); } } console.timeEnd("pingTagCb()"); } function dumpCurrentToken(incomingToken: Token, i: number): void { console.log( `586 ${`\u001b[${35}m${`dumpCurrentToken()`}\u001b[${39}m`}; incoming incomingToken=${JSON.stringify( incomingToken, null, 0 )}; i = ${`\u001b[${33}m${i}\u001b[${39}m`}` ); // Let's ensure it was not a token with trailing whitespace, because now is // the time to separate it and report it as a standalone token. // Also, the following clause will catch the unclosed tags like // <a href="z" click here</a> if ( !["text", "esp"].includes(incomingToken.type) && incomingToken.start !== null && incomingToken.start < i && ((str[~-i] && !str[~-i].trim()) || str[i] === "<") ) { console.log(`603`); // this ending is definitely a token ending. Now the question is, // maybe we need to split all gathered token contents into two: // maybe it's a tag and a whitespace? or an unclosed tag? // in some cases, this token.end will be only end of a second token, // we'll need to find where this last chunk started and terminate the // previous token (one which started at the current token.start) there. if (left(str, i) !== null) { console.log(`611`); incomingToken.end = (left(str, i) as number) + 1; } else { console.log(`614`); incomingToken.end = i; } incomingToken.value = str.slice(incomingToken.start, incomingToken.end); console.log( `619 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`incomingToken.end`}\u001b[${39}m`} = ${ incomingToken.end } (last two characters ending at incomingToken.end: ${JSON.stringify( str[~-incomingToken.end], null, 4 )} + ${JSON.stringify( str[incomingToken.end], null, 4 )}); ${`\u001b[${33}m${`incomingToken.value`}\u001b[${39}m`} = "${ incomingToken.value }"` ); if ( incomingToken.type === "tag" && !"/>".includes(str[~-incomingToken.end]) ) { console.log( `638 ${`\u001b[${35}m${`██ UNCLOSED TAG CASES`}\u001b[${39}m`}` ); // we need to potentially shift the incomingToken.end left, imagine: // <a href="z" click here</a> // ^ // we are here ("i" value), that's incomingToken.end currently // // <a href="z" click here</a> // ^ // incomingToken.end should be here // // PLAN: take current token, if there are attributes, validate // each one of them, terminate at the point of the first smell. // If there are no attributes, terminate at the end of a tag name let cutOffIndex = incomingToken.tagNameEndsAt || i; if ( Array.isArray(incomingToken.attribs) && incomingToken.attribs.length ) { console.log( `660 ${`\u001b[${32}m${`██ validate all attributes`}\u001b[${39}m`}` ); // initial cut-off point is token.tagNameEndsAt console.log(`663 SET cutOffIndex = ${cutOffIndex}`); // with each validated attribute, push the cutOffIndex forward: for ( let i2 = 0, len2 = incomingToken.attribs.length; i2 < len2; i2++ ) { console.log( `671 ${`\u001b[${36}m${`incomingToken.attribs[${i2}]`}\u001b[${39}m`} = ${JSON.stringify( incomingToken.attribs[i2], null, 4 )}` ); if ( incomingToken.attribs[i2].attribNameRecognised && incomingToken.attribs[i2].attribEnds ) { cutOffIndex = incomingToken.attribs[i2].attribEnds as number; console.log( `683 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`cutOffIndex`}\u001b[${39}m`} = ${cutOffIndex}` ); // small tweak - consider this: // <a href="z" click here</a> // ^ // this space in particular // that space above should belong to the tag's index range, // unless the whitespace is bigger than 1: // <a href="z" click here</a> if ( str[cutOffIndex + 1] && !str[cutOffIndex].trim() && str[cutOffIndex + 1].trim() ) { cutOffIndex += 1; console.log( `702 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`cutOffIndex`}\u001b[${39}m`} = ${cutOffIndex}` ); } } else { console.log(`706 ${`\u001b[${31}m${`BREAK`}\u001b[${39}m`}`); // delete false attributes from incomingToken.attribs if (i2 === 0) { // if it's the first attribute and it's already // not suitable, for example: // <a click here</a> // all attributes ("click", "here") are removed: incomingToken.attribs = []; } else { // leave only attributes up to i2-th incomingToken.attribs = incomingToken.attribs.splice(0, i2); } console.log( `719 ${`\u001b[${32}m${`CALCULATED`}\u001b[${39}m`} ${`\u001b[${33}m${`incomingToken.attribs`}\u001b[${39}m`} = ${JSON.stringify( incomingToken.attribs, null, 4 )}` ); // in the end stop the loop: break; } } } incomingToken.end = cutOffIndex; incomingToken.value = str.slice(incomingToken.start, incomingToken.end); if (!incomingToken.tagNameEndsAt) { incomingToken.tagNameEndsAt = cutOffIndex; console.log( `737 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`incomingToken.tagNameEndsAt`}\u001b[${39}m`} = ${ incomingToken.tagNameEndsAt }` ); } if ( incomingToken.tagNameStartsAt && incomingToken.tagNameEndsAt && !incomingToken.tagName ) { incomingToken.tagName = str.slice( incomingToken.tagNameStartsAt, cutOffIndex ); console.log( `752 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`incomingToken.tagName`}\u001b[${39}m`} = ${ incomingToken.tagName }` ); incomingToken.recognised = isTagNameRecognised(incomingToken.tagName); } console.log(`759 ${`\u001b[${32}m${`PING`}\u001b[${39}m`}`); pingTagCb(incomingToken); initToken("text", cutOffIndex); attribReset(); console.log( `764 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.start`}\u001b[${39}m`} = ${ token.start }; ${`\u001b[${33}m${`token.type`}\u001b[${39}m`} = ${token.type}` ); } else { console.log(`769 ${`\u001b[${35}m${`██ HEALTHY TAG`}\u001b[${39}m`}`); console.log(`770 ${`\u001b[${32}m${`PING`}\u001b[${39}m`}`); pingTagCb(incomingToken); console.log(`772 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); // if there was whitespace after token's end: if (str[~-i] && !str[~-i].trim()) { console.log(`776 indeed there was whitespace after token's end`); initToken("text", (left(str, i) as number) + 1); attribReset(); console.log( `780 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.start`}\u001b[${39}m`} = ${ token.start }; ${`\u001b[${33}m${`token.type`}\u001b[${39}m`} = ${token.type}` ); } } console.log( `788 FINALLY, ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); } // if a token is already being recorded, end it if (token.start !== null) { console.log(`798 *`); if (token.end === null && token.start !== i) { // (esp tags will have it set already) token.end = i; token.value = str.slice(token.start, token.end); console.log( `804 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }; ${`\u001b[${33}m${`token.value`}\u001b[${39}m`} = ${JSON.stringify( token.value, null, 4 )}` ); } // normally we'd ping the token but let's not forget we have token stashes // in "attribToBackup" and "parentTokenToBackup" console.log(`817 *`); if (token.start !== null && token.end) { // if it's a text token inside "at" rule, nest it, push into that // "at" rule pending in layers - otherwise, ping as standalone if (lastLayerIs("at")) { (layers[~-layers.length] as LayerKindAt).token.rules.push( token as any ); console.log( `826 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} into layers AT rule` ); } else { console.log( `830 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} as standalone` ); pingTagCb(token); } } console.log(`835 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); } console.log(`839 end of dumpCurrentToken() reached`); console.timeEnd("dumpCurrentToken()"); } function atRuleWaitingForClosingCurlie() { return ( lastLayerIs("at") && isObj((layers[~-layers.length] as LayerKindAt).token) && (layers[~-layers.length] as LayerKindAt).token.openingCurlyAt && !(layers[~-layers.length] as LayerKindAt).token.closingCurlyAt ); } function getNewToken(type: TokenType, startVal: number | null = null): Token { if (type === "tag") { return { type, start: startVal as any, end: null as any, value: null as any, tagNameStartsAt: null as any, tagNameEndsAt: null as any, tagName: null as any, recognised: null, closing: false, void: false, pureHTML: true, // meaning there are no esp bits kind: null, attribs: [], }; } if (type === "comment") { return { type, start: startVal as any, end: null as any, value: null as any, closing: false, kind: "simple", // or "only" or "not" (HTML) - OR - "block" or "line" (CSS) language: "html", // or "css" }; } if (type === "rule") { return { type, start: startVal as any, end: null as any, value: null as any, left: null, nested: false, openingCurlyAt: null, closingCurlyAt: null, selectorsStart: null, selectorsEnd: null, selectors: [], properties: [], }; } if (type === "at") { return { type, start: startVal as any, end: null as any, value: null as any, left: null, nested: false, openingCurlyAt: null, closingCurlyAt: null, identifier: null, identifierStartsAt: null, identifierEndsAt: null, query: null as any, queryStartsAt: null as any, queryEndsAt: null as any, rules: [], }; } if (type === "esp") { return { type, start: startVal as any, end: null as any, value: null as any, head: null, headStartsAt: null, headEndsAt: null, tail: null, tailStartsAt: null, tailEndsAt: null, }; } // a default is text token return { type: "text", start: startVal as any, end: null as any, value: null as any, }; } function initToken(type: TokenType, startVal: number | null): void { console.time("initToken()"); // we mutate the object on the parent scope, so no Object.assign here token = getNewToken(type, startVal); console.timeEnd("initToken()"); } function initProperty(propertyStarts: number | Partial<Property>): void { console.time("initProperty()"); // we mutate the object on the parent scope, so no Object.assign here propertyReset(); if (typeof propertyStarts === "number") { property.propertyStarts = propertyStarts; property.start = propertyStarts; console.timeEnd("initProperty()"); } else { property = { ...propertyDefault, ...propertyStarts }; } } function ifQuoteThenAttrClosingQuote(idx: number): boolean { // either it's not a quote: return ( !`'"`.includes(str[idx]) || // precaution when both attrib.attribOpeningQuoteAt and // attrib.attribValueStartsAt are missing and thus unusable - just // skip this clause in that case... (but it should not ever happen) !(attrib.attribOpeningQuoteAt || attrib.attribValueStartsAt) || // or it's real closing quote, because if not, let's keep it within // the value, it will be easier to validate, imagine: // <div style="float:"left""> // isAttrClosing( str, (attrib.attribOpeningQuoteAt || attrib.attribValueStartsAt) as number, idx ) ); } function attrEndsAt(idx: number, extras?: boolean): boolean { console.log( `981 incoming: ${`\u001b[${33}m${`extras`}\u001b[${39}m`} = ${JSON.stringify( extras, null, 4 )}` ); // either we're within normal head css styles: return ( (`;}/`.includes(str[idx]) && (!attrib || !attrib.attribName || attrib.attribName !== "style")) || // or within inline css styles within html (`/;'"><`.includes(str[idx]) && attrib && attrib.attribName === "style" && // and it's a real quote, not rogue double-wrapping around the value (extras || ifQuoteThenAttrClosingQuote(idx))) ); } // // // // // // // // THE MAIN LOOP // --------------------------------------------------------------------------- // We deliberately step 1 character outside of str length // to simplify the algorithm. Thusly, it's i <= len not i < len: for (let i = 0; i <= len; i++) { console.time(`\u001b[${90}m${`loop iteration`}\u001b[${39}m`); // // // // // THE TOP // ███████ // // // // // Logging: // ------------------------------------------------------------------------- console.log( `\u001b[${36}m${`===============================`}\u001b[${39}m \u001b[${35}m${`str[ ${i} ] = ${ str[i] && str[i].trim() ? str[i] : JSON.stringify(str[i], null, 4) }`}\u001b[${39}m \u001b[${36}m${`===============================`}\u001b[${39}m\n` ); // Progress: // ------------------------------------------------------------------------- if (!doNothing && str[i] && opts.reportProgressFunc) { if (len > 1000 && len < 2000) { if (i === midLen) { opts.reportProgressFunc( Math.floor( (opts.reportProgressFuncTo - opts.reportProgressFuncFrom) / 2 ) ); } } else if (len >= 2000) { // defaults: // opts.reportProgressFuncFrom = 0 // opts.reportProgressFuncTo = 100 currentPercentageDone = opts.reportProgressFuncFrom + Math.floor( (i / len) * (opts.reportProgressFuncTo - opts.reportProgressFuncFrom) ); if (currentPercentageDone !== lastPercentage) { lastPercentage = currentPercentageDone; opts.reportProgressFunc(currentPercentageDone); console.log(`1059 DONE ${currentPercentageDone}%`); } } } // Left/Right helpers // ------------------------------------------------------------------------- const leftVal = left(str, i); const rightVal = right(str, i); // Turn off doNothing if marker passed // ------------------------------------------------------------------------- if ( withinStyle && token.type && !["rule", "at", "text", "comment"].includes(token.type) ) { console.log( `1079 FIY, ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); withinStyle = false; console.log( `1087 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} ${`\u001b[${33}m${`withinStyle`}\u001b[${39}m`} = false` ); } if (doNothing && i >= doNothing) { doNothing = 0; console.log(`1093 TURN OFF doNothing`); } // skip chain of the same-type characters // ------------------------------------------------------------------------- if ( isLatinLetter(str[i]) && isLatinLetter(str[~-i]) && isLatinLetter(str[i + 1]) ) { // <style>.a{color:1pximportant} // ^ // mangled !important if ( property && property.valueStarts && !property.valueEnds && !property.importantStarts && str.startsWith("important", i) ) { property.valueEnds = i; property.value = str.slice(property.valueStarts, i); property.importantStarts = i; console.log( `1118 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.valueEnds`}\u001b[${39}m`} = ${ property.valueEnds }; ${`\u001b[${33}m${`property.value`}\u001b[${39}m`} = ${ property.value }; ${`\u001b[${33}m${`property.importantStarts`}\u001b[${39}m`} = ${ property.importantStarts }` ); } console.log( `1129 ${`\u001b[${32}m${`SKIP`}\u001b[${39}m`} middle of the letters chunk` ); console.timeEnd(`\u001b[${90}m${`loop iteration`}\u001b[${39}m`); continue; } if ( ` \t\r\n`.includes(str[i]) && // ~- means subtract 1 str[i] === str[~-i] && str[i] === str[i + 1] ) { console.log( `1142 ${`\u001b[${32}m${`SKIP`}\u001b[${39}m`} middle of the spaces chunk` ); console.timeEnd(`\u001b[${90}m${`loop iteration`}\u001b[${39}m`); continue; } // catch the curly tails of at-rules // ------------------------------------------------------------------------- if (!doNothing && atRuleWaitingForClosingCurlie()) { console.log(`1152 inside catch the curly tails of at-rules' clauses`); // if (token.type === null && str[i] === "}") { // if (str[i] === "}") { if (str[i] === "}") { if ( !token.type || token.type === "text" || (token.type === "rule" && token.openingCurlyAt === null) ) { // rule token must end earlier if (token.type === "rule") { console.log(`1164 complete the "rule" token`); token.end = (leftVal as number) + 1; token.value = str.slice(token.start, token.end); console.log( `1168 ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); pingTagCb(token); // if it's a text token inside "at" rule, nest it, push into that // "at" rule pending in layers - otherwise, ping as standalone if (lastLayerIs("at")) { (layers[~-layers.length] as LayerKindAt).token.rules.push(token); console.log( `1181 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} into layers AT rule` ); } console.log(`1185 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); // if there was trailing whitespace, initiate it if (leftVal !== null && leftVal < ~-i) { console.log( `1191 initiate whitespace from [${leftVal + 1}, ${i}]` ); initToken("text", leftVal + 1); attribReset(); console.log( `1196 ${`\u001b[${33}m${`token`}\u001b[${39}m`} now = ${JSON.stringify( token, null, 4 )}` ); } } console.log(`1205 call dumpCurrentToken()`); dumpCurrentToken(token, i); console.log( `1209 ${`\u001b[${35}m${`██`}\u001b[${39}m`} restore at rule from layers` ); const poppedToken = layers.pop() as LayerKindAt; token = clone(poppedToken.token); console.log(`1213 new token: ${JSON.stringify(token, null, 4)}`); // then, continue on "at" rule's token... token.closingCurlyAt = i; token.end = i + 1; token.value = str.slice(token.start, token.end); console.log( `1221 ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )} before pinging` ); pingTagCb(token); // if it's a "rule" token and a parent "at" rule is pending in layers, // also put this "rule" into that parent in layers if (lastLayerIs("at")) { console.log( `1233 ${`\u001b[${32}m${`PUSH this rule into last AT layer`}\u001b[${39}m`}` ); (layers[~-layers.length] as LayerKindAt).token.rules.push( token as any ); } console.log(`1240 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); console.log( `1244 ${`\u001b[${31}m${`skip the remaining of the program clauses for this index`}\u001b[${39}m`}` ); doNothing = i + 1; console.log( `1248 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); } } else if (token.type === "text" && str[i] && str[i].trim()) { // terminate the text token, all the non-whitespace characters comprise // rules because we're inside the at-token, it's CSS! token.end = i; token.value = str.slice(token.start, token.end); console.log( `1257 ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); // if it's a text token inside "at" rule, nest it, push into that // "at" rule pending in layers - otherwise, ping as standalone if (lastLayerIs("at")) { (layers[~-layers.length] as LayerKindAt).token.rules.push(token); console.log( `1269 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} into layers AT rule` ); } else { console.log( `1273 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} as standalone` ); pingTagCb(token); } console.log(`1277 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); } } if (token.end && token.end === i) { console.log(`1283 token was captured in the past, so push it now`); if ((token as any).tagName === "style" && !(token as any).closing) { withinStyle = true; console.log( `1287 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`withinStyle`}\u001b[${39}m`} = true` ); } // we need to retain the information after tag was dumped to tagCb() and wiped if (attribToBackup) { console.log(`1292 THIS TAG GOES INTO ATTRIBUTE'S attribValue`); // 1. restore attrib = attribToBackup; console.log( `1297 ${`\u001b[${35}m${`RESTORE`}\u001b[${39}m`} attrib from stashed, now = ${JSON.stringify( attrib, null, 4 )}` ); // 2. push current token into attrib.attribValue console.log( `1306 PUSH token to be inside ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`}` ); attrib.attribValue.push(token as any); // 3. restore real token token = clone(parentTokenToBackup) as TagToken; // 4. reset attribToBackup = undefined; parentTokenToBackup = undefined; console.log( `1318 ${`\u001b[${33}m${`FIY`}\u001b[${39}m`}, ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); } else { console.log(`1325 call dumpCurrentToken()`); dumpCurrentToken(token, i); console.log(`1328 ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} layers`); layers.length = 0; } } console.log( `1334 ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValue, null, 4 )}` ); // // // // // MIDDLE // ██████ // // // // // record "layers" like entering double quotes // ------------------------------------------------------------------------- if (!doNothing) { if ( ["tag", "at"].includes(token.type) && (token as any).kind !== "cdata" ) { console.log( `1360 ${`\u001b[${36}m${`LAYERS CLAUSES`}\u001b[${39}m`} ("tag", "rule" or "at")` ); if ( str[i] && (SOMEQUOTE.includes(str[i]) || `()`.includes(str[i])) && !( // below, we have insurance against single quotes, wrapped with quotes: // "'" or '"' - templating languages might put single quote as a sttring // character, not meaning wrapped-something. ( SOMEQUOTE.includes(str[leftVal as number]) && str[leftVal as number] === str[rightVal as number] ) ) && // protection against double-wrapped values, like // <div style="float:"left""> // // // it's not a quote or a real attr ending ifQuoteThenAttrClosingQuote(i) // because if it's not really a closing quote, it's a rogue-one and // it belongs to the current attribute's value so that later we // can catch it, validating values, imagine "float" value "left" comes // with quotes, as in ""left"" ) { console.log( `1386 ${`\u001b[${32}m${`a new layer quotes`}\u001b[${39}m`}` ); console.log( `1389 last layer's value: ${ lastLayerIs("simple") && (layers[~-layers.length] as LayerSimple).value }` ); if ( // maybe it's the closing counterpart? lastLayerIs("simple") && (layers[~-layers.length] as LayerSimple).value === flipEspTag(str[i]) ) { layers.pop(); console.log(`1401 ${`\u001b[${32}m${`POP`}\u001b[${39}m`} layers`); } else { // it's opening then layers.push({ type: "simple", value: str[i], position: i, }); console.log( `1410 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( { type: "simple", value: str[i], position: i, }, null, 4 )}` ); } } } else if ( token.type === "comment" && ["only", "not"].includes(token.kind) ) { console.log(`1426 inside "comments" layers clauses`); if ([`[`, `]`].includes(str[i])) { console.log(`1428`); if ( // maybe it's the closing counterpart? lastLayerIs("simple") && (layers[~-layers.length] as LayerSimple).value === flipEspTag(str[i]) ) { // maybe it's the closing counterpart? layers.pop(); console.log(`1437 ${`\u001b[${32}m${`POP`}\u001b[${39}m`} layers`); } else { // it's opening then layers.push({ type: "simple", value: str[i], position: i, }); console.log( `1446 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( { type: "simple", value: str[i], }, null, 4 )}` ); } } } else if ( token.type === "esp" && `'"${BACKTICK}()`.includes(str[i]) && !( // below, we have insurance against single quotes, wrapped with quotes: // "'" or '"' - templating languages might put single quote as a sttring // character, not meaning wrapped-something. ( [`"`, `'`, "`"].includes(str[leftVal as number]) && str[leftVal as number] === str[rightVal as number] ) ) ) { console.log(`1470`); if ( // maybe it's the closing counterpart? lastLayerIs("simple") && (layers[~-layers.length] as LayerSimple).value === flipEspTag(str[i]) ) { // maybe it's the closing counterpart? layers.pop(); console.log(`1478 ${`\u001b[${32}m${`POP LAYERS`}\u001b[${39}m`}`); console.log( `1481 ${`\u001b[${31}m${`skip the remaining of the program clauses for this index`}\u001b[${39}m`}` ); doNothing = i + 1; console.log( `1485 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); } else if (!`]})>`.includes(str[i])) { // it's opening then layers.push({ type: "simple", value: str[i], position: i, }); console.log( `1495 ${`\u001b[${32}m${`PUSH LAYER`}\u001b[${39}m`} ${JSON.stringify( { type: "simple", value: str[i], }, null, 4 )}` ); } } // console.log( // `1094 FIY, currently ${`\u001b[${33}m${`layers`}\u001b[${39}m`} = ${JSON.stringify( // layers, // null, // 4 // )}` // ); } // catch the start of at rule's identifierStartsAt // ------------------------------------------------------------------------- if ( !doNothing && token.type === "at" && token.start != null && i >= token.start && !token.identifierStartsAt && str[i] && str[i].trim() && str[i] !== "@" ) { // the media identifier's "entry" requirements are deliberately loose // because we want to catch errors there, imagine somebody mistakenly // adds a comma, @,media // or adds a space, @ media token.identifierStartsAt = i; console.log( `1535 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.identifierStartsAt`}\u001b[${39}m`} = ${ token.identifierStartsAt }` ); } // catch the end of the "at" rule token // ------------------------------------------------------------------------- if ( !doNothing && token.type === "at" && token.queryStartsAt && !token.queryEndsAt && `{;`.includes(str[i]) ) { console.log(`1551 end of the "at" rule token clauses start`); if (str[i] === "{") { if (str[~-i] && str[~-i].trim()) { token.queryEndsAt = i; console.log( `1556 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.queryEndsAt`}\u001b[${39}m`} = ${JSON.stringify( token.queryEndsAt, null, 4 )}` ); } else { // trim the trailing whitespace: // @media (max-width: 600px) { // ^ // this // token.queryEndsAt = leftVal !== null ? leftVal + 1 : i; // left() stops "to the left" of a character, if you used that index // for slicing, that character would be included, in our case, // @media (max-width: 600px) { // ^ // that would be index of this bracket console.log( `1575 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.queryEndsAt`}\u001b[${39}m`} = ${JSON.stringify( token.queryEndsAt, null, 4 )}` ); } } else { // ; closing, for example, illegal: // @charset "UTF-8"; // ^ // we're here // token.queryEndsAt = left(str, i + 1) || 0; console.log( `1590 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.queryEndsAt`}\u001b[${39}m`} = ${JSON.stringify( token.queryEndsAt, null, 4 )}` ); } if (token.queryStartsAt && token.queryEndsAt) { token.query = str.slice(token.queryStartsAt, token.queryEndsAt); console.log( `1601 ${`\u001b[${33}m${`token.query`}\u001b[${39}m`} = ${JSON.stringify( token.query, null, 4 )}` ); } token.end = str[i] === ";" ? i + 1 : i; token.value = str.slice(token.start as number, token.end); if (str[i] === ";") { // if code is clean, that would be @charset for example, no curlies console.log(`1614 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} the token`); pingTagCb(token); } else { // then it's opening curlie console.log(`1618 ${`\u001b[${32}m${`NEST`}\u001b[${39}m`} children`); console.log( `1620 starting ${`\u001b[${33}m${`layers`}\u001b[${39}m`} = ${JSON.stringify( layers, null, 4 )}` ); token.openingCurlyAt = i; console.log( `1629 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.openingCurlyAt`}\u001b[${39}m`} = ${ token.openingCurlyAt }` ); // push so far gathered token into layers layers.push({ type: "at", token, }); console.log( `1640 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} "at" token to layers` ); } console.log(`1644 ${`\u001b[${31}m${`REST`}\u001b[${39}m`} the token`); tokenReset(); doNothing = i + 1; console.log( `1648 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } // catch the start of the query // ------------------------------------------------------------------------- if ( !doNothing && token.type === "at" && token.identifier && str[i] && str[i].trim() && !token.queryStartsAt ) { token.queryStartsAt = i; console.log( `1669 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.queryStartsAt`}\u001b[${39}m`} = ${ token.queryStartsAt }` ); } // catch the end of at rule's identifierStartsAt // ------------------------------------------------------------------------- if ( !doNothing && token && token.type === "at" && token.identifierStartsAt && i >= (token.start as number) && str[i] && (!str[i].trim() || "()".includes(str[i])) && !token.identifierEndsAt ) { token.identifierEndsAt = i; token.identifier = str.slice(token.identifierStartsAt, i); console.log( `1691 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.identifierEndsAt`}\u001b[${39}m`} = ${ token.identifierEndsAt }; ${`\u001b[${33}m${`token.identifier`}\u001b[${39}m`} = "${ token.identifier }"` ); } // catch the end of a CSS chunk // ------------------------------------------------------------------------- // charsThatEndCSSChunks: } , { if (token.type === "rule") { if ( selectorChunkStartedAt && (charsThatEndCSSChunks.includes(str[i]) || (str[i] && rightVal && !str[i].trim() && charsThatEndCSSChunks.includes(str[rightVal]))) ) { console.log( `1713 FIY, ${`\u001b[${33}m${`selectorChunkStartedAt`}\u001b[${39}m`} was ${selectorChunkStartedAt}` ); console.log( `1716 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} to selectors[]: ${JSON.stringify( { value: str.slice(selectorChunkStartedAt, i), selectorStarts: selectorChunkStartedAt, selectorEnds: i, }, null, 4 )}` ); token.selectors.push({ value: str.slice(selectorChunkStartedAt, i), selectorStarts: selectorChunkStartedAt, selectorEnds: i, }); selectorChunkStartedAt = undefined; console.log( `1734 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`} ${`\u001b[${33}m${`selectorChunkStartedAt`}\u001b[${39}m`}` ); token.selectorsEnd = i; console.log( `1739 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.selectorsEnd`}\u001b[${39}m`} = ${ token.selectorsEnd }` ); } else if ( str[i] === "{" && str[i - 1] !== "{" && // avoid Nunjucks variable as CSS rule's value str[i + 1] !== "{" && // avoid Nunjucks variable as CSS rule's value token.openingCurlyAt && !token.closingCurlyAt ) { // we encounted an opening curly even though closing hasn't // been met yet: // <style>.a{float:left;x">.b{color: red} // ^ // we're here console.log( `1756 ${`\u001b[${31}m${`opening curlies!`}\u001b[${39}m`}` ); console.log(`1758 march backwards, find where selector chunk started`); // let selectorChunkStartedAt2; for (let y = i; y--; ) { console.log( `1762 ${`\u001b[${36}m${`str[${y}]`}\u001b[${39}m`} = ${JSON.stringify( str[y], null, 4 )}` ); if (!str[y].trim() || `{}"';`.includes(str[y])) { console.log( `1770 ${`\u001b[${34}m${`BREAK`}\u001b[${39}m`}, slice: "${`\u001b[${35}m${str.slice( y + 1, i )}\u001b[${39}m`}"` ); // patch the property if (property && property.start && !property.end) { property.end = y + 1; property.property = str.slice(property.start, property.end); console.log( `1781 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${ property.end }; ${`\u001b[${33}m${`property.property`}\u001b[${39}m`} = ${ property.property }` ); console.log( `1788 PATCHED ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); pushProperty(property); propertyReset(); console.log( `1797 push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); token.end = y + 1; token.value = str.slice(token.start, token.end); console.log( `1803 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }; ${`\u001b[${33}m${`token.value`}\u001b[${39}m`} = ${ token.value }` ); console.log( `1810 PATCHED ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); console.log(`1817 ${`\u001b[${32}m${`PING`}\u001b[${39}m`}`); pingTagCb(token); initToken(str[y + 1] === "@" ? "at" : "rule", y + 1); attribReset(); token.left = left(str, y + 1); token.selectorsStart = y + 1; console.log( `1824 NEW ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); i = y + 1; console.log( `1833 ${`\u001b[${31}m${`REWIND`}\u001b[${39}m`} ${`\u001b[${33}m${`i`}\u001b[${39}m`} = ${JSON.stringify( i, null, 4 )}` ); } break; } } } } // catch the beginning of a token // ------------------------------------------------------------------------- // imagine layers are like this: // [ // { // type: "esp", // openingLump: "<%@", // guessedClosingLump: "@%>", // position: 0, // }, // { // type: "simple", // value: '"', // position: 17, // }, // { // type: "simple", // value: "'", // position: 42, // }, // ]; // we extract the last type="esp" layer to simplify calculations const lastEspLayerObjIdx = getLastEspLayerObjIdx(layers); console.log(`1873 main sorting checks start`); console.time(`main-sorting-checks`); if (!doNothing && str[i]) { // console.log( // `1857 ███████████████████████████████████████ IS TAG STARTING? ${startsTag( // str, // i, // token, // layers, // withinStyle // )}` // ); // console.log( // `1707 ███████████████████████████████████████ IS COMMENT STARTING? ${startsHtmlComment( // str, // i, // token, // layers, // withinStyle // )}` // ); // console.log( // `1717 ███████████████████████████████████████ IS ESP TAG STARTING? ${startsEsp( // str, // i, // token, // layers, // withinStyle // )}` // ); if (startsTag(str, i, token, layers, withinStyle, leftVal, rightVal)) { // // // // TAG STARTING // // // console.log(`1914 (html) tag opening`); if (token.type && token.start !== null) { if (token.type === "rule") { console.log(`1918`); if (property && property.start) { // patch important if needed if (property.importantStarts && !property.importantEnds) { property.importantEnds = i; property.important = str.slice(property.importantStarts, i); console.log( `1925 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.importantEnds`}\u001b[${39}m`} = ${ property.importantEnds }; ${`\u001b[${33}m${`property.important`}\u001b[${39}m`} = "${ property.important }"` ); } // patch property if (property.propertyStarts && !property.propertyEnds) { property.propertyEnds = i; console.log( `1936 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.propertyEnds`}\u001b[${39}m`} = ${ property.propertyEnds }` ); if (!property.property) { property.property = str.slice(property.propertyStarts, i); console.log( `1943 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.property`}\u001b[${39}m`} = ${JSON.stringify( property.property, null, 4 )}` ); } } if (!property.end) { property.end = i; console.log( `1954 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${ property.end }` ); } // patch value if (property.valueStarts && !property.valueEnds) { property.valueEnds = i; console.log( `1964 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.valueEnds`}\u001b[${39}m`} = ${ property.valueEnds }` ); if (!property.value) { property.value = str.slice(property.valueStarts, i); console.log( `1971 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.value`}\u001b[${39}m`} = ${JSON.stringify( property.value, null, 4 )}` ); } } pushProperty(property); propertyReset(); console.log( `1983 push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); } } console.log(`1988 call dumpCurrentToken()`); dumpCurrentToken(token, i); console.log(`1991 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); } // add other HTML-specific keys onto the object // second arg is "start" key: initToken("tag", i); attribReset(); console.log( `2001 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.start`}\u001b[${39}m`} = ${ token.start }; ${`\u001b[${33}m${`token.type`}\u001b[${39}m`} = ${token.type}` ); if (withinStyle) { withinStyle = false; console.log( `2009 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`withinStyle`}\u001b[${39}m`} = false` ); } // extract the tag name: const badCharacters = `?![-/`; let extractedTagName = ""; let letterMet = false; console.log("."); console.log( `2019 ${`\u001b[${36}m${`extract the tag name`}\u001b[${39}m`}` ); if (rightVal) { for (let y = rightVal as number; y < len; y++) { console.log( `${`\u001b[${36}m${`str[y]`}\u001b[${39}m`} = ${JSON.stringify( str[y], null, 4 )}` ); if ( !letterMet && str[y] && str[y].trim() && str[y].toUpperCase() !== str[y].toLowerCase() ) { letterMet = true; } if ( // at least one letter has been met, to cater // <? xml ... letterMet && str[y] && // it's whitespace (!str[y].trim() || // or symbol which definitely does not belong to a tag, // considering we want to catch some rogue characters to // validate and flag them up later (!/\w/.test(str[y]) && !badCharacters.includes(str[y])) || str[y] === "[") // if letter has been met, "[" is also terminating character // think <![CDATA[x<y]]> // ^ // this ) { console.log( `2057 SET ${`\u001b[${33}m${`extractedTagName`}\u001b[${39}m`} = ${JSON.stringify( extractedTagName, null, 4 )}` ); break; } else if (!badCharacters.includes(str[y])) { extractedTagName += str[y].trim().toLowerCase(); } } } console.log("."); // set the kind: if (extractedTagName === "doctype") { (token as TagToken).kind = "doctype"; console.log( `2077 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ (token as TagToken).kind }` ); } else if (extractedTagName === "cdata") { (token as TagToken).kind = "cdata"; console.log( `2084 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ (token as TagToken).kind }` ); } else if (extractedTagName === "xml") { (token as TagToken).kind = "xml"; console.log( `2091 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ (token as TagToken).kind }` ); } else if (inlineTags.has(extractedTagName)) { (token as TagToken).kind = "inline"; console.log( `2098 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ (token as TagToken).kind }` ); if (extractedTagName) { // for perf doNothing = i; console.log( `2107 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } } } else if (!withinScript && startsHtmlComment(str, i, token, layers)) { // // // // HTML COMMENT STARTING // // // console.log(`2123 HTML comment opening`); if (token.start != null) { console.log(`2126 call dumpCurrentToken()`); dumpCurrentToken(token, i); } // add other HTML-specific keys onto the object // second arg is "start" key: initToken("comment", i); attribReset(); // the "language" default is "html" anyway so no need to set it console.log( `2137 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.start`}\u001b[${39}m`} = ${ token.start }; ${`\u001b[${33}m${`token.type`}\u001b[${39}m`} = ${token.type}` ); // set "closing" if (str[i] === "-") { (token as CommentToken).closing = true; console.log( `2146 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.closing`}\u001b[${39}m`} = ${ (token as CommentToken).closing }` ); } else if ( matchRightIncl(str, i, ["<![endif]-->"], { i: true, trimBeforeMatching: true, maxMismatches: 2, }) ) { (token as CommentToken).closing = true; (token as CommentToken).kind = "only"; console.log( `2160 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.closing`}\u001b[${39}m`} = ${ (token as CommentToken).closing }; ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ (token as CommentToken).kind }` ); } if (withinStyle) { withinStyle = false; console.log( `2171 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`withinStyle`}\u001b[${39}m`} = false` ); } } else if ( !withinScript && startsCssComment(str, i, token, layers, withinStyle) ) { // // // // CSS COMMENT STARTING // // // console.log(`2185 CSS block comment opening`); if (token.start != null) { console.log(`2188 call dumpCurrentToken()`); dumpCurrentToken(token, i); } // add other token-specific keys onto the object // second arg is "start" key: initToken("comment", i); attribReset(); (token as CommentToken).language = "css"; console.log( `2199 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.language`}\u001b[${39}m`} = ${ (token as CommentToken).language }` ); (token as CommentToken).kind = str[i] === "/" && str[i + 1] === "/" ? "line" : "block"; token.value = str.slice(i, i + 2); token.end = i + 2; (token as CommentToken).closing = str[i] === "*" && str[i + 1] === "/"; withinStyleComment = true; if ((token as CommentToken).closing) { withinStyleComment = false; } doNothing = i + 2; console.log( `2217 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); console.log( `2221 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}; ${`\u001b[${33}m${`withinStyleComment`}\u001b[${39}m`} = ${JSON.stringify( withinStyleComment, null, 4 )}` ); } else if ( !withinScript && // if we encounter two consecutive characters of guessed lump ((typeof lastEspLayerObjIdx === "number" && layers[lastEspLayerObjIdx] && layers[lastEspLayerObjIdx].type === "esp" && (layers[lastEspLayerObjIdx] as LayerEsp).openingLump && (layers[lastEspLayerObjIdx] as LayerEsp).guessedClosingLump && (layers[lastEspLayerObjIdx] as LayerEsp).guessedClosingLump.length > 1 && // current character is among guessed lump's characters (layers[lastEspLayerObjIdx] as LayerEsp).guessedClosingLump.includes( str[i] ) && // ...and the following character too... (layers[lastEspLayerObjIdx] as LayerEsp).guessedClosingLump.includes( str[i + 1] ) && // since we "jump" over layers, that is, passed quotes // and what not, we have to ensure we don't skip // legit cases like: // ${"${name}${name}${name}${name}"} // ^ // here // Responsys expression can be within a value! we have // to respect those quotes! // // these are erroneous quotes representing layers // which we do ignore (JSP example): // // <%@taglib prefix="t' tagdir='/WEB-INF/tags"%> // ^ ^ ^ ^ // errors !( // we excluse the same case, // ${"${name}${name}${name}${name}"} // ^ // false ending // we ensure that quote doesn't follow the esp layer // "lastEspLayerObjIdx" and there's counterpart of it // on the right, and there's ESP char on the right of it // next layer after esp's follows ( layers[lastEspLayerObjIdx + 1] && // and it's quote `'"`.includes((layers[lastEspLayerObjIdx + 1] as any).value) && // matching quote on the right has ESP character following // it exists (>-1) str.indexOf((layers[lastEspLayerObjIdx + 1] as any).value, i) > 0 && ( layers[lastEspLayerObjIdx] as LayerEsp ).guessedClosingLump.includes( str[ right( str, str.indexOf( (layers[lastEspLayerObjIdx + 1] as any).value, i ) ) as number ] ) ) )) || // hard check (startsEsp(str, i, token, layers, withinStyle) && // ensure we're not inside quotes, so it's not an expression within a value // ${"${name}${name}${name}${name}"} // ^ // we could be here - notice quotes wrapping all around // (!lastLayerIs("simple") || ![`'`, `"`].includes( (layers[~-layers.length] as LayerSimple).value ) || // or we're within an attribute (so quotes are HTML tag's not esp tag's) (attrib && attrib.attribStarts && !attrib.attribEnds)))) ) { // // // // ESP TAG STARTING // // // console.log( `2319 ${`\u001b[${32}m${`ESP heads or tails start here`}\u001b[${39}m`}` ); // in case of inline CSS styles, check, maybe we need to end any // inline CSS rule tokens if ( attrib && attrib.attribValue.length && !attrib.attribValue[~-attrib.attribValue.length].end ) { attrib.attribValue[~-attrib.attribValue.length].end = i; attrib.attribValue[~-attrib.attribValue.length].value = str.slice( attrib.attribValue[~-attrib.attribValue.length].start, i ); console.log( `2335 ${`\u001b[${32}m${`PATCH`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValue[~-attrib.attribValue.length]`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValue[~-attrib.attribValue.length], null, 4 )}` ); } // // // // FIRST, extract the tag opening and guess the closing judging from it const wholeEspTagLumpOnTheRight = getWholeEspTagLumpOnTheRight( str, i, layers ); console.log( `2353 ██ ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`wholeEspTagLumpOnTheRight`}\u001b[${39}m`} = ${wholeEspTagLumpOnTheRight}` ); console.log( `2356 FIY, ${`\u001b[${33}m${`layers`}\u001b[${39}m`} = ${JSON.stringify( layers, null, 4 )}` ); console.log( `2363 FIY, ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); // lump can't end with attribute's ending, that is, something like: // <frameset cols="**"> // that's a false positive if (!espLumpBlacklist.includes(wholeEspTagLumpOnTheRight)) { console.log(`2374`); // check the "layers" records - maybe it's a closing part of a set? let lengthOfClosingEspChunk; let disposableVar = { char: "", idx: 0, }; if ( layers.length && // // if layer match result is truthy, we take it, otherwise, move on // but don't calculate twice! // eslint-disable-next-line no-cond-assign (lengthOfClosingEspChunk = matchLayerLast( wholeEspTagLumpOnTheRight, layers )) ) { console.log( `2395 closing part of a set ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} against the last layer` ); console.log( `2398 ${`\u001b[${33}m${`lengthOfClosingEspChunk`}\u001b[${39}m`} = ${JSON.stringify( lengthOfClosingEspChunk, null, 4 )}` ); // if this was closing of a standalone esp tag, terminate it and ping // it to the cb() if (token.type === "esp") { if (!token.end) { token.end = i + lengthOfClosingEspChunk; token.value = str.slice( token.start as number, token.end as number ); token.tail = str.slice(i, i + lengthOfClosingEspChunk); token.tailStartsAt = i; token.tailEndsAt = token.end; // correction for XML-like templating tags, closing can // have a slash, <c:set zzz/> // ^ if (str[i] === ">" && str[leftVal as number] === "/") { token.tailStartsAt = leftVal; console.log( `2424 closing slash correction, ${`\u001b[${32}m${`SET`}\u001b[${39}m`} token.tailStartsAt=${ token.tailStartsAt }` ); token.tail = str.slice(token.tailStartsAt as number, i + 1); } console.log( `2432 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${32}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); } // activate doNothing until the end of tails because otherwise, // mid-tail characters will initiate new tail start clauses // and we'll have overlap/false result doNothing = token.tailEndsAt as number; console.log( `2445 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); console.log( `2449 FIY, ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}; ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}; ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )};` ); // it depends will we ping it as a standalone token or will we // nest inside the parent tag among attributes if (parentTokenToBackup) { console.log( `2467 ${`\u001b[${32}m${`NEST INSIDE THE STASHED TAG`}\u001b[${39}m`}` ); // push token to parent, to be among its attributes // 1. ensure key "attribs" exist (thinking about comment tokens etc) if (!Array.isArray(parentTokenToBackup.attribs)) { parentTokenToBackup.attribs = []; } // 2. push somewhere if (property && property.start) { // push to attribValue console.log( `2480 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} token to be inside ${`\u001b[${33}m${`property.value`}\u001b[${39}m`}` ); if (!Array.isArray(property.value)) { property.value = []; } property.value.push({ ...token } as any); console.log( `2488 ${`\u001b[${32}m${`NOW`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); } else if (attribToBackup) { // restore attrib = attribToBackup; console.log( `2498 ${`\u001b[${35}m${`RESTORE`}\u001b[${39}m`} attrib from stashed, now = ${JSON.stringify( attrib, null, 4 )}` ); // push to attribValue console.log( `2507 PUSH token to be inside ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`}` ); attrib.attribValue.push({ ...token } as any); } else if ( attrib && attrib.attribStarts && Array.isArray(attrib.attribValue) ) { // push to attrib value console.log(`2516 PUSH token to attrib`); attrib.attribValue.push({ ...token } as any); console.log( `2519 now ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValue, null, 4 )}` ); } else { // push to attribs console.log(`2527 PUSH token to be among attribs`); parentTokenToBackup.attribs.push({ ...token } as any); } // 3. parentTokenToBackup becomes token token = clone(parentTokenToBackup); console.log( `2534 ${`\u001b[${32}m${`RESTORE`}\u001b[${39}m`} ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); // 4. resets parentTokenToBackup = undefined; attribToBackup = undefined; // 5. pop layers, remove the opening ESP tag record console.log(`2546 POP layers`); layers.pop(); // 6. finally, continue, bypassing the rest of the code in this loop console.log( `2551 ${`\u001b[${31}m${`CONTINUE`}\u001b[${39}m`}` ); console.timeEnd( `\u001b[${90}m${`loop iteration`}\u001b[${39}m` ); continue; } else { console.log( `2559 ${`\u001b[${32}m${`PING AS STANDALONE`}\u001b[${39}m`}` ); dumpCurrentToken(token, i); } console.log(`2564 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); } // pop the recorded layers, at this moment record of ESP chunk // will be lost: layers.pop(); console.log(`2571 ${`\u001b[${32}m${`POP`}\u001b[${39}m`} layers`); } else if ( layers.length && // eslint-disable-next-line no-cond-assign (lengthOfClosingEspChunk = matchLayerLast( wholeEspTagLumpOnTheRight, layers, true )) ) { console.log( `2582 closing part of a set ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} against first layer` ); console.log( `2585 wipe all layers, there were strange unclosed characters` ); console.log( `2588 ${`\u001b[${33}m${`lengthOfClosingEspChunk`}\u001b[${39}m`} = ${JSON.stringify( lengthOfClosingEspChunk, null, 4 )}` ); // if this was closing of a standalone esp tag, terminate it and ping // it to the cb() if (token.type === "esp") { if (!token.end) { token.end = i + (lengthOfClosingEspChunk || 0); token.value = str.slice( token.start as number, token.end as number ); console.log( `2605 ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )} before pinging` ); } if (!token.tailStartsAt) { token.tailStartsAt = i; } if (!token.tailEndsAt && lengthOfClosingEspChunk) { token.tailEndsAt = token.tailStartsAt + lengthOfClosingEspChunk; token.tail = str.slice(i, i + lengthOfClosingEspChunk); } dumpCurrentToken(token, i); console.log(`2621 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); } // pop the recorded layers, at this moment record of ESP chunk // will be lost: layers.length = 0; console.log(`2628 ${`\u001b[${32}m${`WIPE`}\u001b[${39}m`} layers`); } else if ( // insurance against stray tails inside attributes: // <a b="{ x %}"> // ^ ^ // | | // | we're here // | // | // this opening bracket is incomplete // and therefore not recognised as an opening // // // if ESP character lump we extracted, for example, // %} contains a closing character, in this case, a } attrib && attrib.attribValue && attrib.attribValue.length && attrib.attribValue[~-attrib.attribValue.length].start && Array.from( str.slice( attrib.attribValue[~-attrib.attribValue.length].start, i ) ).some( (char, idx) => wholeEspTagLumpOnTheRight.includes(flipEspTag(char)) && // ensure it's not a false alarm, "notVeryEspChars" // bunch, for example, % or $ can be legit characters // // either it's from "veryEspChars" list so // it can be anywhere, not necessarily at the // beginning, for example, broken mailchimp: // <a b="some text | x *|"> // ^ // this is // (veryEspChars.includes(char) || // or that character must be the first character // of the attribute's value, for example: // <a b="% x %}"> // ^ // this // // because imagine false positive, legit %: // <a b="Real 5% discount! x %}"> // ^ // definitely not a part of broken opening {% // // it's zero'th index: !idx) && (disposableVar = { char, idx }) ) && // we're inside attribute token.type === "tag" && attrib && attrib.attribValueStartsAt && !attrib.attribValueEndsAt && // last attribute's value element is text-type // imagine, the { x from <a b="{ x %}"> would be // such unrecognised text: attrib.attribValue[~-attrib.attribValue.length] && (attrib.attribValue[~-attrib.attribValue.length] as any).type === "text" ) { console.log( `2694 ${`\u001b[${31}m${`██`}\u001b[${39}m`} seems like a stray lump` ); console.log( `2697 FIY, ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); console.log( `2704 FIY, ${`\u001b[${33}m${`disposableVar`}\u001b[${39}m`} = ${JSON.stringify( disposableVar, null, 4 )}` ); console.log( `2712 let's convert last attrib.attribValue[] object into ESP-type` ); // token does contain ESP tags, so it's not pure HTML token.pureHTML = false; const lastAttrValueObj = attrib.attribValue[~-attrib.attribValue.length]; // getNewToken() just creates a new token according // the latest (DRY) reference, it doesn't reset // the "token" unlike initToken() const newTokenToPutInstead: EspToken = getNewToken( "esp", lastAttrValueObj.start ) as EspToken; // for remaining values, we need to consider, is there // text in front: // // <a b="{ x %}"> // vs. // <a b="something { x %}"> if (!disposableVar.idx) { console.log( `2738 ${`\u001b[${33}m${`ESP tag is this whole text token`}\u001b[${39}m`}` ); newTokenToPutInstead.head = disposableVar.char; newTokenToPutInstead.headStartsAt = lastAttrValueObj.start; newTokenToPutInstead.headEndsAt = newTokenToPutInstead.headStartsAt + 1; newTokenToPutInstead.tailStartsAt = i; newTokenToPutInstead.tailEndsAt = i + wholeEspTagLumpOnTheRight.length; newTokenToPutInstead.tail = wholeEspTagLumpOnTheRight; (attrib.attribValue as any[])[~-attrib.attribValue.length] = newTokenToPutInstead; } else { console.log( `2753 ${`\u001b[${33}m${`we need to extract frontal part of text token`}\u001b[${39}m`}` ); } } else { console.log( `2758 closing part of a set ${`\u001b[${31}m${`NOT MATCHED`}\u001b[${39}m`} - means it's a new opening` ); // If we've got an unclosed heads and here new heads are starting, // pop the last heads in layers - they will never be matched anyway. // Let parser/linter deal with it if (lastLayerIs("esp")) { layers.pop(); console.log( `2767 ${`\u001b[${31}m${`POP layers - it was heads without tails`}\u001b[${39}m`}` ); } // if we're within a tag attribute, push the last esp token there if (attribToBackup) { if (!Array.isArray(attribToBackup.attribValue)) { attribToBackup.attribValue = []; } console.log(`2776 push token to attribValue`); attribToBackup.attribValue.push(token as any); } console.log(`2780 push new layer`); layers.push({ type: "esp", openingLump: wholeEspTagLumpOnTheRight, guessedClosingLump: flipEspTag(wholeEspTagLumpOnTheRight), position: i, }); console.log( `2788 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( { type: "esp", openingLump: wholeEspTagLumpOnTheRight, guessedClosingLump: flipEspTag(wholeEspTagLumpOnTheRight), position: i, }, null, 4 )}` ); console.log( `2800 ${`\u001b[${33}m${`layers`}\u001b[${39}m`} = ${JSON.stringify( layers, null, 4 )}` ); // also, if it's a standalone ESP token, terminate the previous token // and start recording a new-one if (token.start !== null) { // it means token has already being recorded, we need to tackle it - // the new, ESP token is incoming! // we nest ESP tokens inside "tag" type attributes if (token.type === "tag") { console.log( `2817 ${`\u001b[${36}m${`██`}\u001b[${39}m`} ESP tag-inside-tag clauses` ); // maybe it's an ESP token within an inline CSS style? // <div style="width: {{ w }}"> console.log( `2823 FIY, ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); if (attrib && attrib.attribName === "style") { console.log( `2832 ${`\u001b[${32}m${`ESP inside inline CSS style rule's value`}\u001b[${39}m`}` ); if ( property.start && !property.end && property.propertyEnds && !property.valueStarts ) { property.valueStarts = i; console.log( `2843 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.valueStarts`}\u001b[${39}m`} = ${JSON.stringify( property.valueStarts, null, 4 )}` ); } else if (property.start) { // imagine: // <div style="width: 100{{ w }}"> // ^ // we're here // or // <td style="a: b; {% if x %}c: d{% endif %} e: f;">x</td> // ^ // we're here if (!Array.isArray(property.value)) { // terminate the property console.log( `2865 ███████████████████████████████████████ FIY, ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}; ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}; ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); // complete the property if (property.propertyStarts && !property.propertyEnds) { console.log(`2882`); property.propertyEnds = (leftVal as number) + 1; property.property = str.slice( property.propertyStarts, i ); } else if (property.valueStarts && !property.valueEnds) { console.log(`2889`); property.valueEnds = (leftVal as number) + 1; property.value = str.slice( property.valueStarts, property.valueEnds ); } if (property.start && !property.end) { property.end = (leftVal as number) + 1; } console.log( `2902 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); if (attrib && Array.isArray(attrib.attribValue)) { attrib.attribValue.push(clone(property)); console.log( `2912 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} property into ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`}` ); // if there was trailing whitespace, like for example: // <td style="a: b;\n {% if x %}c: d {% endif %}\ne: f;"> // ^ // here // // then create the missing text token to reflect this gap if (property.end !== i) { console.log( `2923 PATCH NEEDED ███████████████████████████████████████` ); const newTextToken = getNewToken( "text", (leftVal as number) + 1 ) as TextToken; newTextToken.end = i; newTextToken.value = str.slice( (leftVal as number) + 1, i ); console.log( `2935 ${`\u001b[${32}m${`SET`}\u001b[${39}m`}${`\u001b[${33}m${`newTextToken`}\u001b[${39}m`} = ${JSON.stringify( newTextToken, null, 4 )}` ); attrib.attribValue.push(clone(newTextToken)); } propertyReset(); console.log( `2946 ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} property` ); } } } } else { // usual inner-tag ESP tokens // <a b="{% if something %}"> // instead of dumping the tag token and starting a new-one, // save the parent token, then nest all ESP tags among attributes if ( token.tagNameStartsAt && (!token.tagName || !token.tagNameEndsAt) ) { token.tagNameEndsAt = i; token.tagName = str.slice(token.tagNameStartsAt, i); token.recognised = isTagNameRecognised(token.tagName); console.log( `2965 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.tagNameEndsAt`}\u001b[${39}m`} = ${ token.tagNameEndsAt }; ${`\u001b[${33}m${`token.tagName`}\u001b[${39}m`} = ${ token.tagName }` ); } if (attrib.attribStarts && !attrib.attribEnds) { attribToBackup = clone(attrib); console.log( `2976 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attribToBackup`}\u001b[${39}m`} = ${JSON.stringify( attribToBackup, null, 4 )}` ); } } parentTokenToBackup = clone(token); console.log( `2987 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`parentTokenToBackup`}\u001b[${39}m`} = ${JSON.stringify( parentTokenToBackup, null, 4 )}` ); } else if (token.type === "text") { // case like: // <div style="x: a{{ b }}c{{ d }}e;"> // ^ // we're here token.end = i; token.value = str.slice(token.start, i); console.log( `3002 COMPLETE ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); if (Array.isArray(property.value)) { property.value.push(token); console.log( `3012 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} to ${`\u001b[${33}m${`property`}\u001b[${39}m`} now: ${JSON.stringify( property, null, 4 )}` ); } else { console.log(`3019 dump the token`); dumpCurrentToken(token, i); } } else if (!attribToBackup) { console.log( `3024 ${`\u001b[${36}m${`██`}\u001b[${39}m`} standalone ESP tag - call the dump` ); dumpCurrentToken(token, i); } else if ( attribToBackup && Array.isArray(attribToBackup.attribValue) && attribToBackup.attribValue.length && ( attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ] as any ).type === "esp" && !attribToBackup.attribValue[~-attribToBackup.attribValue.length] .end ) { console.log( `3040 complete the unclosed token in attribToBackup` ); attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ].end = i; attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ].value = str.slice( attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ].start, i ); console.log( `3054 ██ patched ${`\u001b[${33}m${`attribToBackup`}\u001b[${39}m`} = ${JSON.stringify( attribToBackup, null, 4 )}` ); } } // now, either way, if parent tag was stashed in "parentTokenToBackup" // or if this is a new ESP token and there's nothing to nest, // let's initiate it: initToken("esp", i); // attribReset(); // ^^^ DON'T RESET attrib - because we nest ESP tags within attrib.value console.log( `3071 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.start`}\u001b[${39}m`} = ${ token.start }; ${`\u001b[${33}m${`token.type`}\u001b[${39}m`} = ${token.type}` ); (token as EspToken).head = wholeEspTagLumpOnTheRight; (token as EspToken).headStartsAt = i; (token as EspToken).headEndsAt = i + wholeEspTagLumpOnTheRight.length; // toggle parentTokenToBackup.pureHTML if (parentTokenToBackup && parentTokenToBackup.pureHTML) { parentTokenToBackup.pureHTML = false; console.log( `3084 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`parentTokenToBackup.pureHTML`}\u001b[${39}m`} = ${JSON.stringify( parentTokenToBackup.pureHTML, null, 4 )}` ); } // if text token has been initiated, imagine: // "attribValue": [ // { // "type": "text", // "start": 6, <-------- after the initiation of this, we started ESP token at 6 // "end": null, // "value": null // }, // { // "type": "esp", // "start": 6, <-------- same start on real ESP token // ... // ], if ( attribToBackup && Array.isArray(attribToBackup.attribValue) && attribToBackup.attribValue.length ) { console.log(`3110 *`); if ( attribToBackup.attribValue[~-attribToBackup.attribValue.length] .start === token.start ) { console.log( `3116 ${`\u001b[${31}m${`TEXT TOKEN INITIATED WHERE ESP WILL BE`}\u001b[${39}m`}` ); // erase it from stash attribToBackup.attribValue.pop(); console.log( `3121 ${`\u001b[${31}m${`POP`}\u001b[${39}m`} attribToBackup.attribValue, now attribToBackup.attribValue: ${JSON.stringify( attribToBackup.attribValue, null, 4 )}` ); } else if ( // if the "text" type object is the last in "attribValue" and // it's not closed, let's close it and calculate its value: ( attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ] as any ).type === "text" && !attribToBackup.attribValue[~-attribToBackup.attribValue.length] .end ) { console.log(`3138`); attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ].end = i; attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ].value = str.slice( attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ].start, i ); console.log( `3152 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attribToBackup.attribValue[ ${~-attribToBackup.attribValue.length} ]`}\u001b[${39}m`} = ${JSON.stringify( attribToBackup.attribValue[ ~-attribToBackup.attribValue.length ], null, 4 )}` ); } } } // do nothing for the second and following characters from the lump doNothing = i + (lengthOfClosingEspChunk || wholeEspTagLumpOnTheRight.length); console.log( `3170 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); } console.log(`3174 end of ESP head/tail clauses reached`); } else if ( !withinScript && withinStyle && !withinStyleComment && str[i] && str[i].trim() && // insurance against rogue extra closing curlies: // .a{x}} // don't start new rule at closing curlie! !`{}`.includes(str[i]) && // if at rule starts right after <style>, if we're on "@" // for example: // <style>@media a {.b{c}}</style> // first the <style> tag token will be pushed and then tag object // reset and then, still at "@" (!token.type || // or, there was whitespace and we started recording a text token // <style> @media a {.b{c}}</style> // ^ // we're here - look at the whitespace on the left. // ["text"].includes(token.type)) ) { // Text token inside styles can be either whitespace chunk // or rogue characters. In either case, inside styles, when // "withinStyle" is on, non-whitespace character terminates // this text token and "rule" token starts console.log( `3203 ██ ${`\u001b[${32}m${`at/rule starts`}\u001b[${39}m`}` ); if (token.type) { console.log(`3207 call dumpCurrentToken()`); dumpCurrentToken(token, i); } initToken(str[i] === "@" ? "at" : "rule", i); attribReset(); (token as RuleToken).left = lastNonWhitespaceCharAt; console.log( `3215 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.left`}\u001b[${39}m`} = ${JSON.stringify( (token as RuleToken).left, null, 4 )}` ); (token as RuleToken).nested = layers.some((o) => o.type === "at"); console.log( `3223 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.nested`}\u001b[${39}m`} = ${JSON.stringify( (token as RuleToken).nested, null, 4 )}` ); } else if (!token.type) { console.log(`3230 BLANK token, so initiate text token`); initToken("text", i); attribReset(); console.log( `3234 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); if (withinScript && str.indexOf("</script>", i)) { console.log( `3243 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); doNothing = str.indexOf("</script>", i); } else { doNothing = i; console.log( `3253 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } } } console.timeEnd(`main-sorting-checks`); let R1; let R2; if ( !doNothing && str[i] && (property.start || str[i] === "!") && (!layers.length || layers[~-layers.length].type !== "esp") && (token.type !== "text" || Array.isArray(property.value)) ) { const idxRightIncl = right(str, i - 1) as number; R1 = `;<>`.includes(str[idxRightIncl]) || // or it's a quote (`'"`.includes(str[idxRightIncl]) && // but then it has to be a matching counterpart // either there are no layers (!layers || // or there are but they're empty !layers.length || // or array is not empty but its last element is !layers[~-layers.length] || // or it's neither empty not falsy but doesn't have "value" key !(layers[~-layers.length] as any).value || // or it is a plain object with a value key and that layer // means opening quotes has been opened and this quote at this // index (or if it's whitespace, first index to the right) is a // closing counterpart for that quote in "layers" (layers[~-layers.length] as any).value === str[idxRightIncl])); R2 = matchRightIncl(str, i, ["!important"], { i: true, trimBeforeMatching: true, maxMismatches: 2, }); console.log( `3298 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${ R1 ? 32 : 31 }m${`R1`}\u001b[${39}m`} = ${R1}; ${`\u001b[${ R2 ? 32 : 31 }m${`R2`}\u001b[${39}m`} = ${R2}` ); } // catch the end of a css property (with or without !important) // ------------------------------------------------------------------------- /* istanbul ignore else */ if ( !doNothing && property && ((property.semi && property.semi < i && property.semi < i) || (((property.valueStarts && !property.valueEnds && str[rightVal as number] !== "!" && // either non-whitespace character doesn't exist on the right (!rightVal || // or at that character !important does not start R1)) || (property.importantStarts && !property.importantEnds)) && (!property.valueEnds || str[rightVal as number] !== ";") && // either end of string was reached (!str[i] || // or it's a whitespace !str[i].trim() || // or it's a semicolon after a value (!property.valueEnds && str[i] === ";") || // or we reached the end of the attribute attrEndsAt( i, Array.isArray(property.value) && property.value[~-property.value.length].type === "esp" )))) ) { console.log(`3335 ${`\u001b[${32}m${`css property ends`}\u001b[${39}m`}`); /* istanbul ignore else */ if (property.importantStarts && !property.importantEnds) { property.importantEnds = (left(str, i) as number) + 1; property.important = str.slice( property.importantStarts, property.importantEnds ); console.log( `3345 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.importantEnds`}\u001b[${39}m`} = ${JSON.stringify( property.importantEnds, null, 4 )}; ${`\u001b[${33}m${`property.important`}\u001b[${39}m`} = ${JSON.stringify( property.important, null, 4 )}` ); } /* istanbul ignore else */ if (property.valueStarts && !property.valueEnds) { property.valueEnds = (left(str, i) as number) + 1; if (!Array.isArray(property.value)) { property.value = str.slice(property.valueStarts, property.valueEnds); console.log( `3363 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.valueEnds`}\u001b[${39}m`} = ${JSON.stringify( property.valueEnds, null, 4 )}; ${`\u001b[${33}m${`property.value`}\u001b[${39}m`} = ${JSON.stringify( property.value, null, 4 )}` ); } } /* istanbul ignore else */ if (str[i] === ";") { property.semi = i; console.log( `3380 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.semi`}\u001b[${39}m`} = ${JSON.stringify( property.semi, null, 4 )}` ); property.end = i + 1; console.log( `3388 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); } else if (str[rightVal as number] === ";") { property.semi = rightVal; property.end = (property.semi as number) + 1; console.log( `3398 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.semi`}\u001b[${39}m`} = ${JSON.stringify( property.semi, null, 4 )}; ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); doNothing = property.end; console.log( `3411 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } /* istanbul ignore else */ if (!property.end) { property.end = (left(str, i) as number) + 1; console.log( `3423 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); } /* istanbul ignore else */ if (token.type === "text" && token.start && !token.end) { token.end = i; token.value = str.slice(token.start, i); if (Array.isArray(property.value)) { property.value.push(token); console.log( `3438 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} to ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); } // restore real token if (parentTokenToBackup) { token = clone(parentTokenToBackup) as TagToken; console.log( `3450 ${`\u001b[${32}m${`RESTORE`}\u001b[${39}m`} ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); } } // we might need to extract inner whitespace as // a standalone text token: // <style>.a{ padding: 1px 2px 3px 4px } // ^ // we're here let newTextToken; if ( property.valueEnds !== i && !property.important && !str[i - 1].trim() ) { newTextToken = getNewToken("text", property.valueEnds) as TextToken; newTextToken.end = i; newTextToken.value = str.slice(property.valueEnds as number, i); console.log( `3475 ${`\u001b[${32}m${`SET`}\u001b[${39}m`}${`\u001b[${33}m${`newTextToken`}\u001b[${39}m`} = ${JSON.stringify( newTextToken, null, 4 )}` ); } pushProperty(property); console.log( `3485 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( property, null, 4 )}, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`}` ); propertyReset(); if (newTextToken) { console.log( `3494 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( newTextToken, null, 4 )}` ); pushProperty(newTextToken); } if (!doNothing && (!str[i] || str[i].trim()) && str[i] === ";") { doNothing = i; console.log( `3506 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } } // catch the end of a css property's value // ------------------------------------------------------------------------- /* istanbul ignore else */ if ( !doNothing && // token.type === "rule" && property && property.start && property.valueStarts && !property.valueEnds ) { console.log( `3527 ${`\u001b[${90}m${`css property's value ending clauses`}\u001b[${39}m`}` ); if ( // either end was reached !str[i] || // or terminating characters (semi etc) follow R1 || // or !important starts R2 || str[right(str, i - 1) as number] === "!" || // normal head css styles: (`;}`.includes(str[i]) && (!attrib || !attrib.attribName || attrib.attribName !== "style")) || // inline css styles within html (`;'"`.includes(str[i]) && attrib && attrib.attribName === "style" && // it's real quote, not rogue double-wrapping around the value ifQuoteThenAttrClosingQuote(i)) || // it's a whitespace chunk with linebreaks (rightVal && !str[i].trim() && (str.slice(i, rightVal).includes("\n") || str.slice(i, rightVal).includes("\r"))) ) { console.log( `3553 FIY, ${`\u001b[${33}m${`lastNonWhitespaceCharAt`}\u001b[${39}m`} = ${JSON.stringify( lastNonWhitespaceCharAt, null, 4 )}` ); if ( lastNonWhitespaceCharAt && // it's not a quote (!`'"`.includes(str[i]) || // there's nothing on the right !rightVal || // or it is a quote, but there's no quote on the right !`'";`.includes(str[rightVal])) ) { property.valueEnds = lastNonWhitespaceCharAt + 1; console.log( `3571 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.valueEnds`}\u001b[${39}m`} = ${ property.valueEnds }` ); // if it's a text token, end it, imagine // <div style="width: {{ w }}px"> // ^ // we're here if (token.type === "text") { token.end = i; token.value = str.slice(token.start, i); console.log( `3584 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); if (Array.isArray(property.value)) { property.value.push(token); console.log( `3592 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} to ${`\u001b[${33}m${`property`}\u001b[${39}m`}, now: ${JSON.stringify( property, null, 4 )}` ); } // restore parent token token = clone(parentTokenToBackup) as TagToken; } if (!Array.isArray(property.value)) { property.value = str.slice( property.valueStarts, lastNonWhitespaceCharAt + 1 ); console.log( `3610 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.value`}\u001b[${39}m`} = ${ property.value }` ); } } if (str[i] === ";") { property.semi = i; console.log( `3619 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.semi`}\u001b[${39}m`} = ${JSON.stringify( property.semi, null, 4 )}` ); } else if ( // it's whitespace str[i] && !str[i].trim() && // semicolon follows str[rightVal as number] === ";" ) { property.semi = rightVal; console.log( `3634 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.semi`}\u001b[${39}m`} = ${JSON.stringify( property.semi, null, 4 )}` ); } if ( // if semicolon has been spotted... property.semi ) { // set the ending too property.end = property.semi + 1; // happy path, clean code has "end" at semi console.log( `3649 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); } if ( // if there's no semicolon in the view !property.semi && // and semi is not coming next !R1 && // and !important is not following !R2 && str[right(str, i - 1) as number] !== "!" && // and property hasn't ended !property.end ) { // we need to end it because this is it property.end = i; console.log( `3671 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); } console.log( `3680 ${`\u001b[${32}m${`NOW`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); if (property.end) { // push and init and patch up to resume if (property.end > i) { // if ending is in the future, skip everything up to it doNothing = property.end; console.log( `3693 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } pushProperty(property); propertyReset(); console.log( `3703 push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); } } else if ( str[i] === ":" && property && property.colon && property.colon < i && lastNonWhitespaceCharAt && property.colon + 1 < lastNonWhitespaceCharAt ) { // .a{b:c d:e;} // ^ // we're here // console.log(`3718 ${`\u001b[${31}m${`MISSING SEMICOL`}\u001b[${39}m`}`); console.log( `3720 FIY, ${`\u001b[${33}m${`lastNonWhitespaceCharAt`}\u001b[${39}m`} = ${JSON.stringify( lastNonWhitespaceCharAt, null, 4 )}` ); // semicolon is missing... // traverse backwards from "lastNonWhitespaceCharAt", just in case // there's space before colon, .a{b:c d :e;} // ^ // we're here // // we're looking to pinpoint where one rule ends and another starts. console.log( `3736 ██ "${str.slice( right(str, property.colon) as any, lastNonWhitespaceCharAt + 1 )}"` ); let split: string[] = []; if (right(str, property.colon)) { split = str .slice( right(str, property.colon) as number, lastNonWhitespaceCharAt + 1 ) .split(/\s+/); console.log( `${`\u001b[${33}m${`split`}\u001b[${39}m`} = ${JSON.stringify( split, null, 4 )}` ); } if (split.length === 2) { // it's missing semicol, like: .a{b:c d:e;} // ^ ^ // |gap| we split // property.valueEnds = property.valueStarts + split[0].length; property.value = str.slice(property.valueStarts, property.valueEnds); property.end = property.valueEnds; console.log( `3767 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); // push and init and patch up to resume console.log( `3776 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); pushProperty(property); // backup the values before wiping the property: const whitespaceStarts = property.end; const newPropertyStarts = lastNonWhitespaceCharAt + 1 - split[1].length; propertyReset(); console.log( `3789 push, then ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); pushProperty({ type: "text", start: whitespaceStarts, end: newPropertyStarts, value: str.slice(whitespaceStarts, newPropertyStarts), } as any); console.log( `3799 PUSH to ${`\u001b[${33}m${`token.properties`}\u001b[${39}m`}, now = ${JSON.stringify( (token as any).properties, null, 4 )}` ); property.start = newPropertyStarts; property.propertyStarts = newPropertyStarts; console.log( `3809 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); } } else if (str[i] === "/" && str[rightVal as number] === "*") { // comment starts // <a style="color: red/* zzz */"> // ^ // we're here /* istanbul ignore else */ if (property.valueStarts && !property.valueEnds) { property.valueEnds = i; property.value = str.slice(property.valueStarts, i); } /* istanbul ignore else */ if (!property.end) { property.end = i; } console.log( `3834 ${`\u001b[${32}m${`NOW`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); // push and init and patch up to resume pushProperty(property); propertyReset(); console.log( `3845 push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); } } // catch the css property's semicolon // ------------------------------------------------------------------------- if ( !doNothing && property && property.start && !property.end && str[i] === ";" ) { property.semi = i; property.end = i + 1; console.log( `3862 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.semi`}\u001b[${39}m`} = ${JSON.stringify( property.semi, null, 4 )}; ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); if (!property.propertyEnds) { property.propertyEnds = i; console.log( `3875 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.propertyEnds`}\u001b[${39}m`} = ${JSON.stringify( property.propertyEnds, null, 4 )}` ); } if ( property.propertyStarts && property.propertyEnds && !property.property ) { property.property = str.slice( property.propertyStarts, property.propertyEnds ); console.log( `3892 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.property`}\u001b[${39}m`} = ${JSON.stringify( property.property, null, 4 )}` ); } pushProperty(property); console.log( `3902 push ${JSON.stringify( property, null, 4 )}, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`}` ); propertyReset(); doNothing = i; console.log( `3912 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } // catch the end of css property's !important // ------------------------------------------------------------------------- /* istanbul ignore else */ if ( property && property.importantStarts && !property.importantEnds && str[i] && !str[i].trim() ) { property.importantEnds = i; property.important = str.slice(property.importantStarts, i); console.log( `3933 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.importantEnds`}\u001b[${39}m`} = ${ property.importantEnds }; ${`\u001b[${33}m${`property.important`}\u001b[${39}m`} = ${JSON.stringify( property.important, null, 0 )}` ); } // catch the start of css property's !important // ------------------------------------------------------------------------- /* istanbul ignore else */ if ( !doNothing && property && property.valueEnds && !property.importantStarts && // it's an exclamation mark (str[i] === "!" || // considering missing excl. mark cases, more strict req.: (isLatinLetter(str[i]) && str.slice(i).match(importantStartsRegexp))) ) { console.log( `3957 ${`\u001b[${32}m${`css property's !important starts`}\u001b[${39}m`}` ); property.importantStarts = i; console.log( `3961 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.importantStarts`}\u001b[${39}m`} = ${JSON.stringify( property.importantStarts, null, 4 )}` ); // correction for cases like: // <style>.a{color:red 1important} // ^ // we're here, that "1" needs to be included as part of important if ( // it's non-whitespace char in front (str[i - 1] && str[i - 1].trim() && // and before that it's whitespace str[i - 2] && !str[i - 2].trim()) || // there's a "1" in front (str[i - 1] === "1" && // and it's not numeric character before it // padding: 101important // ^ // unlikely it's a mistyped ! str[i - 2] && !/\d/.test(str[i - 2])) ) { // merge that character into !important property.valueEnds = (left(str, i - 1) as number) + 1; property.value = str.slice( property.valueStarts as number, property.valueEnds ); console.log( `3995 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); property.importantStarts--; property.important = str[i - 1] + property.important; } } // catch the start of a css property's value // ------------------------------------------------------------------------- /* istanbul ignore else */ if ( !doNothing && property && property.colon && !property.valueStarts && // can't be within ESP token, // <div style="width: {{ w }}"> // ^ (!layers.length || layers[~-layers.length].type !== "esp") && str[i] && str[i].trim() ) { console.log(`4021`); /* istanbul ignore else */ if ( // stopper character met: `;}'"`.includes(str[i]) && // either it's real closing quote or not a quote ifQuoteThenAttrClosingQuote(i) ) { console.log(`4029 ${`\u001b[${31}m${`broken code!`}\u001b[${39}m`}`); /* istanbul ignore else */ if (str[i] === ";") { property.semi = i; console.log( `4034 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.semi`}\u001b[${39}m`} = ${JSON.stringify( property.semi, null, 4 )}` ); } let temp; // patch missing .end /* istanbul ignore else */ if (!property.end) { property.end = property.semi ? property.semi + 1 : (left(str, i) as number) + 1; console.log( `4051 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); temp = property.end; } // push and init and patch up to resume pushProperty(property); propertyReset(); console.log( `4064 push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); console.log( `4068 FIY, ${`\u001b[${33}m${`temp`}\u001b[${39}m`} = ${JSON.stringify( temp, null, 4 )}` ); // if there was a whitespace gap, submit it as text token /* istanbul ignore else */ if (temp && temp < i) { pushProperty({ type: "text", start: temp, end: i, value: str.slice(temp, i), } as any); } } else if (str[i] === "!") { console.log( `4087 ${`\u001b[${32}m${`css property's !important starts`}\u001b[${39}m`}` ); property.importantStarts = i; console.log( `4091 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.importantStarts`}\u001b[${39}m`} = ${ property.importantStarts }` ); } else { console.log( `4097 ${`\u001b[${32}m${`css property's value starts`}\u001b[${39}m`}` ); property.valueStarts = i; console.log( `4101 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.valueStarts`}\u001b[${39}m`} = ${ property.valueStarts }` ); } } // catch double opening curlies inside a css property if ( !doNothing && str[i] === "{" && str[i + 1] === "{" && property && property.valueStarts && !property.valueEnds && str.indexOf("}}", i) > 0 ) { doNothing = str.indexOf("}}") + 2; console.log( `4120 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } // catch the start of a css chunk // ------------------------------------------------------------------------- if ( !doNothing && token.type === "rule" && str[i] && str[i].trim() && !"{}".includes(str[i]) && !selectorChunkStartedAt && !token.openingCurlyAt ) { if (!",".includes(str[i])) { selectorChunkStartedAt = i; console.log( `4142 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`selectorChunkStartedAt`}\u001b[${39}m`} = ${selectorChunkStartedAt}` ); if (token.selectorsStart === null) { token.selectorsStart = i; console.log( `4148 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.selectorsStart`}\u001b[${39}m`} = ${ token.selectorsStart }` ); } } else { // this contraption is needed to catch commas and assign // correctly broken chunk range, [selectorsStart, selectorsEnd] token.selectorsEnd = i + 1; console.log( `4158 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.selectorsEnd`}\u001b[${39}m`} = ${ token.selectorsEnd }` ); } } // catch the end of a css property's name // ------------------------------------------------------------------------- if ( !doNothing && // token.type === "rule" && property && property.propertyStarts && property.propertyStarts < i && !property.propertyEnds && // end was reached (!str[i] || // or it's whitespace !str[i].trim() || // or // it's not suitable (!attrNameRegexp.test(str[i]) && // and // it's a colon (clean code) // <div style="float:left;">z</div> // ^ // we're here // (str[i] === ":" || // // or // // <div style="float.:left;">z</div> // ^ // include this dot within property name // so that we can catch it later validating prop names // !rightVal || !`:/}`.includes(str[rightVal as number]) || // mind the rogue closings .a{x}} (str[i] === "}" && str[rightVal] === "}"))) || // <style>.a{b!} // ^ str[i] === "!") && // also, regarding the slash, // <div style="//color: red;"> // ^ // don't close here, continue, gather "//color" // (str[i] !== "/" || str[i - 1] !== "/") ) { console.log( `4211 ${`\u001b[${32}m${`css property's name ends`}\u001b[${39}m`}` ); property.propertyEnds = i; property.property = str.slice(property.propertyStarts, i); console.log( `4217 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); if (property.valueStarts) { // it's needed to safeguard against case like: // <style>.a{b:c d:e;}</style> // ^ // imagine we're here - valueStarts is not set! property.end = i; console.log( `4230 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); } // missing colon and onwards: // <style>.b{c}</style> // <style>.b{c;d}</style> if ( `};`.includes(str[i]) || // it's whitespace and it's not leading up to a colon (str[i] && !str[i].trim() && str[rightVal as number] !== ":") ) { if (str[i] === ";") { property.semi = i; console.log( `4249 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.semi`}\u001b[${39}m`} = ${JSON.stringify( property.semi, null, 4 )}` ); } // precaution against broken code: // .a{x}} // if (!property.end) { property.end = property.semi ? property.semi + 1 : i; console.log( `4263 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); } // push and init and patch up to resume pushProperty(property); propertyReset(); console.log( `4275 push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); } // cases with replaced colon: // <div style="float.left;"> if ( // it's a non-whitespace character str[i] && str[i].trim() && // and property seems plausible - its first char at least attrNameRegexp.test(str[property.propertyStarts]) && // but this current char is not: !attrNameRegexp.test(str[i]) && // and it's not terminating character !`:'"`.includes(str[i]) ) { console.log( `4294 ${`\u001b[${31}m${`dodgy character?`}\u001b[${39}m`}` ); // find out locations of next semi and next colon const nextSemi = str.indexOf(";", i); const nextColon = str.indexOf(":", i); console.log( `4300 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`nextSemi`}\u001b[${39}m`} = ${nextSemi}; ${`\u001b[${33}m${`nextColon`}\u001b[${39}m`} = ${nextColon}` ); // whatever the situation, colon must not be before semi on the right // either one or both missing is fine, we just want to avoid // <div style="floa.t:left; // ^ // this is not a dodgy colon // // but, // // <div style="float.left; // ^ // this is if ( // either semi but no colon ((nextColon === -1 && nextSemi !== -1) || !(nextColon !== -1 && nextSemi !== -1 && nextColon < nextSemi)) && !`{}`.includes(str[i]) && rightVal && // <style>.a{b!} // ^ (!`!`.includes(str[i]) || isLatinLetter(str[rightVal])) ) { // <div style="float.left;"> // ^ // we're here console.log( `4328 ${`\u001b[${32}m${`CORRECTION #1 - set this as colon`}\u001b[${39}m`}` ); property.colon = i; property.valueStarts = rightVal; console.log( `4333 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.colon`}\u001b[${39}m`} = ${ property.colon }; ${`\u001b[${33}m${`property.valueStarts`}\u001b[${39}m`} = ${ property.valueStarts }` ); } else if ( nextColon !== -1 && nextSemi !== -1 && nextColon < nextSemi ) { // case like // <div style="floa/t:left;"> // ^ // we're here console.log( `4349 ${`\u001b[${32}m${`CORRECTION #2 - patch by extending the prop`}\u001b[${39}m`}` ); property.propertyEnds = null; console.log( `4353 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.propertyEnds`}\u001b[${39}m`} = ${ property.propertyEnds }` ); } else if (str[i] === "!") { property.importantStarts = i; console.log( `4360 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.importantStarts`}\u001b[${39}m`} = ${ property.importantStarts }` ); } } } // catch the colon of a css property // ------------------------------------------------------------------------- if ( !doNothing && // we don't check for token.type === "rule" because inline css will use // these clauses too and token.type === "tag" there, but // attrib.attribName === "style" // on other hand, we don't need strict validation here either, to enter // these clauses it's enough that "property" was initiated. property && property.propertyEnds && !property.valueStarts && str[i] === ":" ) { property.colon = i; console.log( `4385 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.colon`}\u001b[${39}m`} = ${JSON.stringify( property.colon, null, 4 )}` ); // if string abruptly ends, record it here if (!rightVal) { property.end = i + 1; console.log( `4396 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.end`}\u001b[${39}m`} = ${JSON.stringify( property.end, null, 4 )}` ); if (str[i + 1]) { // push and init and patch up to resume pushProperty(property); propertyReset(); console.log( `4408 push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); // that's some trailing whitespace, create a new text token for it if ((token as any).properties) { (token as any).properties.push({ type: "text", start: i + 1, end: null as any, value: null as any, }); console.log( `4420 PUSH to ${`\u001b[${33}m${`token.properties`}\u001b[${39}m`}, now = ${JSON.stringify( (token as any).properties, null, 4 )}` ); doNothing = i + 1; console.log( `4429 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } } } console.log( `4440 FIY, ${`\u001b[${33}m${`lastNonWhitespaceCharAt`}\u001b[${39}m`} = ${JSON.stringify( lastNonWhitespaceCharAt, null, 4 )}` ); // insurance against rogue characters // <style>.a{float:left;x">color: red} // | ^ // | we're here // propertyStarts if ( property.propertyEnds && lastNonWhitespaceCharAt && property.propertyEnds !== lastNonWhitespaceCharAt + 1 && // it ends upon a bad character !attrNameRegexp.test(str[property.propertyEnds]) ) { property.propertyEnds = lastNonWhitespaceCharAt + 1; property.property = str.slice( property.propertyStarts as number, property.propertyEnds ); console.log( `4465 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`property.propertyEnds`}\u001b[${39}m`} = ${ property.propertyEnds }; ${`\u001b[${33}m${`property.property`}\u001b[${39}m`} = ${ property.property }` ); } } // catch the start of a css property's name // ------------------------------------------------------------------------- if ( !doNothing && token.type === "rule" && str[i] && str[i].trim() && // NOTA BENE - there's same clause for inline HTML style // let all the crap in, filter later: !"{}".includes(str[i]) && // above is instead of a stricter clause: // attrNameRegexp.test(str[i]) && token.selectorsEnd && token.openingCurlyAt && !property.propertyStarts && !property.importantStarts ) { console.log( `4492 ${`\u001b[${32}m${`css property's name starts`}\u001b[${39}m`}` ); // first, check maybe there's unfinished text token before it if ( Array.isArray(token.properties) && token.properties.length && token.properties[~-token.properties.length].start && !token.properties[~-token.properties.length].end ) { token.properties[~-token.properties.length].end = i; token.properties[~-token.properties.length].value = str.slice( token.properties[~-token.properties.length].start as number, i ); console.log( `4508 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} last elem of ${`\u001b[${33}m${`token.properties[]`}\u001b[${39}m`} to: ${JSON.stringify( token.properties[~-token.properties.length], null, 4 )}` ); } // in normal cases we're set propertyStarts but sometimes it can be // importantStarts, imagine: // <style>.a{color:red; !important;} // ^ // we're here // // we want to put "!important" under key "important", not under // "property" if (str[i] === ";") { console.log(`4526`); initProperty({ start: i, end: i + 1, semi: i, }); pushProperty(property); propertyReset(); console.log( `4535 init, push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); } else if (str[i] === "!") { console.log(`4538`); initProperty({ start: i, importantStarts: i, }); console.log( `4544 ${`\u001b[${32}m${`INIT`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); } else { console.log(`4551`); initProperty(i); console.log( `4554 ${`\u001b[${32}m${`INIT`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); } doNothing = i; console.log( `4564 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } // catch the start a property // ------------------------------------------------------------------------- // Mostly happens in dirty code cases - the start is normally being triggered // not from here, the first character, but earlier, from previous clauses. // But imagine <div style="float;left">z</div> // ^ // wrong // // in case like above, "l" would not have the beginning of a property // triggered, hence this clause here if ( !doNothing && (!token || token.type !== "esp") && // style attribute is being processed at the moment attrib && attrib.attribName === "style" && // it's not done yet attrib.attribOpeningQuoteAt && !attrib.attribClosingQuoteAt && // but property hasn't been initiated !property.start && // yet the character is suitable: // it's not a whitespace str[i] && str[i].trim() && // NOTA BENE - there's same clause for inline HTML style // it's not some separator !`'"`.includes(str[i]) && // it's not inside CSS block comment !lastLayerIs("block") ) { console.log(`4603 inside start of css property/comment token`); // It's either css comment or a css property. // Dirty characters go as property name, then later we validate and // catch them. // Empty space goes as text token, see separate clauses above. if ( // currently it's slash str[i] === "/" && // asterisk follows, straight away or after whitespace str[rightVal as number] === "*" ) { console.log( `4616 ${`\u001b[${32}m${`BLOCK COMMENT OPENING`}\u001b[${39}m`}` ); attribPush({ type: "comment", start: i, end: (rightVal as number) + 1, value: str.slice(i, (rightVal as number) + 1), // think of broken cases with whitespace, / * closing: false, kind: "block", language: "css", }); // push a new layer, comment layers.push({ type: "block", value: str.slice(i, (rightVal as number) + 1), // think of broken cases with whitespace, / * position: i, }); console.log( `4636 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} new layer, ${JSON.stringify( { type: "block", value: str[i], position: i, }, null, 4 )}` ); // skip the next char, consider there might be whitespace in front doNothing = (rightVal as number) + 1; console.log( `4650 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } // if it's a closing comment else if (str[i] === "*" && str[rightVal as number] === "/") { console.log(`4659 call closingComment()`); closingComment(i); } else { console.log(`4662`); // first, close the text token if it's not ended if ( Array.isArray(attrib.attribValue) && attrib.attribValue.length && !attrib.attribValue[~-attrib.attribValue.length].end ) { attrib.attribValue[~-attrib.attribValue.length].end = i; attrib.attribValue[~-attrib.attribValue.length].value = str.slice( attrib.attribValue[~-attrib.attribValue.length].start, i ); console.log( `4675 complete last attrib object: ${JSON.stringify( attrib.attribValue[~-attrib.attribValue.length], null, 4 )}` ); } // initiate a property // if !important has been detected, that's a CSS like: // <div style="float:left;!important"> // the !important is alone by itself // also, it can be semi along by itself if (str[i] === ";") { console.log(`4689`); initProperty({ start: i, end: i + 1, semi: i, }); console.log( `4696 ${`\u001b[${32}m${`INIT`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); doNothing = i; console.log( `4704 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } else if (R2) { console.log(`4711`); initProperty({ start: i, importantStarts: i, }); console.log( `4717 ${`\u001b[${32}m${`INIT`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); } else { // protection against unclosed quotes // <div style="float:left;; > // ^ // we're here console.log(`4728`); initProperty(i); console.log( `4731 ${`\u001b[${32}m${`INIT`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); } } } // in comment type, "only" kind tokens, submit square brackets to layers // ------------------------------------------------------------------------- // ps. it's so that we can rule out greater-than signs if (token.type === "comment" && ["only", "not"].includes(token.kind)) { if (str[i] === "[") { // submit it to layers // TODO } } // catch the ending of a token // ------------------------------------------------------------------------- if (!doNothing) { if (token.type === "tag" && !layers.length && str[i] === ">") { token.end = i + 1; token.value = str.slice(token.start, token.end); console.log( `4759 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); // at this point other attributes might be still not submitted yet, // we can't reset it here } else if ( token.type === "comment" && token.language === "html" && !layers.length && token.kind === "simple" && ((str[token.start] === "<" && str[i] === "-" && (matchLeft(str, i, "!-", { trimBeforeMatching: true, }) || (matchLeftIncl(str, i, "!-", { trimBeforeMatching: true, }) && str[i + 1] !== "-"))) || (str[token.start] === "-" && str[i] === ">" && matchLeft(str, i, "--", { trimBeforeMatching: true, maxMismatches: 1, }))) ) { if ( str[i] === "-" && (matchRight(str, i, ["[if", "(if", "{if"], { i: true, trimBeforeMatching: true, }) || (matchRight(str, i, ["if"], { i: true, trimBeforeMatching: true, }) && // the following case will assume closing sq. bracket is present (xBeforeYOnTheRight(str, i, "]", ">") || // in case there are no brackets leading up to "mso" (which must exist) (str.includes("mso", i) && !str.slice(i, str.indexOf("mso")).includes("<") && !str.slice(i, str.indexOf("mso")).includes(">"))))) ) { // don't set the token's end, leave it open until the // closing bracket, for example, it might be: // <!--[if gte mso 9]> // ^ // we're here // console.log( `4810 ${`\u001b[${32}m${`OUTLOOK CONDITIONAL "ONLY" DETECTED`}\u001b[${39}m`}` ); token.kind = "only"; console.log( `4814 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ token.kind }` ); } else if ( // ensure it's not starting with closing counterpart, // --><![endif]--> // but with // <!--<![endif]--> str[token.start] !== "-" && matchRightIncl(str, i, ["-<![endif"], { i: true, trimBeforeMatching: true, maxMismatches: 2, }) ) { // don't set the token's end, leave it open until the // closing bracket, for example, it might be: // <!--<![endif]--> // ^ // we're here // console.log( `4837 ${`\u001b[${32}m${`OUTLOOK CONDITIONAL "NOT" DETECTED`}\u001b[${39}m`}` ); token.kind = "not"; token.closing = true; console.log( `4842 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ token.kind }; ${`\u001b[${33}m${`token.closing`}\u001b[${39}m`} = ${ token.closing }` ); } else if ( token.kind === "simple" && token.language === "html" && !token.closing && str[rightVal as number] === ">" ) { console.log( `4855 ${`\u001b[${32}m${`simplet-kind comment token's ending caught`}\u001b[${39}m`}` ); token.end = (rightVal as number) + 1; token.kind = "simplet"; token.closing = null; console.log( `4861 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); console.log( `4866 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ token.kind }` ); console.log( `4871 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.closing`}\u001b[${39}m`} = ${ token.closing }` ); } else if (token.language === "html") { // if it's a simple HTML comment, <!--, end it right here console.log( `4878 ${`\u001b[${32}m${`${token.kind} comment token's ending caught`}\u001b[${39}m`}` ); token.end = i + 1; // tokenizer will catch <!- as opening, so we need to extend // for correct cases with two dashes <!-- if ( str[leftVal as number] === "!" && str[rightVal as number] === "-" ) { token.end = (rightVal as number) + 1; console.log( `4890 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); } token.value = str.slice(token.start, token.end); console.log( `4898 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); } // at this point other attributes might be still not submitted yet, // we can't reset it here } else if ( token.type === "comment" && token.language === "html" && str[i] === ">" && (!layers.length || str[rightVal as number] === "<") ) { // if last layer was for square bracket, this means closing // counterpart is missing so we need to remove it now // because it's the ending of the tag ("only" kind) or // at least the first part of it ("not" kind) if ( Array.isArray(layers) && layers.length && (layers[~-layers.length] as any).value === "[" ) { layers.pop(); console.log(`4921 ${`\u001b[${31}m${`POP`}\u001b[${39}m`} layers`); } // the difference between opening Outlook conditional comment "only" // and conditional "only not" is that <!--> follows if ( !["simplet", "not"].includes(token.kind) && matchRight(str, i, ["<!-->", "<!---->"], { trimBeforeMatching: true, maxMismatches: 1, lastMustMatch: true, }) ) { console.log( `4935 that's kind="not" comment and it continues on the right` ); token.kind = "not"; console.log( `4939 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ token.kind }` ); } else { console.log( `4945 that's the end of opening type="comment" kind="only" comment` ); token.end = i + 1; token.value = str.slice(token.start, token.end); console.log( `4950 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); } } else if ( token.type === "comment" && token.language === "css" && str[i] === "*" && str[i + 1] === "/" ) { token.end = i + 1; token.value = str.slice(token.start, token.end); console.log( `4964 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); } else if ( token.type === "esp" && token.end === null && typeof token.head === "string" && typeof token.tail === "string" && token.tail.includes(str[i]) ) { console.log(`4975 POSSIBLE ESP TAILS`); // extract the whole lump of ESP tag characters: let wholeEspTagClosing = ""; for (let y = i; y < len; y++) { if (espChars.includes(str[y])) { wholeEspTagClosing += str[y]; } else { break; } } console.log(`4986 wholeEspTagClosing = ${wholeEspTagClosing}`); // now, imagine the new heads start, for example, // {%- z -%}{%- // ^ // we're here // find the breaking point where tails end if (wholeEspTagClosing.length > token.head.length) { console.log( `4996 wholeEspTagClosing.length = ${`\u001b[${33}m${ wholeEspTagClosing.length }\u001b[${39}m`} > token.head.length = ${`\u001b[${33}m${ token.head.length }\u001b[${39}m`}` ); // in order for this to be tails + new heads, the total length should be // at least bigger than heads. // // For example: Responsys heads: $( - 2 chars. Tails = ) - 1 char. // Responsys total of closing tail + head - )$( - 3 chars. // That's more than head, 2 chars. // // For example, eDialog heads: _ - 1 char. Tails: __ - 2 chars. // eDialog total of closing tail + head = 3 chars. // That's more than head, 1 char. // // And same applies to Nujnucks, even considering mix of diferent // heads. // // Another important point - first character in ESP literals. // Even if there are different types of literals, more often than not // first character is constant. Variations are often inside of // the literals pair - for example Nunjucks {{ and {% and {%- // the first character is always the same. // const headsFirstChar = token.head[0]; if (wholeEspTagClosing.endsWith(token.head)) { console.log(`5024 - chunk ends with the same heads`); // we have a situation like // zzz *|aaaa|**|bbb|* // ^ // we're here and we extracted a chunk |**| and we're // trying to split it into two. // // by the way, that's very lucky because node.heads (opening *| above) // is confirmed - we passed those heads and we know they are exact. // Now, our chunk ends with exactly the same new heads. // The only consideration is error scenario, heads intead of tails. // That's why we'll check, tags excluded, that's the length left: // |**| minus heads *| equals |* -- length 2 -- happy days. // Bad scenario: // *|aaaa*|bbb|* // ^ // we're here // // *| minus heads *| -- length 0 -- raise an error! token.end = i + wholeEspTagClosing.length - token.head.length; token.value = str.slice(token.start, token.end); console.log( `5047 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); doNothing = token.end; console.log( `5053 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); } else if (wholeEspTagClosing.startsWith(token.tail)) { token.end = i + token.tail.length; token.value = str.slice(token.start, token.end); console.log( `5059 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); doNothing = token.end; console.log( `5065 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); } else if ( (!token.tail.includes(headsFirstChar) && wholeEspTagClosing.includes(headsFirstChar)) || wholeEspTagClosing.endsWith(token.head) || wholeEspTagClosing.startsWith(token.tail) ) { console.log(`5073`); // We're very lucky because heads and tails are using different // characters, possibly opposite brackets of some kind. // That's Nunjucks, Responsys (but no eDialog) patterns. const firstPartOfWholeEspTagClosing = wholeEspTagClosing.slice( 0, wholeEspTagClosing.indexOf(headsFirstChar) ); const secondPartOfWholeEspTagClosing = wholeEspTagClosing.slice( wholeEspTagClosing.indexOf(headsFirstChar) ); console.log( `${`\u001b[${33}m${`firstPartOfWholeEspTagClosing`}\u001b[${39}m`} = ${JSON.stringify( firstPartOfWholeEspTagClosing, null, 4 )}` ); console.log( `${`\u001b[${33}m${`secondPartOfWholeEspTagClosing`}\u001b[${39}m`} = ${JSON.stringify( secondPartOfWholeEspTagClosing, null, 4 )}` ); // imagine we sliced off (Nunjucks): -%}{%- // if every character from anticipated tails (-%}) is present in the front // chunk, Bob's your uncle, that's tails with new heads following. if ( firstPartOfWholeEspTagClosing.length && secondPartOfWholeEspTagClosing.length && token.tail .split("") .every((char) => firstPartOfWholeEspTagClosing.includes(char)) ) { console.log(`5108 definitely tails + new heads`); token.end = i + firstPartOfWholeEspTagClosing.length; token.value = str.slice(token.start, token.end); console.log( `5112 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); doNothing = token.end; console.log( `5118 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); } } else { // so heads and tails don't contain unique character, and more so, // starting-one, PLUS, second set is different. // For example, ESP heads/tails can be *|zzz|* // Imaginary example, following heads would be variation of those // above, ^|zzz|^ console.log(`CASE #2.`); // TODO // for now, return defaults, from else scenario below: // we consider this whole chunk is tails. token.end = i + wholeEspTagClosing.length; token.value = str.slice(token.start, token.end); console.log( `5134 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); doNothing = token.end; console.log( `5140 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); } console.log(`5143`); } else { // we consider this whole chunk is tails. token.end = i + wholeEspTagClosing.length; token.value = str.slice(token.start, token.end); console.log( `5149 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); // if last layer is ESP tag and we've got its closing, pop the layer if (lastLayerIs("esp")) { console.log( `5157 ${`\u001b[${32}m${`POP`}\u001b[${39}m`} layers, now ${`\u001b[${33}m${`layers`}\u001b[${39}m`}: ${JSON.stringify( layers, null, 4 )}` ); layers.pop(); } doNothing = token.end; console.log( `5168 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${doNothing}` ); } } // END OF if (!doNothing) } // Catch the end of a tag name // ------------------------------------------------------------------------- if ( !doNothing && token.type === "tag" && token.tagNameStartsAt && !token.tagNameEndsAt ) { console.log(`5184 catch the end of a tag name clauses`); // tag names can be with numbers, h1 if (!str[i] || !charSuitableForTagName(str[i])) { token.tagNameEndsAt = i; console.log( `5190 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.tagNameEndsAt`}\u001b[${39}m`} = ${ token.tagNameEndsAt }` ); token.tagName = str.slice(token.tagNameStartsAt, i).toLowerCase(); console.log( `5197 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.tagName`}\u001b[${39}m`} = ${ token.tagName }` ); if (token.tagName && token.tagName.toLowerCase() === "script") { withinScript = !withinScript; console.log( `5205 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`withinScript`}\u001b[${39}m`} = ${JSON.stringify( withinScript, null, 4 )}` ); } if (token.tagName === "xml" && token.closing && !token.kind) { token.kind = "xml"; console.log( `5216 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.kind`}\u001b[${39}m`} = ${ token.kind }` ); } // We evaluate self-closing tags not by presence of slash but evaluating // is the tag name among known self-closing tags. This way, we can later // catch and fix missing closing slashes. if (voidTags.includes(token.tagName)) { token.void = true; console.log( `5228 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.void`}\u001b[${39}m`} = ${ token.void }` ); } token.recognised = isTagNameRecognised(token.tagName); console.log( `5237 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.recognised`}\u001b[${39}m`} = ${ token.recognised }` ); doNothing = i; console.log( `5244 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } } // Catch the start of a tag name: // ------------------------------------------------------------------------- if ( !doNothing && token.type === "tag" && !token.tagNameStartsAt && token.start != null && (token.start < i || str[token.start] !== "<") ) { console.log(`5263 catch the start of a tag name clauses`); // MULTIPLE ENTRY! // Consider closing tag's slashes and tag name itself. if (str[i] === "/") { token.closing = true; console.log( `5270 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.closing`}\u001b[${39}m`} = ${ token.closing }` ); doNothing = i; console.log( `5277 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } else if (isLatinLetter(str[i])) { token.tagNameStartsAt = i; console.log( `5286 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.tagNameStartsAt`}\u001b[${39}m`} = ${ token.tagNameStartsAt }` ); // if by now closing marker is still null, set it to false - there // won't be any closing slashes between opening bracket and tag name if (!token.closing) { token.closing = false; console.log( `5295 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.closing`}\u001b[${39}m`} = ${ token.closing }` ); doNothing = i; console.log( `5302 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } } else { // TODO - tag opening followed by not-a-letter? // <?a> } } // catch the end of a tag attribute's name // ------------------------------------------------------------------------- if ( !doNothing && token.type === "tag" && token.kind !== "cdata" && attrib.attribNameStartsAt && i > attrib.attribNameStartsAt && attrib.attribNameEndsAt === null && !isAttrNameChar(str[i]) ) { console.log(`5326 inside catch the tag attribute name end clauses`); attrib.attribNameEndsAt = i; attrib.attribName = str.slice(attrib.attribNameStartsAt, i); attrib.attribNameRecognised = allHtmlAttribs.has(attrib.attribName); if (attrib.attribName.startsWith("mc:")) { // that's a mailchimp attribute token.pureHTML = false; } console.log( `5337 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribNameEndsAt`}\u001b[${39}m`} = ${ attrib.attribNameEndsAt }; ${`\u001b[${33}m${`attrib.attribName`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribName, null, 0 )}` ); // maybe there's a space in front of equal, <div class= ""> if (str[i] && !str[i].trim() && str[rightVal as number] === "=") { console.log(`5348 equal on the right`); } else if ( (str[i] && !str[i].trim()) || str[i] === ">" || (str[i] === "/" && str[rightVal as number] === ">") ) { if (`'"`.includes(str[rightVal as number])) { console.log( `5356 ${`\u001b[${31}m${`space instead of equal`}\u001b[${39}m`}` ); } else { console.log( `5360 ${`\u001b[${31}m${`a value-less attribute detected`}\u001b[${39}m`}` ); attrib.attribEnds = i; console.log( `5364 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribEnds`}\u001b[${39}m`} = ${ attrib.attribEnds }` ); // push and wipe console.log( `5371 ${`\u001b[${32}m${`PUSH ATTR AND WIPE`}\u001b[${39}m`}` ); token.attribs.push(clone(attrib)); attribReset(); } } } // catch the start of a tag attribute's name // ------------------------------------------------------------------------- if ( !doNothing && str[i] && token.type === "tag" && token.kind !== "cdata" && token.tagNameEndsAt && i > token.tagNameEndsAt && attrib.attribStarts === null && isAttrNameChar(str[i]) ) { console.log(`5391 inside catch the tag attribute name start clauses`); attrib.attribStarts = i; // even though in theory left() which reports first non-whitespace // character's index on the left can be null, it does not happen // in this context - there will be tag's name or something in front! attrib.attribLeft = lastNonWhitespaceCharAt as number; attrib.attribNameStartsAt = i; console.log( `5399 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribStarts`}\u001b[${39}m`} = ${ attrib.attribStarts }; ${`\u001b[${33}m${`attrib.attribLeft`}\u001b[${39}m`} = ${ attrib.attribLeft }; ${`\u001b[${33}m${`attrib.attribNameStartsAt`}\u001b[${39}m`} = ${ attrib.attribNameStartsAt }` ); console.log( `5409 ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValue, null, 4 )}` ); } // catch the curlies inside CSS rule // ------------------------------------------------------------------------- if (!doNothing && token.type === "rule") { if ( str[i] === "{" && str[i + 1] !== "{" && str[i - 1] !== "{" && !token.openingCurlyAt ) { token.openingCurlyAt = i; console.log( `5429 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.openingCurlyAt`}\u001b[${39}m`} = ${ token.openingCurlyAt }` ); } else if ( str[i] === "}" && token.openingCurlyAt && !token.closingCurlyAt ) { token.closingCurlyAt = i; token.end = i + 1; token.value = str.slice(token.start, token.end); console.log( `5442 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.closingCurlyAt`}\u001b[${39}m`} = ${ token.closingCurlyAt }; ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${token.end}` ); // check is the property's last text token closed: if ( Array.isArray(token.properties) && token.properties.length && token.properties[~-token.properties.length].start && !token.properties[~-token.properties.length].end ) { token.properties[~-token.properties.length].end = i; token.properties[~-token.properties.length].value = str.slice( token.properties[~-token.properties.length].start, i ); console.log( `5460 ${`\u001b[${32}m${`COMPLETE`}\u001b[${39}m`} ${`\u001b[${33}m${`token.properties[]`}\u001b[${39}m`} last elem, now = ${JSON.stringify( token.properties[~-token.properties.length], null, 4 )}` ); } // if there's partial, still-pending property, push it if (property.start) { console.log( `5471 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} the pending property` ); token.properties.push(property); propertyReset(); } console.log(`5477 ${`\u001b[${32}m${`PING`}\u001b[${39}m`}`); pingTagCb(token); // if it's a "rule" token and a parent "at" rule is pending in layers, // also put this "rule" into that parent in layers if (lastLayerIs("at")) { console.log( `5484 ${`\u001b[${32}m${`PUSH this rule into last AT layer`}\u001b[${39}m`}` ); (layers[~-layers.length] as LayerKindAt).token.rules.push(token); } console.log(`5489 ${`\u001b[${32}m${`RESET`}\u001b[${39}m`}`); tokenReset(); } } // catch the ending of a attribute sub-token value // ------------------------------------------------------------------------- if ( !doNothing && attrib.attribName && Array.isArray(attrib.attribValue) && attrib.attribValue.length && !attrib.attribValue[~-attrib.attribValue.length].end ) { // TODO console.log( `5506 ${`\u001b[${35}m${`██`}\u001b[${39}m`} inside attribute sub-token end clauses` ); // if it's a closing comment if (str[i] === "*" && str[rightVal as number] === "/") { closingComment(i); } } // catch the beginning of a attribute sub-token value // ------------------------------------------------------------------------- if ( // EITHER IT'S INLINE CSS: (!doNothing && // attribute has been recording attrib && // and it's not finished attrib.attribValueStartsAt && !attrib.attribValueEndsAt && // and its property hasn't been recording !property.propertyStarts && // and it's not within ESP token inside inline CSS token.type !== "esp" && // we're inside the value i >= attrib.attribValueStartsAt && // if attribValue array is empty, no object has been placed yet, Array.isArray(attrib.attribValue) && (!attrib.attribValue.length || // or there is one but it's got ending (prevention from submitting // another text type object on top, before previous has been closed) (attrib.attribValue[~-attrib.attribValue.length].end && // and that end is less than current index i attrib.attribValue[~-attrib.attribValue.length].end <= i))) || // OR IT'S HEAD CSS (!doNothing && // css rule token has been recording token.type === "rule" && // token started: token.openingCurlyAt && // but not ended: !token.closingCurlyAt && // there is no unfinished property being recorded !property.propertyStarts) ) { console.log( `5552 ${`\u001b[${36}m${`██`}\u001b[${39}m`} inside attribute sub-token start clauses` ); // if it's suitable for property, start a property if ( str[i] === ";" && // a) if it's inline HTML tag CSS style attribute ((attrib && Array.isArray(attrib.attribValue) && attrib.attribValue.length && // last attribute has semi already set: (attrib.attribValue[~-attrib.attribValue.length] as any).semi && // and that semi is really behind this current index (attrib.attribValue[~-attrib.attribValue.length] as any).semi < i) || // or // b) if it's head CSS styles block (token && token.type === "rule" && Array.isArray(token.properties) && token.properties.length && (token.properties[~-token.properties.length] as any).semi && (token.properties[~-token.properties.length] as any).semi < i)) ) { // rogue semi? // <div style="float:left;;"> // ^ // if so, it goes as a standalone property, something like: // { // start: 23, // end: 24, // property: null, // propertyStarts: null, // propertyEnds: null, // value: null, // valueStarts: null, // valueEnds: null, // important: null, // importantStarts: null, // importantEnds: null, // colon: null, // semi: 23, // } initProperty({ start: i, semi: i, }); console.log( `5600 ${`\u001b[${32}m${`INIT`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`} = ${JSON.stringify( property, null, 4 )}` ); doNothing = i + 1; console.log( `5608 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${31}m${`doNothing`}\u001b[${39}m`} = ${JSON.stringify( doNothing, null, 4 )}` ); } // if it's whitespace, for example, // <a style=" /* zzz */color: red; "> // ^ // this // // rogue text will go as property, for example: // // <a style=" z color: red; "> else if ( // whitespace is automatically text token (str[i] && !str[i].trim()) || // if comment layer has been started, it's also a text token, no matter even // if it's a property, because it's comment's contents. lastLayerIs("block") ) { console.log(`5630`); // depends where to push, is it inline css or head css rule if (attrib.attribName) { (attrib.attribValue as any).push({ type: "text", start: i, end: null, value: null, }); console.log( `5640 PUSH to ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`}, now = ${JSON.stringify( attrib.attribValue, null, 4 )}` ); } else if ( token.type === "rule" && // we don't want to push over the properties in-progress (!Array.isArray(token.properties) || !token.properties.length || // last property should have ended token.properties[~-token.properties.length].end) ) { token.properties.push({ type: "text", start: i, end: null as any, value: null as any, }); console.log( `5661 PUSH to ${`\u001b[${33}m${`token.properties`}\u001b[${39}m`}, now = ${JSON.stringify( token.properties, null, 4 )}` ); } } } // Catch the end of a tag attribute's value: // ------------------------------------------------------------------------- if ( !doNothing && token.type === "tag" && attrib.attribValueStartsAt && i >= attrib.attribValueStartsAt && attrib.attribValueEndsAt === null ) { console.log(`5681 inside a catching end of a tag attr clauses`); if (SOMEQUOTE.includes(str[i])) { console.log(`5683 currently on a quote`); console.log( `5686 ███████████████████████████████████████ isAttrClosing(str, ${ attrib.attribOpeningQuoteAt || attrib.attribValueStartsAt }, ${i}) = ${isAttrClosing( str, attrib.attribOpeningQuoteAt || attrib.attribValueStartsAt, i )}` ); if ( // so we're on a single/double quote, // (str[i], the current character is a quote) // and... // we're not inside some ESP tag - ESP layers are not pending: !layers.some((layerObj) => layerObj.type === "esp") && // and the current character passed the // attribute closing quote validation by // "is-html-attribute-closing" // // the isAttrClosing() api is the following: // 1. str, 2. opening quotes index, 3. suspected // character for attribute closing (quotes typically, // but can be mismatching)... // see the package "is-html-attribute-closing" on npm: // // // either end was reached, (!str[i] || // or there is no closing bracket further !str.includes(">", i) || // further checks confirm it looks like legit closing isAttrClosing( str, attrib.attribOpeningQuoteAt || attrib.attribValueStartsAt, i )) ) { console.log( `5724 ${`\u001b[${32}m${`opening and closing quotes matched!`}\u001b[${39}m`}` ); console.log( `5727 ${`\u001b[${32}m${`FIY`}\u001b[${39}m`}, ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); attrib.attribClosingQuoteAt = i; attrib.attribValueEndsAt = i; if (attrib.attribValueStartsAt) { attrib.attribValueRaw = str.slice(attrib.attribValueStartsAt, i); } attrib.attribEnds = i + 1; if (property.propertyStarts) { attrib.attribValue.push(clone(property)); console.log( `5744 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} property into ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`}` ); propertyReset(); console.log( `5748 ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} property` ); } if ( Array.isArray(attrib.attribValue) && attrib.attribValue.length && !attrib.attribValue[~-attrib.attribValue.length].end ) { console.log( `5758 set the ending on the last object within "attribValue"` ); // if it's not a property (of inline style), set its "end" if ( !(attrib.attribValue[~-attrib.attribValue.length] as any).property ) { attrib.attribValue[~-attrib.attribValue.length].end = i; console.log( `5766 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValue[${~-attrib .attribValue.length}].end`}\u001b[${39}m`} = ${ attrib.attribValue[~-attrib.attribValue.length].end };` ); if ( (attrib.attribValue[~-attrib.attribValue.length] as any) .property === null ) { console.log( `5777 ${`\u001b[${31}m${`CSS property without a value!`}\u001b[${39}m`}` ); // it's CSS property without a value: // <img style="display" /> ( attrib.attribValue[~-attrib.attribValue.length] as any ).property = str.slice( attrib.attribValue[~-attrib.attribValue.length].start, i ); ( attrib.attribValue[~-attrib.attribValue.length] as any ).propertyEnds = i; console.log( `5791 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValue[${~-attrib .attribValue.length}].value`}\u001b[${39}m`} = ${ attrib.attribValue[~-attrib.attribValue.length].value }; ${`\u001b[${33}m${`attrib.attribValue[${~-attrib .attribValue.length}].propertyEnds`}\u001b[${39}m`} = ${i}` ); } else { console.log(`5798 assign to value`); attrib.attribValue[~-attrib.attribValue.length].value = str.slice( attrib.attribValue[~-attrib.attribValue.length].start, i ); console.log( `5805 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValue[${~-attrib .attribValue.length}].value`}\u001b[${39}m`} = ${ attrib.attribValue[~-attrib.attribValue.length].value }` ); } } } console.log( `5814 ${`\u001b[${32}m${`NOW`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); // 2. if the pair was mismatching, wipe layers' last element if (str[attrib.attribOpeningQuoteAt as number] !== str[i]) { layers.pop(); layers.pop(); console.log( `5826 POP x 2, now layers = ${JSON.stringify(layers, null, 4)}` ); } // 3. last check for the last attribValue's .end - in some broken code // cases it might be still null: // <div style="float:left;x"> // ^ // we're here if ( attrib.attribValue[~-attrib.attribValue.length] && !attrib.attribValue[~-attrib.attribValue.length].end ) { attrib.attribValue[~-attrib.attribValue.length].end = i; console.log( `5841 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} .end on the last attribValue, now = ${JSON.stringify( attrib.attribValue[~-attrib.attribValue.length], null, 4 )}` ); } // 4. push and wipe console.log( `5851 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); token.attribs.push(clone(attrib)); attribReset(); } else if ( (!Array.isArray(attrib.attribValue) || !attrib.attribValue.length || // last attrib value should not be a text token (attrib.attribValue[~-attrib.attribValue.length] as any).type !== "text") && !property.propertyStarts ) { // quotes not matched, so it's unencoded, raw quote, part of the value // for example // <table width=""100"> // ^ // rogue quote // let's initiate a next token attrib.attribValue.push({ type: "text", start: i, end: null as any, value: null as any, }); console.log( `5882 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} new to attrib.attribValue, now ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`}: ${JSON.stringify( attrib.attribValue, null, 4 )}` ); } console.log(`5890`); } else if ( attrib.attribOpeningQuoteAt === null && ((str[i] && !str[i].trim()) || ["/", ">"].includes(str[i]) || (espChars.includes(str[i]) && espChars.includes(str[i + 1]))) ) { // ^ either whitespace or tag's closing or ESP literal's start ends // the attribute's value if there are no quotes console.log(`5899 opening quote was missing, terminate attr val here`); attrib.attribValueEndsAt = i; attrib.attribValueRaw = str.slice(attrib.attribValueStartsAt, i); if ( Array.isArray(attrib.attribValue) && attrib.attribValue.length && !attrib.attribValue[~-attrib.attribValue.length].end ) { attrib.attribValue[~-attrib.attribValue.length].end = i; attrib.attribValue[~-attrib.attribValue.length].value = str.slice( attrib.attribValue[~-attrib.attribValue.length].start, attrib.attribValue[~-attrib.attribValue.length].end ); } attrib.attribEnds = i; console.log( `5916 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValueEndsAt`}\u001b[${39}m`} = ${ attrib.attribValueEndsAt }; ${`\u001b[${33}m${`attrib.attribValueRaw`}\u001b[${39}m`} = ${ attrib.attribValueRaw }; ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValue, null, 4 )}; ${`\u001b[${33}m${`attrib.attribEnds`}\u001b[${39}m`} = ${ attrib.attribEnds }` ); // 2. push and wipe token.attribs.push(clone(attrib)); attribReset(); // 3. pop layers layers.pop(); console.log( `5936 ${`\u001b[${31}m${`POP`}\u001b[${39}m`} ${`\u001b[${33}m${`layers`}\u001b[${39}m`}, now:\n${JSON.stringify( layers, null, 4 )}` ); // 4. tackle the tag ending if (str[i] === ">") { token.end = i + 1; token.value = str.slice(token.start, token.end); console.log( `5948 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); } } else if ( str[i] === "=" && leftVal !== null && rightVal && (`'"`.includes(str[rightVal]) || (str[~-i] && isLatinLetter(str[~-i]))) && // this will catch url params like // <img src="https://z.png?query=" /> // ^ // false alarm // // let's exclude anything URL-related !( attrib && attrib.attribOpeningQuoteAt && // check for presence of slash, / (/\//.test(str.slice(attrib.attribOpeningQuoteAt + 1, i)) || // check for mailto: /mailto:/.test(str.slice(attrib.attribOpeningQuoteAt + 1, i)) || // check for /\w?\w/ like // <img src="codsen.com?query=" /> // ^ /\w\?\w/.test(str.slice(attrib.attribOpeningQuoteAt + 1, i))) ) ) { console.log( `5979 ${`\u001b[${31}m${`MISSING CLOSING QUOTE ON PREVIOUS ATTR.`}\u001b[${39}m`}` ); // all depends, are there whitespace characters: // imagine // <a href="border="0"> // vs // <a href="xyz border="0"> // that's two different cases - there's nothing to salvage in former! console.log( `5990 ${`\u001b[${36}m${`██ traverse backwards, try to salvage something`}\u001b[${39}m`}` ); let whitespaceFound; let attribClosingQuoteAt; for (let y = leftVal; y >= attrib.attribValueStartsAt; y--) { console.log( `5997 ${`\u001b[${36}m${`------- str[${y}] = ${str[y]} -------`}\u001b[${39}m`}` ); // catch where whitespace starts if (!whitespaceFound && str[y] && !str[y].trim()) { whitespaceFound = true; if (attribClosingQuoteAt) { // slice the captured chunk const extractedChunksVal = str.slice(y, attribClosingQuoteAt); console.log( `6008 ${`\u001b[${33}m${`extractedChunksVal`}\u001b[${39}m`} = ${JSON.stringify( extractedChunksVal, null, 4 )}` ); } } // where that caught whitespace ends, that's the default location // of double quotes. // <a href="xyz border="0"> // ^ ^ // | | // | we go from here // to here if (whitespaceFound && str[y] && str[y].trim()) { whitespaceFound = false; if (!attribClosingQuoteAt) { // that's the first, default location attribClosingQuoteAt = y + 1; console.log( `6030 SET attribClosingQuoteAt = ${attribClosingQuoteAt}` ); } else { console.log(`6033 X`); } } } console.log( `6039 FIY, ${`\u001b[${33}m${`attribClosingQuoteAt`}\u001b[${39}m`} = ${JSON.stringify( attribClosingQuoteAt, null, 4 )}` ); if (attribClosingQuoteAt) { attrib.attribValueEndsAt = attribClosingQuoteAt; if (attrib.attribValueStartsAt) { attrib.attribValueRaw = str.slice( attrib.attribValueStartsAt, attribClosingQuoteAt ); console.log( `6055 FIY, ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); if ( Array.isArray(attrib.attribValue) && attrib.attribValue.length && !attrib.attribValue[~-attrib.attribValue.length].end ) { attrib.attribValue[~-attrib.attribValue.length].end = attrib.attribValueEndsAt; attrib.attribValue[~-attrib.attribValue.length].value = str.slice( attrib.attribValue[~-attrib.attribValue.length].start, attrib.attribValueEndsAt ); console.log( `6074 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} attrib.attribValue's last object's end and value: ${JSON.stringify( attrib.attribValue, null, 4 )}` ); } } attrib.attribEnds = attribClosingQuoteAt; console.log( `6084 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribClosingQuoteAt`}\u001b[${39}m`} = ${ attrib.attribClosingQuoteAt }; ${`\u001b[${33}m${`attrib.attribValueEndsAt`}\u001b[${39}m`} = ${ attrib.attribValueEndsAt }; ${`\u001b[${33}m${`attrib.attribValueRaw`}\u001b[${39}m`} = ${ attrib.attribValueRaw }; ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValue, null, 4 )}; ${`\u001b[${33}m${`attrib.attribEnds`}\u001b[${39}m`} = ${ attrib.attribEnds }` ); // 2. if the pair was mismatching, wipe layers' last element if (str[attrib.attribOpeningQuoteAt as number] !== str[i]) { layers.pop(); console.log( `6103 POP x 1, now layers = ${JSON.stringify(layers, null, 4)}` ); } // 3. push and wipe token.attribs.push(clone(attrib)); attribReset(); console.log( `6112 ██ ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); // 4. pull the i back to the position where the attribute ends i = ~-attribClosingQuoteAt; console.timeEnd(`\u001b[${90}m${`loop iteration`}\u001b[${39}m`); continue; } else if ( attrib.attribOpeningQuoteAt && (`'"`.includes(str[rightVal as number]) || allHtmlAttribs.has( str.slice(attrib.attribOpeningQuoteAt + 1, i).trim() )) ) { // worst case scenario: // <span width="height="100"> // // traversing back from second "=" we hit only the beginning of an // attribute, there was nothing to salvage. // In this case, reset the attribute's calculation, go backwards to "h". // 1. pull back the index, go backwards, read this new attribute again i = attrib.attribOpeningQuoteAt; // 2. end the attribute attrib.attribEnds = attrib.attribOpeningQuoteAt + 1; console.log( `6143 SET ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribEnds`}\u001b[${39}m`} = ${ attrib.attribEnds }` ); // 3. value doesn't start, this needs correction attrib.attribValueStartsAt = null; // 4. pop the opening quotes layer layers.pop(); // 5. push and wipe token.attribs.push(clone(attrib)); attribReset(); // 6. continue console.timeEnd(`\u001b[${90}m${`loop iteration`}\u001b[${39}m`); continue; } } else if (str[i] === "/" && str[rightVal as number] === ">") { console.log(`6163 ${`\u001b[${33}m${`TAG ENDS`}\u001b[${39}m`}`); if (attrib.attribValueStartsAt) { attrib.attribValueStartsAt = null; console.log( `6167 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValueStartsAt`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValueStartsAt, null, 4 )}` ); } if (!attrib.attribEnds) { attrib.attribEnds = i; console.log( `6177 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribEnds`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribEnds, null, 4 )}` ); } } else if ( attrib && attrib.attribName !== "style" && attrib.attribStarts && !attrib.attribEnds && !property.propertyStarts && // // AND, // // either there are no attributes recorded under attrib.attribValue: (!Array.isArray(attrib.attribValue) || // or it's array but empty: !attrib.attribValue.length || // or is it not empty but its last attrib has ended by now (attrib.attribValue[~-attrib.attribValue.length].end && attrib.attribValue[~-attrib.attribValue.length].end <= i)) ) { console.log( `6202 ${`\u001b[${33}m${`ATTR. DOESN'T END, STRING VALUE TOKEN STARTS UNDER attribValue`}\u001b[${39}m`}` ); attrib.attribValue.push({ type: "text", start: i, end: null as any, value: null as any, }); console.log( `6213 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} new to attrib.attribValue, now ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`}: ${JSON.stringify( attrib.attribValue, null, 4 )}` ); } else if ( property && !property.importantStarts && // ESP token is involved: Array.isArray(property.value) && str[i] && // and !important does not follow: (str[i].trim() || !R2) ) { // <div style="width: {{ w }}px"> // ^ // we're here // also, this clause will initiate text tokens // for all intra-ESP whitespace: // <div style="padding: {{ t }} {{ r }} {{ b }} {{ l }}"> // ^ // like this // backup the parent tag token parentTokenToBackup = clone(token); console.log( `6241 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`parentTokenToBackup`}\u001b[${39}m`} = ${JSON.stringify( parentTokenToBackup, null, 4 )}` ); // initiate a text token initToken("text", i); console.log( `6252 ${`\u001b[${33}m${`token`}\u001b[${39}m`} now = ${JSON.stringify( token, null, 4 )}` ); } } else if ( token.type === "esp" && attribToBackup && parentTokenToBackup && attribToBackup.attribOpeningQuoteAt && attribToBackup.attribValueStartsAt && `'"`.includes(str[i]) && str[attribToBackup.attribOpeningQuoteAt] === str[i] && isAttrClosing(str, attribToBackup.attribOpeningQuoteAt, i) ) { console.log( `6270 ${`\u001b[${31}m${`██`}\u001b[${39}m`} emergency catching tag attr closing quotes inside attribute, with ESP tag unclosed` ); // imagine unclosed ESP tag inside attr value: // <tr class="{% x"> // ^ // we're here // we need to still proactively look for closing attribute quotes, // even inside ESP tags, if we're inside tag attributes console.log( `6282 ${`\u001b[${32}m${`opening and closing quotes matched!`}\u001b[${39}m`}` ); console.log( `6285 ${`\u001b[${32}m${`FIY`}\u001b[${39}m`}, ${`\u001b[${33}m${`attribToBackup`}\u001b[${39}m`} = ${JSON.stringify( attribToBackup, null, 4 )}` ); // 1. patch up missing token (which is type="esp" currently) values token.end = i; token.value = str.slice(token.start, i); // 2. push token into attribToBackup.attribValue if (attribToBackup && !Array.isArray(attribToBackup.attribValue)) { attribToBackup.attribValue = []; } console.log(`6300 push token to attribValue`); attribToBackup.attribValue.push(token); // 3. patch up missing values in attribToBackup attribToBackup.attribValueEndsAt = i; attribToBackup.attribValueRaw = str.slice( attribToBackup.attribValueStartsAt as number, i ); attribToBackup.attribClosingQuoteAt = i; attribToBackup.attribEnds = i + 1; // 4. restore parent token token = clone(parentTokenToBackup); token.attribs.push(attribToBackup); // 5. reset all attribToBackup = undefined; parentTokenToBackup = undefined; console.log( `6322 FIY, now ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); attribReset(); // 6. pop the last 3 layers // currently layers array should be like: // [ // { // "type": "simple", // "value": '"', // "position": 10 // }, // { // "type": "esp", // "openingLump": "{%", // "guessedClosingLump": "%}", // "position": 11 // } // { // "type": "simple", // "value": '"', // "position": 15 // }, // ] layers.pop(); layers.pop(); layers.pop(); } // Catch the start of a tag attribute's value: // ------------------------------------------------------------------------- if ( !doNothing && token.type === "tag" && !attrib.attribValueStartsAt && attrib.attribNameEndsAt && attrib.attribNameEndsAt <= i && str[i] && str[i].trim() ) { console.log(`6368 inside catching attr value start clauses`); if ( str[i] === "=" && !SOMEQUOTE.includes(str[rightVal as number]) && !`=`.includes(str[rightVal as number]) && !espChars.includes(str[rightVal as number]) // it might be an ESP literal ) { // find the index of the next quote, single or double const firstQuoteOnTheRightIdx = SOMEQUOTE.split("") .map((quote) => str.indexOf(quote, rightVal as number)) .filter((val) => val > 0).length ? Math.min( ...SOMEQUOTE.split("") .map((quote) => str.indexOf(quote, rightVal as number)) .filter((val) => val > 0) ) : undefined; console.log( `6387 ${`\u001b[${33}m${`firstQuoteOnTheRightIdx`}\u001b[${39}m`} = ${JSON.stringify( firstQuoteOnTheRightIdx, null, 4 )}` ); // catch attribute name - equal - attribute name - equal // <span width=height=100> if ( // there is a character on the right (otherwise value would be null) rightVal && // there is equal character in the remaining chunk str.slice(rightVal).includes("=") && // characters upto first equals form a known attribute value allHtmlAttribs.has( str .slice(rightVal, rightVal + str.slice(rightVal).indexOf("=")) .trim() .toLowerCase() ) ) { console.log(`6409 attribute ends`); // we have something like: // <span width=height=100> // 1. end the attribute attrib.attribEnds = i + 1; // 2. push and wipe console.log( `6418 ${`\u001b[${32}m${`attrib wipe, push and reset`}\u001b[${39}m`}` ); token.attribs.push({ ...attrib }); attribReset(); } else if ( // try to stop this clause: // // if there are no quotes in the remaining string !firstQuoteOnTheRightIdx || // there is one but there are equal character between here and its location str .slice(rightVal as number, firstQuoteOnTheRightIdx) .includes("=") || // if there is no second quote of that type in the remaining string !str.includes( str[firstQuoteOnTheRightIdx], firstQuoteOnTheRightIdx + 1 ) || // if string slice from quote to quote includes equal or brackets Array.from( str.slice( firstQuoteOnTheRightIdx + 1, str.indexOf( str[firstQuoteOnTheRightIdx], firstQuoteOnTheRightIdx + 1 ) ) ).some((char) => `<>=`.includes(char)) ) { console.log( `6448 case of missing opening quotes - attribute continues` ); // case of missing opening quotes attrib.attribValueStartsAt = rightVal; console.log( `6453 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValueStartsAt`}\u001b[${39}m`} = ${ attrib.attribValueStartsAt }` ); // push missing entry into layers layers.push({ type: "simple", value: null as any, position: attrib.attribValueStartsAt as any, }); console.log( `6465 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( { type: "simple", value: null, position: attrib.attribValueStartsAt, }, null, 4 )}` ); } } else if (SOMEQUOTE.includes(str[i])) { // maybe it's <span width='"100"> and it's a false opening quote, ' const nextCharIdx = rightVal; if ( // a non-whitespace character exists on the right of index i nextCharIdx && // if it is a quote character SOMEQUOTE.includes(str[nextCharIdx]) && // but opposite kind, str[i] !== str[nextCharIdx] && // and string is long enough str.length > nextCharIdx + 2 && // and remaining string contains that quote like the one on the right str.slice(nextCharIdx + 1).includes(str[nextCharIdx]) && // and to the right of it we don't have str[i] quote, // case: <span width="'100'"> (!str.indexOf(str[nextCharIdx], nextCharIdx + 1) || !right(str, str.indexOf(str[nextCharIdx], nextCharIdx + 1)) || str[i] !== str[ right( str, str.indexOf(str[nextCharIdx], nextCharIdx + 1) ) as number ]) && // and that slice does not contain equal or brackets or quote of other kind !Array.from( str.slice(nextCharIdx + 1, str.indexOf(str[nextCharIdx])) ).some((char) => `<>=${str[i]}`.includes(char)) ) { console.log(`6506 ${`\u001b[${31}m${`rogue quote!`}\u001b[${39}m`}`); // pop the layers layers.pop(); } else { // OK then... // has the quotes started (it's closing quote) or it's the opening quote? /* eslint no-lonely-if: "off" */ if (!attrib.attribOpeningQuoteAt) { console.log(`6516 all fine, mark the quote as starting`); attrib.attribOpeningQuoteAt = i; console.log( `6519 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribOpeningQuoteAt`}\u001b[${39}m`} = ${ attrib.attribOpeningQuoteAt }` ); if ( // character exists on the right str[i + 1] && // EITHER it's not the same as opening quote we're currently on (str[i + 1] !== str[i] || // OR it's a rogue quote, part of the value !ifQuoteThenAttrClosingQuote(i + 1)) ) { attrib.attribValueStartsAt = i + 1; console.log( `6534 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValueStartsAt`}\u001b[${39}m`} = ${ attrib.attribValueStartsAt }` ); } } else { // One quote exists. // <table width="100"> // ^ // /* istanbul ignore else */ if (isAttrClosing(str, attrib.attribOpeningQuoteAt, i)) { console.log(`6546`); attrib.attribClosingQuoteAt = i; console.log( `6549 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribClosingQuoteAt`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribClosingQuoteAt, null, 4 )}` ); } /* istanbul ignore else */ if (attrib.attribOpeningQuoteAt && attrib.attribClosingQuoteAt) { if (attrib.attribOpeningQuoteAt < ~-attrib.attribClosingQuoteAt) { attrib.attribValueRaw = str.slice( attrib.attribOpeningQuoteAt + 1, attrib.attribClosingQuoteAt ); console.log( `6565 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValueRaw`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValueRaw, null, 4 )}` ); } else { attrib.attribValueRaw = ""; console.log( `6574 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribValueRaw`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValueRaw, null, 4 )}` ); } attrib.attribEnds = i + 1; console.log( `6584 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribEnds`}\u001b[${39}m`} = ${ attrib.attribEnds }` ); // push and wipe console.log( `6590 ${`\u001b[${32}m${`attrib wipe, push and reset`}\u001b[${39}m`}` ); token.attribs.push(clone(attrib)); attribReset(); } console.log( `6596 now ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); } } } // else - value we assume does not start } // // // // // // "PARSING" ERROR CLAUSES // ███████████████████████ // // // // // // Catch raw closing brackets inside attribute's contents, maybe they // mean the tag ending and maybe the closing quotes are missing? if ( !doNothing && str[i] === ">" && // consider ERB templating tags like <%= @p1 %> str[i - 1] !== "%" && token.type === "tag" && attrib.attribStarts && !attrib.attribEnds ) { console.log( `6634 ${`\u001b[${31}m${`██`}\u001b[${39}m`} bracket within attribute's value` ); // Idea is simple: we have to situations: // 1. this closing bracket is real, closing bracket // 2. this closing bracket is unencoded raw text // Now, we need to distinguish these two cases. // It's easiest done traversing right until the next closing bracket. // If it's case #1, we'll likely encounter a new tag opening (or nothing). // If it's case #2, we'll likely encounter a tag closing or attribute // combo's equal+quote let thisIsRealEnding = false; if (str[i + 1]) { // Traverse then for (let y = i + 1; y < len; y++) { console.log( `6653 ${`\u001b[${36}m${`str[${y}] = ${JSON.stringify( str[y], null, 0 )}`}\u001b[${39}m`}` ); // if we reach the closing counterpart of the quotes, terminate if ( attrib.attribOpeningQuoteAt && str[y] === str[attrib.attribOpeningQuoteAt] ) { console.log( `6666 closing quote (${ str[attrib.attribOpeningQuoteAt] }) found, ${`\u001b[${31}m${`BREAK`}\u001b[${39}m`}` ); if (y !== i + 1 && str[~-y] !== "=") { thisIsRealEnding = true; console.log( `6673 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`thisIsRealEnding`}\u001b[${39}m`} = ${thisIsRealEnding}` ); } break; } else if (str[y] === ">") { // must be real tag closing, we just tackle missing quotes // TODO - missing closing quotes break; } else if (str[y] === "<") { thisIsRealEnding = true; console.log( `6684 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`thisIsRealEnding`}\u001b[${39}m`} = ${thisIsRealEnding}` ); // TODO - pop only if type === "simple" and it's the same opening // quotes of this attribute layers.pop(); console.log( `6691 ${`\u001b[${31}m${`POP`}\u001b[${39}m`} ${`\u001b[${33}m${`layers`}\u001b[${39}m`}, now:\n${JSON.stringify( layers, null, 4 )}` ); console.log(`6698 break`); break; } else if (!str[y + 1]) { // if end was reached and nothing caught, that's also positive sign thisIsRealEnding = true; console.log( `6704 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`thisIsRealEnding`}\u001b[${39}m`} = ${thisIsRealEnding}` ); console.log(`6707 break`); break; } } } else { console.log(`6712 string ends so this was the bracket`); thisIsRealEnding = true; } // // // // FINALLY, // // // // if "thisIsRealEnding" was set to "true", terminate the tag here. if (thisIsRealEnding) { token.end = i + 1; token.value = str.slice(token.start, token.end); console.log( `6729 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`token.end`}\u001b[${39}m`} = ${ token.end }` ); // set and push the attribute's records, just closing quote will be // null and possibly value too if ( attrib.attribValueStartsAt && i && attrib.attribValueStartsAt < i && str.slice(attrib.attribValueStartsAt, i).trim() ) { attrib.attribValueEndsAt = i; attrib.attribValueRaw = str.slice(attrib.attribValueStartsAt, i); if ( Array.isArray(attrib.attribValue) && attrib.attribValue.length && !attrib.attribValue[~-attrib.attribValue.length].end ) { console.log(`6751`); attrib.attribValue[~-attrib.attribValue.length].end = i; attrib.attribValue[~-attrib.attribValue.length].value = str.slice( attrib.attribValue[~-attrib.attribValue.length].start, i ); } // otherwise, nulls stay } else { attrib.attribValueStartsAt = null; } if (attrib.attribEnds === null) { attrib.attribEnds = i; console.log( `6766 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribEnds`}\u001b[${39}m`} = ${ attrib.attribEnds }` ); } if (attrib) { // 2. push and wipe console.log( `6775 ${`\u001b[${32}m${`attrib wipe, push and reset`}\u001b[${39}m`}` ); token.attribs.push(clone(attrib)); attribReset(); } } } // // // // // BOTTOM // ██████ // // // // // // // // // // // ping charCb // ------------------------------------------------------------------------- if (str[i] && opts.charCb) { console.log( `6805 ${`\u001b[${32}m${`PING`}\u001b[${39}m`} ${JSON.stringify( { type: token.type, chr: str[i], i, }, null, 4 )}` ); pingCharCb({ type: token.type, chr: str[i], i, }); } // // // // // // // // catch end of the string // ------------------------------------------------------------------------- // notice there's no "doNothing" if (!str[i] && token.start !== null) { token.end = i; token.value = str.slice(token.start, token.end); // if there is unfinished "attrib" object, submit it // as is, that's abruptly ended attribute // insurance clauses - in case text token slips through this far if (token.type !== "tag") { // maybe it's a broken code case where ESP token is set // as the main "token" and there's backed up real tag token? if (token.type === "esp" && parentTokenToBackup) { console.log( `6845 ${`\u001b[${31}m${`broken ESP token!`}\u001b[${39}m`}` ); // property by now will be already pushed to attrib, // so we check its contents directly if ( attrib && Array.isArray(attrib.attribValue) && attrib.attribValue.length && Array.isArray(attrib.attribValue[~-attrib.attribValue.length].value) ) { // push this esp token to the last attrib value (attrib.attribValue[~-attrib.attribValue.length].value as any).push( clone(token) ); console.log( `6862 SET ${`\u001b[${33}m${`attrib.attribValue`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribValue, null, 4 )}` ); // patch missing values on attrib if (!attrib.attribValueEndsAt) { attrib.attribValueEndsAt = token.end; } } token = clone(parentTokenToBackup); console.log( `6877 ${`\u001b[${32}m${`RESTORE`}\u001b[${39}m`} ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}` ); attribToBackup = undefined; parentTokenToBackup = undefined; token.attribs.push(clone(attrib)); attribReset(); } attribReset(); console.log(`6891 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`} attrib`); } else if (attrib && attrib.attribName) { console.log( `6894 FIY, ${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify( token, null, 4 )}; ${`\u001b[${33}m${`attrib`}\u001b[${39}m`} = ${JSON.stringify( attrib, null, 4 )}` ); // push and wipe console.log( `6907 ${`\u001b[${32}m${`PUSH ATTR AND WIPE`}\u001b[${39}m`}` ); // patch the attr ending if it's missing if (!attrib.attribEnds) { attrib.attribEnds = i; console.log( `6913 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`attrib.attribEnds`}\u001b[${39}m`} = ${JSON.stringify( attrib.attribEnds, null, 4 )}` ); } (token as any).attribs.push({ ...attrib }); attribReset(); } // if there was an unfinished CSS property, finish it if ( token && Array.isArray((token as RuleToken).properties) && (token as RuleToken).properties.length && !(token as RuleToken).properties[ ~-(token as RuleToken).properties.length ].end ) { (token as RuleToken).properties[ ~-(token as RuleToken).properties.length ].end = i; if ( (token as RuleToken).properties[ ~-(token as RuleToken).properties.length ].start && !(token as RuleToken).properties[ ~-(token as RuleToken).properties.length ].value ) { (token as RuleToken).properties[ ~-(token as RuleToken).properties.length ].value = str.slice( (token as RuleToken).properties[ ~-(token as RuleToken).properties.length ].start, i ); } } // if there is unfinished css property that has been // recording, end it and push it as is. That's an // abruptly ended css chunk. if (property && property.propertyStarts) { // patch property.end if (!property.end) { property.end = i; } pushProperty(property); propertyReset(); console.log( `6966 push, then ${`\u001b[${31}m${`WIPE`}\u001b[${39}m`} ${`\u001b[${33}m${`property`}\u001b[${39}m`}` ); } console.log(`6970 ${`\u001b[${32}m${`PING`}\u001b[${39}m`}`); pingTagCb(token); } // // // // // // // // Record last non-whitespace character // ------------------------------------------------------------------------- if (str[i] && str[i].trim()) { lastNonWhitespaceCharAt = i; } // // // // // // // // logging: // ------------------------------------------------------------------------- console.log( `${`\u001b[${90}m${`==========================================\n██ token: ${JSON.stringify( token, null, 4 )}${ property.propertyStarts || property.importantStarts ? `\n██ property: ${JSON.stringify(property, null, 4)}` : "" }${ attrib.attribStarts ? `\n██ attrib: ${JSON.stringify(attrib, null, 4)}` : "" }${ attribToBackup ? `\n██ attribToBackup: ${JSON.stringify(attribToBackup, null, 4)}` : "" }${ parentTokenToBackup ? `\n██ parentTokenToBackup: ${JSON.stringify( parentTokenToBackup, null, 4 )}` : "" }${ layers.length ? `\n██ layers: ${JSON.stringify(layers, null, 4)}` : "" }`}\u001b[${39}m`}${ doNothing ? `\n${`\u001b[${31}m${`DO NOTHING UNTIL ${doNothing}`}\u001b[${39}m`}` : "" }` ); console.log( `${`\u001b[${90}m${`withinStyle = ${withinStyle}`}\u001b[${39}m`} ${`\u001b[${90}m${`withinStyleComment = ${withinStyleComment}`}\u001b[${39}m`} ${`\u001b[${90}m${`withinScript = ${withinScript}`}\u001b[${39}m`}` ); console.log( `${`\u001b[${90}m${`selectorChunkStartedAt = ${selectorChunkStartedAt}`}\u001b[${39}m`}` ); console.log(`${`\u001b[${90}m${`rightVal = ${rightVal}`}\u001b[${39}m`}`); console.log( `${`\u001b[${90}m${`lastNonWhitespaceCharAt = ${lastNonWhitespaceCharAt}`}\u001b[${39}m`}` ); console.log( `${ parentTokenToBackup ? `${`\u001b[${90}m${`parentTokenToBackup = ${JSON.stringify( parentTokenToBackup, null, 4 )}`}\u001b[${39}m`}` : "" }` ); console.timeEnd(`\u001b[${90}m${`loop iteration`}\u001b[${39}m`); } // // finally, clear stashes // if (charStash.length) { console.log( `7061 FINALLY, clear ${`\u001b[${33}m${`charStash`}\u001b[${39}m`}` ); for (let i = 0, len2 = charStash.length; i < len2; i++) { reportFirstFromStash(charStash, opts.charCb, opts.charCbLookahead); console.log( `7066 ${`\u001b[${90}m${`██ charStash`}\u001b[${39}m`} = ${JSON.stringify( charStash, null, 4 )}` ); } } if (tagStash.length) { console.log( `7077 FINALLY, clear ${`\u001b[${33}m${`tagStash`}\u001b[${39}m`}` ); for (let i = 0, len2 = tagStash.length; i < len2; i++) { reportFirstFromStash(tagStash, opts.tagCb, opts.tagCbLookahead); console.log( `7082 ${`\u001b[${90}m${`██ tagStash`}\u001b[${39}m`} = ${JSON.stringify( tagStash, null, 4 )}` ); } } // return stats const timeTakenInMilliseconds = Date.now() - start; console.log(" "); console.log( `7095 ${`\u001b[${35}m${`██`}\u001b[${39}m`} ${`\u001b[${33}m${`timeTakenInMilliseconds`}\u001b[${39}m`} = ${JSON.stringify( timeTakenInMilliseconds, null, 4 )}` ); console.log(" "); return { timeTakenInMilliseconds, }; } // ----------------------------------------------------------------------------- // export some util functions for testing purposes because sources are in TS // and unit test runners can't read TS const util = { matchLayerLast }; export { tokenizer, defaults, version, util };
the_stack
import * as React from "react"; import { Scene, DepthOfFieldEffectBlurLevel, ImageProcessingConfiguration } from "babylonjs"; import { Inspector, IObjectInspectorProps } from "../../components/inspector"; import { InspectorList } from "../../gui/inspector/fields/list"; import { InspectorColor } from "../../gui/inspector/fields/color"; import { InspectorNumber } from "../../gui/inspector/fields/number"; import { InspectorSection } from "../../gui/inspector/fields/section"; import { InspectorBoolean } from "../../gui/inspector/fields/boolean"; import { InspectorVector2 } from "../../gui/inspector/fields/vector2"; import { SceneSettings } from "../../scene/settings"; import { AbstractInspector } from "../abstract-inspector"; export interface IRendererInspectorState { /** * Defines wether or not SSAO 2 is enabled. */ ssao2Enabled: boolean; /** * Defines wether or not Motion Blur is enabled. */ motionBlurEnabled: boolean; /** * Defines wether or not SSR is enabled. */ ssrEnabled: boolean; /** * Defines the configuration of the default pipleine. */ default: { /** * Defines wether or not the default rendering pipleine is enabled. */ enabled: boolean; /** * Defines wether or not image processing is enabled. */ imageProcessingEnabled: boolean; /** * Defines wether or not bloom is enabled */ bloomEnabled: boolean; /** * Defines wether or not sharpen is enabled. */ sharpenEnabled: boolean; /** * Defines wether or not DOF is enabled. */ depthOfFieldEnabled: boolean; /** * Defines wether or not Chromatic Aberration is enabled. */ chromaticAberrationEnabled: boolean; /** * Defines wether or not grain is enabled. */ grainEnabled: boolean; /** * Defines wether or not glow is enabled. */ glowEnabled: boolean; /** * Defines wether or not vignette is enabled. */ vignetteEnabled: boolean; }; } export class RenderingInspector extends AbstractInspector<Scene, IRendererInspectorState> { /** * Constructor. * @param props defines the component's props. */ public constructor(props: IObjectInspectorProps) { super(props); this.state = { ssao2Enabled: SceneSettings.IsSSAOEnabled(), motionBlurEnabled: SceneSettings.IsMotionBlurEnabled(), ssrEnabled: SceneSettings.IsScreenSpaceReflectionsEnabled(), default: this._getDefaultState(), }; } /** * Renders the content of the inspector. */ public renderContent(): React.ReactNode { return ( <> {this._getSSAO2Inspector()} {this._getMotionBlurInspector()} {this._getSSRInspector()} {this._getDefaultInspector()} </> ); } /** * Returns the SSAO2 inspector used to configure the SSAO 2 post-process. */ private _getSSAO2Inspector(): React.ReactNode { const enable = <InspectorBoolean object={this.state} property="ssao2Enabled" label="Enabled" onChange={(v) => { SceneSettings.SetSSAOEnabled(this.editor, this.state.ssao2Enabled); this.setState({ ssao2Enabled: v }); }} /> if (!this.state.ssao2Enabled || !SceneSettings.SSAOPipeline) { return ( <InspectorSection title="SSAO 2"> {enable} </InspectorSection> ); } return ( <InspectorSection title="SSAO 2"> {enable} <InspectorNumber object={SceneSettings.SSAOPipeline} property="radius" label="Radius" step={0.01} /> <InspectorNumber object={SceneSettings.SSAOPipeline} property="totalStrength" label="Strength" step={0.01} /> <InspectorNumber object={SceneSettings.SSAOPipeline} property="samples" label="Samples" step={1} min={1} max={32} /> <InspectorNumber object={SceneSettings.SSAOPipeline} property="maxZ" label="Max Z" step={0.01} /> <InspectorBoolean object={SceneSettings.SSAOPipeline} property="expensiveBlur" label="Expansive Blur" /> </InspectorSection> ); } /** * Returns the Motion Blur inspector used to configure the Motion Blur post-process. */ private _getMotionBlurInspector(): React.ReactNode { const enable = <InspectorBoolean object={this.state} property="motionBlurEnabled" label="Enabled" onChange={(v) => { SceneSettings.SetMotionBlurEnabled(this.editor, this.state.motionBlurEnabled); this.setState({ motionBlurEnabled: v }); }} /> if (!this.state.motionBlurEnabled || !SceneSettings.MotionBlurPostProcess) { return ( <InspectorSection title="Motion Blur"> {enable} </InspectorSection> ); } return ( <InspectorSection title="Motion Blur"> {enable} <InspectorNumber object={SceneSettings.MotionBlurPostProcess} property="motionStrength" label="Strength" step={0.01} /> <InspectorNumber object={SceneSettings.MotionBlurPostProcess} property="motionBlurSamples" label="Samples" step={1} min={1} max={64} /> <InspectorBoolean object={SceneSettings.MotionBlurPostProcess} property="isObjectBased" label="Object Based" /> </InspectorSection> ); } /** * Returns the SSE inspector used to configure the Screen-Space-Reflections post-process. */ private _getSSRInspector(): React.ReactNode { const enable = <InspectorBoolean object={this.state} property="ssrEnabled" label="Enabled" onChange={(v) => { SceneSettings.SetScreenSpaceReflectionsEnabled(this.editor, this.state.ssrEnabled); this.setState({ ssrEnabled: v }); }} /> if (!this.state.ssrEnabled || !SceneSettings.ScreenSpaceReflectionsPostProcess) { return ( <InspectorSection title="Screen Space Reflections"> {enable} </InspectorSection> ); } return ( <InspectorSection title="Screen Space Reflections"> {enable} <InspectorNumber object={SceneSettings.ScreenSpaceReflectionsPostProcess} property="strength" label="Strength" step={0.01} /> <InspectorNumber object={SceneSettings.ScreenSpaceReflectionsPostProcess} property="threshold" label="Threshold" step={0.01} /> <InspectorNumber object={SceneSettings.ScreenSpaceReflectionsPostProcess} property="step" label="Step" step={0.001} /> <InspectorNumber object={SceneSettings.ScreenSpaceReflectionsPostProcess} property="reflectionSpecularFalloffExponent" label="Specular Exponent" step={0.001} /> <InspectorNumber object={SceneSettings.ScreenSpaceReflectionsPostProcess} property="reflectionSamples" label="Samples" step={1} min={1} max={512} /> <InspectorNumber object={SceneSettings.ScreenSpaceReflectionsPostProcess} property="roughnessFactor" label="Roughness Factor" step={0.01} min={0} max={10} /> <InspectorSection title="Smooth"> <InspectorBoolean object={SceneSettings.ScreenSpaceReflectionsPostProcess} property="enableSmoothReflections" label="Enable" /> <InspectorNumber object={SceneSettings.ScreenSpaceReflectionsPostProcess} property="smoothSteps" label="Steps" step={1} min={0} max={32} /> </InspectorSection> </InspectorSection> ); } /** * Returns the default inspector used to configure the default rendering pipleline of Babylon.JS. */ private _getDefaultInspector(): React.ReactNode { const enable = <InspectorBoolean object={this.state.default} property="enabled" label="Enabled" onChange={() => { SceneSettings.SetDefaultPipelineEnabled(this.editor, this.state.default.enabled); this._updateDefaultState(); }} /> if (!this.state.default.enabled || !SceneSettings.DefaultPipeline) { return ( <InspectorSection title="Default Pipeline"> {enable} </InspectorSection> ); } const imageProcessingEnable = <InspectorBoolean object={SceneSettings.DefaultPipeline} property="imageProcessingEnabled" label="Enabled" onChange={() => this._updateDefaultState()} />; const imageProcessing = this.state.default.imageProcessingEnabled ? ( <InspectorSection title="Image Processing"> {imageProcessingEnable} <InspectorNumber object={SceneSettings.DefaultPipeline.imageProcessing} property="exposure" label="Exposure" step={0.01} /> <InspectorNumber object={SceneSettings.DefaultPipeline.imageProcessing} property="contrast" label="Contrast" step={0.01} /> <InspectorBoolean object={SceneSettings.DefaultPipeline.imageProcessing} property="toneMappingEnabled" label="Tone Mapping Enabled" /> <InspectorBoolean object={SceneSettings.DefaultPipeline.imageProcessing} property="fromLinearSpace" label="From Linear Space" /> </InspectorSection> ) : ( <InspectorSection title="Image Processing"> {imageProcessingEnable} </InspectorSection> ); const bloomEnable = <InspectorBoolean object={SceneSettings.DefaultPipeline} property="bloomEnabled" label="Enabled" onChange={() => this._updateDefaultState()} />; const bloom = this.state.default.bloomEnabled ? ( <InspectorSection title="Bloom"> {bloomEnable} <InspectorNumber object={SceneSettings.DefaultPipeline} property="bloomKernel" label="Kernel" step={1} min={1} max={512} /> <InspectorNumber object={SceneSettings.DefaultPipeline} property="bloomWeight" label="Weight" step={0.01} min={0} max={1} /> <InspectorNumber object={SceneSettings.DefaultPipeline} property="bloomThreshold" label="Threshold" step={0.01} min={0} max={1} /> <InspectorNumber object={SceneSettings.DefaultPipeline} property="bloomScale" label="Scale" step={0.01} min={0} max={1} /> </InspectorSection> ) : ( <InspectorSection title="Bloom"> {bloomEnable} </InspectorSection> ); const sharpenEnable = <InspectorBoolean object={SceneSettings.DefaultPipeline} property="sharpenEnabled" label="Enabled" onChange={() => this._updateDefaultState()} />; const sharpen = this.state.default.sharpenEnabled ? ( <InspectorSection title="Sharpen"> {sharpenEnable} <InspectorNumber object={SceneSettings.DefaultPipeline.sharpen} property="edgeAmount" label="Edge Amount" step={0.01} min={0} max={2} /> <InspectorNumber object={SceneSettings.DefaultPipeline.sharpen} property="colorAmount" label="Color Amount" step={0.01} min={0} max={2} /> </InspectorSection> ) : ( <InspectorSection title="Sharpen"> {sharpenEnable} </InspectorSection> ); const depthOfFieldEnable = <InspectorBoolean object={SceneSettings.DefaultPipeline} property="depthOfFieldEnabled" label="Enabled" onChange={() => this._updateDefaultState()} />; const depthOfField = this.state.default.depthOfFieldEnabled ? ( <InspectorSection title="Depth Of Field"> {depthOfFieldEnable} <InspectorNumber object={SceneSettings.DefaultPipeline.depthOfField} property="focusDistance" label="Focus Distance" step={1} min={0} /> <InspectorNumber object={SceneSettings.DefaultPipeline.depthOfField} property="fStop" label="F-Stop" step={0.01} min={0} /> <InspectorNumber object={SceneSettings.DefaultPipeline.depthOfField} property="focalLength" label="Focal Length" step={0.01} min={0} /> <InspectorList object={SceneSettings.DefaultPipeline} property="depthOfFieldBlurLevel" label="Blur Level" items={[ { label: "Low", data: DepthOfFieldEffectBlurLevel.Low }, { label: "Medium", data: DepthOfFieldEffectBlurLevel.Medium }, { label: "High", data: DepthOfFieldEffectBlurLevel.High }, ]} onChange={() => { this.forceUpdate(); }} /> </InspectorSection> ) : ( <InspectorSection title="Depth Of Field"> {depthOfFieldEnable} </InspectorSection> ); const chromaticAberrationEnable = <InspectorBoolean object={SceneSettings.DefaultPipeline} property="chromaticAberrationEnabled" label="Enabled" onChange={() => this._updateDefaultState()} />; const chromaticAberraction = this.state.default.chromaticAberrationEnabled ? ( <InspectorSection title="Chromatic Aberration"> {chromaticAberrationEnable} <InspectorNumber object={SceneSettings.DefaultPipeline.chromaticAberration} property="aberrationAmount" label="Amount" step={0.01} /> <InspectorNumber object={SceneSettings.DefaultPipeline.chromaticAberration} property="radialIntensity" label="Radial Intensity" step={0.01} /> <InspectorVector2 object={SceneSettings.DefaultPipeline.chromaticAberration} property="direction" label="Direction" step={0.01} /> <InspectorVector2 object={SceneSettings.DefaultPipeline.chromaticAberration} property="centerPosition" label="Center" step={0.01} /> </InspectorSection> ) : ( <InspectorSection title="Chromatic Aberration"> {chromaticAberrationEnable} </InspectorSection> ); const grainEnabled = <InspectorBoolean object={SceneSettings.DefaultPipeline} property="grainEnabled" label="Enabled" onChange={() => this._updateDefaultState()} />; const grain = this.state.default.grainEnabled ? ( <InspectorSection title="Grain"> {grainEnabled} <InspectorNumber object={SceneSettings.DefaultPipeline.grain} property="intensity" label="Intensity" min={0} step={0.01} /> <InspectorBoolean object={SceneSettings.DefaultPipeline.grain} property="animated" label="Animated" /> </InspectorSection> ) : ( <InspectorSection title="Grain"> {grainEnabled} </InspectorSection> ); const glowLayerEnabled = <InspectorBoolean object={SceneSettings.DefaultPipeline} property="glowLayerEnabled" label="Enabled" onChange={() => this._updateDefaultState()} />; const glow = this.state.default.glowEnabled ? ( <InspectorSection title="Glow Layer"> {glowLayerEnabled} <InspectorNumber object={SceneSettings.DefaultPipeline.glowLayer} property="blurKernelSize" label="Blur Kernel Size" min={1} max={512} step={1} /> <InspectorNumber object={SceneSettings.DefaultPipeline.glowLayer} property="intensity" label="Intensity" min={0} step={0.01} /> </InspectorSection> ) : ( <InspectorSection title="Glow Layer"> {glowLayerEnabled} </InspectorSection> ); let vignette: React.ReactNode = null; if (SceneSettings.DefaultPipeline.imageProcessingEnabled) { const vignetteEnabled = <InspectorBoolean object={SceneSettings.DefaultPipeline.imageProcessing} property="vignetteEnabled" label="Enabled" onChange={() => this._updateDefaultState()} />; vignette = this.state.default.vignetteEnabled ? ( <InspectorSection title="Vignette"> {vignetteEnabled} <InspectorList object={SceneSettings.DefaultPipeline.imageProcessing} property="vignetteBlendMode" label="Blend Mode" items={[ { label: "Multiply", data: ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY }, { label: "Opaque", data: ImageProcessingConfiguration.VIGNETTEMODE_OPAQUE }, ]} /> <InspectorNumber object={SceneSettings.DefaultPipeline.imageProcessing} property="vignetteWeight" label="Weight" step={0.01} /> <InspectorColor object={SceneSettings.DefaultPipeline.imageProcessing} property="vignetteColor" label="Color" step={0.01} /> </InspectorSection> ) : ( <InspectorSection title="Vignette"> {vignetteEnabled} </InspectorSection> ); } return ( <InspectorSection title="Default Pipeline"> {enable} <InspectorSection title="Anti Aliasing"> <InspectorBoolean object={SceneSettings.DefaultPipeline} property="fxaaEnabled" label="FXAA Enabled" /> <InspectorNumber object={SceneSettings.DefaultPipeline} property="samples" label="Samples" step={1} min={1} max={32} /> </InspectorSection> {imageProcessing} {bloom} {sharpen} {depthOfField} {chromaticAberraction} {vignette} {grain} {glow} </InspectorSection> ); } /** * Returns the new state of the default pipeline. */ private _getDefaultState(): IRendererInspectorState["default"] { return { enabled: SceneSettings.IsDefaultPipelineEnabled(), imageProcessingEnabled: SceneSettings.DefaultPipeline?.imageProcessingEnabled ?? false, bloomEnabled: SceneSettings.DefaultPipeline?.bloomEnabled ?? false, sharpenEnabled: SceneSettings.DefaultPipeline?.sharpenEnabled ?? false, depthOfFieldEnabled: SceneSettings.DefaultPipeline?.depthOfFieldEnabled ?? false, chromaticAberrationEnabled: SceneSettings.DefaultPipeline?.chromaticAberrationEnabled ?? false, grainEnabled: SceneSettings.DefaultPipeline?.grainEnabled ?? false, glowEnabled: SceneSettings.DefaultPipeline?.glowLayerEnabled ?? false, vignetteEnabled: SceneSettings.DefaultPipeline?.imageProcessing?.vignetteEnabled ?? false, } } /** * Updates the default rendering pipeline state. */ private _updateDefaultState(): void { this.setState({ default: { ...this.state.default, ...this._getDefaultState(), }, }); } } Inspector.RegisterObjectInspector({ ctor: RenderingInspector, ctorNames: ["Scene"], title: "Rendering", });
the_stack
///<reference path="./typings/bundle.d.ts"/> ///<reference path="./typings/serialport.d.ts" /> ///<reference path="./typings/config.d.ts" /> ///<reference path="./typings/node-static.d.ts" /> ///<reference path="./typings/http2.ts" /> ///<reference path="./typings/ip-range-check.ts" /> import * as websocket from 'websocket'; import { Grbl, STATE_IDLE, GrblVersion, GrblLineParserResultStartup, GrblLineParserResultOk, GrblLineParserResultError, GrblLineParserResultAlarm, GrblLineParserResultFeedback, GrblLineParserResultDollar, GrblLineParserResultStatus, GrblSerialPortError, } from './grbl'; import http = require('http'); import http2 = require('http2'); import fs = require('fs'); import serialport = require("serialport"); import config = require("config"); import path = require("path"); import staticFiles = require("node-static"); import ipRangeCheck = require("ip-range-check"); interface GrblServerConfig { serialPort: string; serialBaud: number; serverPort: number; TLSKey: string; TLSCert: string; }; interface GrblConfig { '$0': string; '$1': string; '$2': string; '$3': string; '$4': string; '$5': string; '$6': string; '$10': string; '$11': string; '$12': string; '$13': string; '$20': string; '$21': string; '$22': string; '$23': string; '$24': string; '$25': string; '$26': string; '$27': string; '$100': string; '$101': string; '$102': string; '$110': string; '$111': string; '$112': string; '$120': string; '$121': string; '$122': string; '$130': string; '$131': string; '$132': string; } interface JSONRPCRequest { method: string; params: any; id: number; } interface JSONRPCResponse { result?: any; error?: JSONRPCError; id: number; } interface JSONRPCError { code: number; message?: string; data?: any; } const JSONRPCErrorParseError = <JSONRPCError>{ code: -32700, message: 'Parse Error' }; const JSONRPCErrorInvalidRequest = <JSONRPCError>{ code: -32600, message: 'Invalid Request' }; const JSONRPCErrorMethodNotFound = <JSONRPCError>{ code: -32601, message: 'Method not found' }; const JSONRPCErrorInvalidParams = <JSONRPCError>{ code: -32602, message: 'Invalid params' }; const JSONRPCErrorInternalError = <JSONRPCError>{ code: -32603, message: 'Internal error' }; class JSONRPCErrorServerError implements JSONRPCError { code: number; /* -32000 to -32099 */ message: string; data: any; constructor(code: number, message: string, data: any) { this.code = code; this.message = message; this.data = data; } } class JSONRPCErrorGrblError extends JSONRPCErrorServerError { constructor(data: any) { super(-32000, "Error on grbl", data); } } class JSONRPCErrorNotIdleError extends JSONRPCErrorServerError { constructor(data: any) { super(-32001, "Grbl state is not idle", data); } } class GCode { name : string; sent : Array<string>; remain: Array<string>; total: number; createdTime: number; startedTime : number = null; finishedTime : number = null; constructor(name: string, gcode: string) { this.name = name; this.sent = []; this.remain = gcode.split(/\n/); this.total = this.remain.length; this.createdTime = new Date().getTime(); } } export class GrblServer { rev: String; grblVersion: GrblVersion; httpServer : http.Server; http2Server : http.Server; wsServer : websocket.server; wssServer : websocket.server; sessions : Array<websocket.connection>; grbl : Grbl; grblConfig: GrblConfig; serverConfig: GrblServerConfig; gcode: GCode; start() { this.loadConfig(); this.startHttp(); this.startWebSocket(); this.openSerialPort(); } loadConfig() { this.serverConfig = <GrblServerConfig>{ serverPort: config.get('serverPort'), serialPort: config.get('serialPort'), serialBaud: config.get('serialBaud'), TLSKey: config.get('TLSKey'), TLSCert: config.get('TLSCert'), }; this.rev = fs.readFileSync('out/rev.txt', 'utf-8'); console.log('Launching with this config: '); console.log(this.serverConfig); } startHttp() { var fileServer = new staticFiles.Server('./browser', { cache: 3600 * 24 * 30 }); var handler = (req : http.IncomingMessage, res : http.ServerResponse) => { if (req.url === '/config') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(this.serverConfig)); } else { fileServer.serve(req, res); } }; console.log('startHttp'); this.httpServer = http.createServer(handler); this.httpServer.listen(this.serverConfig.serverPort, () => { console.log('Server is listening on port ' + this.serverConfig.serverPort); }); if (this.serverConfig.TLSKey) { this.http2Server = http2.createServer({ key: fs.readFileSync(this.serverConfig.TLSKey), cert: fs.readFileSync(this.serverConfig.TLSCert) }, handler); var http2port = this.serverConfig.serverPort - 80 + 443; this.http2Server.listen(http2port, () => { console.log('Server is listening on port ' + http2port); }); } } startWebSocket() { console.log('startWebSocket'); this.sessions = []; this.wsServer = this._startWebSocket(this.httpServer); if (this.http2Server) { this.wssServer = this._startWebSocket(this.http2Server); } } _startWebSocket(server: http.Server):websocket.server { var wsServer = new websocket.server({ httpServer: server, maxReceivedFrameSize: 131072, maxReceivedMessageSize: 10 * 1024 * 1024, autoAcceptConnections: false }); wsServer.on('request', (req) => { var allowed = ipRangeCheck(req.remoteAddress, [ '127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '::1/128', 'fe80::/10', 'fc00::/7', ]); if (!allowed) { req.reject(); console.log('Connection from origin ' + req.remoteAddress + ' rejected.'); return; } var connection: websocket.connection; try { connection = req.accept(null, req.origin); } catch (e) { console.log(e); return; } console.log('Connection accepted. from:' + req.remoteAddress + ' origin:' + req.origin); this.sessions.push(connection); this.sendInitialMessage(connection); connection.on('message', (message) => { console.log(message); try { if (message.type !== 'utf8') return; console.log('Req: ' + message.utf8Data); var req: JSONRPCRequest; try { req = JSON.parse(message.utf8Data); } catch (e) { this.sendMessage(connection, { id: null, error: JSONRPCErrorParseError, }); } console.log('request ', req.method); var method: (params: any)=>Promise<any> = (<any>this)['service_' + req.method]; if (!method) { this.sendMessage(connection, { id: req.id, error: JSONRPCErrorMethodNotFound, }); } method.call(this, req.params || {}). then( (result: any) => { this.sendMessage(connection, { id: req.id, result: result || null }); }, (error: JSONRPCErrorServerError) => { this.sendMessage(connection, { id: req.id, error: error || null }); }); } catch (e) { this.sendMessage(connection, { id: null, error: JSONRPCErrorInternalError, }); } }); connection.on('frame', (frame: websocket.frame) => { console.log(frame); }); connection.on('error', (e) => { console.log(e); }); connection.on('close', (reasonCode, description) => { console.log('Peer ' + connection.remoteAddress + ' disconnected.', reasonCode, description); this.sessions.splice(this.sessions.indexOf(connection), 1); console.log(this.sessions); }); }); return wsServer; } sendInitialMessage(connection: websocket.connection) { this.sendMessage(connection, { id: null, result: { type: 'init', lastAlarm: this.grbl.lastAlarm ? this.grbl.lastAlarm.message : null, lastFeedback: this.grbl.lastFeedback ? this.grbl.lastFeedback.message : null, status: this.grbl.status, serverRev: this.rev, grblVersion: this.grblVersion, } }); if (this.grblConfig) { this.sendMessage(connection, { id: null, result: { type: 'config', config: this.grblConfig } }); } else { this.getConfig(); } this.sendMessage(connection, { id: null, result: { type: 'gcode', gcode: this.gcode, } }); } sendMessage(connection: websocket.connection, response: JSONRPCResponse) { connection.sendUTF(JSON.stringify(response)); } sendBroadcastMessage(message: any) { for (let i = 0, it: websocket.connection; it = this.sessions[i]; i++) { this.sendMessage(it, message); } } service_upload(params: any): Promise<any> { return new Promise( (resolve, reject) => { if (this.gcode) { reject(new JSONRPCErrorNotIdleError(this.grbl.status.state)); return; } // load new gcode this.gcode = new GCode(params.name, params.gcode); console.log('New gcode uploaded: ', this.gcode.remain.length, 'lines'); this.sendBroadcastMessage({ id: null, result: { type: 'gcode', gcode: this.gcode, } }); resolve(); }); } service_gcode(params: any): Promise<any> { return new Promise( (resolve, reject) => { if (params.execute) { this.gcode.startedTime = new Date().getTime(); this.sendOneLine(); this.sendBroadcastMessage({ id: null, result: { type: 'gcode.start', time: this.gcode.startedTime, } }); resolve(); } else if (params.clear) { this.gcode = null; this.sendBroadcastMessage({ id: null, result: { type: 'gcode', gcode: this.gcode, } }); } else { resolve({ type: 'gcode', gcode: this.gcode, }); } }); } service_config(params: any): Promise<GrblConfig> { return Promise.resolve(this.grblConfig); } service_command(params: any): Promise<any> { if (params.command === '$$') { return this.getConfig(); } else { return this.grbl.command(params.command); } } service_reset(params: any): Promise<any> { return new Promise( (resolve, reject) => { this.grbl.reset(); resolve(); }); } service_resume(params: any): Promise<any> { return new Promise( (resolve, reject) => { this.grbl.realtimeCommand('~'); resolve(); }); } service_pause(params: any): Promise<any> { return new Promise( (resolve, reject) => { this.grbl.realtimeCommand('!'); resolve(); }); } openSerialPort() { console.log('openSerialPort'); var sp = new serialport.SerialPort(this.serverConfig.serialPort, { baudrate: this.serverConfig.serialBaud, parser: serialport.parsers.readline("\n") }, false); this.grbl = new Grbl(sp); this.grbl.open(); this.grbl.on('startup', (res: GrblLineParserResultStartup) => { this.initializeGrbl(); this.grblVersion = res.version; this.sendBroadcastMessage({ id: null, result: res.toObject({ type: 'startup', version: res.version, }), }); this.sendBroadcastMessage({ id: null, result: { type: 'gcode', gcode: null, } }); }); this.grbl.on('statuschange', (status: GrblLineParserResultStatus) => { console.log('statuschange'); this.sendBroadcastMessage({ id: null, result: { type: 'status', status: status } }); }); this.grbl.on('alarm', (res: GrblLineParserResultAlarm) => { this.sendBroadcastMessage({ id: null, result: res.toObject({ type: 'alarm', }), }); }); this.grbl.on('feedback', (res: GrblLineParserResultFeedback) => { this.sendBroadcastMessage({ id: null, result: res.toObject({ type: 'feedback', }), }); }); this.grbl.on('error', (e: GrblSerialPortError) => { console.log('Error on grbl: ' + e); this.sendBroadcastMessage({ id: null, error: new JSONRPCErrorGrblError(e.message), }); setTimeout( () => { this.openSerialPort(); }, 5000); }); } destory() { this.grbl.close(); } initializeGrbl() { this.gcode = null; this.getConfig(); } getConfig():Promise<GrblConfig> { return new Promise( (resolve, reject) => { this.grbl.getConfig(). then( (res) => { var results: any = {}; for (var i = 0, it: GrblLineParserResultDollar; (it = res[i]); i++) { var match: Array<any> = it.raw.match(/([^=]+)=([^\s]+)/) if (!match) { console.log('unexpected line: ', it); return; } results[ match[1] ] = match[2]; } this.grblConfig = results; this.sendBroadcastMessage({ id: null, result: { type: 'config', config: this.grblConfig } }); resolve(res); }, (e) => { }); }); } sendOneLine() { if (!this.gcode) { return; } if (!this.gcode.remain.length) { this.gcode.finishedTime = new Date().getTime(); // done this.sendBroadcastMessage({ id: null, result: { type: 'gcode.done', time: this.gcode.finishedTime, } }); return; } var code = this.gcode.remain.shift(); this.gcode.sent.push(code); this.sendBroadcastMessage({ id: null, result: { type: 'gcode.progress', gcode: code, } }); this.grbl.command(code). then( () => { this.sendOneLine(); }, (e) => { this.sendOneLine(); console.log('Error on sending gcode:' + e); this.sendBroadcastMessage({ id: null, error: new JSONRPCErrorGrblError(e.message), }); }); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { AlertRules } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { MonitorClient } from "../monitorClient"; import { AlertRuleResource, AlertRulesListByResourceGroupOptionalParams, AlertRulesListBySubscriptionOptionalParams, AlertRulesCreateOrUpdateOptionalParams, AlertRulesCreateOrUpdateResponse, AlertRulesDeleteOptionalParams, AlertRulesGetOptionalParams, AlertRulesGetResponse, AlertRuleResourcePatch, AlertRulesUpdateOptionalParams, AlertRulesUpdateResponse, AlertRulesListByResourceGroupResponse, AlertRulesListBySubscriptionResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing AlertRules operations. */ export class AlertRulesImpl implements AlertRules { private readonly client: MonitorClient; /** * Initialize a new instance of the class AlertRules class. * @param client Reference to the service client */ constructor(client: MonitorClient) { this.client = client; } /** * List the classic metric alert rules within a resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: AlertRulesListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<AlertRuleResource> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: AlertRulesListByResourceGroupOptionalParams ): AsyncIterableIterator<AlertRuleResource[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: AlertRulesListByResourceGroupOptionalParams ): AsyncIterableIterator<AlertRuleResource> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * List the classic metric alert rules within a subscription. * @param options The options parameters. */ public listBySubscription( options?: AlertRulesListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<AlertRuleResource> { const iter = this.listBySubscriptionPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listBySubscriptionPagingPage(options); } }; } private async *listBySubscriptionPagingPage( options?: AlertRulesListBySubscriptionOptionalParams ): AsyncIterableIterator<AlertRuleResource[]> { let result = await this._listBySubscription(options); yield result.value || []; } private async *listBySubscriptionPagingAll( options?: AlertRulesListBySubscriptionOptionalParams ): AsyncIterableIterator<AlertRuleResource> { for await (const page of this.listBySubscriptionPagingPage(options)) { yield* page; } } /** * Creates or updates a classic metric alert rule. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param ruleName The name of the rule. * @param parameters The parameters of the rule to create or update. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, ruleName: string, parameters: AlertRuleResource, options?: AlertRulesCreateOrUpdateOptionalParams ): Promise<AlertRulesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, ruleName, parameters, options }, createOrUpdateOperationSpec ); } /** * Deletes a classic metric alert rule * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param ruleName The name of the rule. * @param options The options parameters. */ delete( resourceGroupName: string, ruleName: string, options?: AlertRulesDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, ruleName, options }, deleteOperationSpec ); } /** * Gets a classic metric alert rule * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param ruleName The name of the rule. * @param options The options parameters. */ get( resourceGroupName: string, ruleName: string, options?: AlertRulesGetOptionalParams ): Promise<AlertRulesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, ruleName, options }, getOperationSpec ); } /** * Updates an existing classic metric AlertRuleResource. To update other fields use the CreateOrUpdate * method. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param ruleName The name of the rule. * @param alertRulesResource Parameters supplied to the operation. * @param options The options parameters. */ update( resourceGroupName: string, ruleName: string, alertRulesResource: AlertRuleResourcePatch, options?: AlertRulesUpdateOptionalParams ): Promise<AlertRulesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, ruleName, alertRulesResource, options }, updateOperationSpec ); } /** * List the classic metric alert rules within a resource group. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: AlertRulesListByResourceGroupOptionalParams ): Promise<AlertRulesListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * List the classic metric alert rules within a subscription. * @param options The options parameters. */ private _listBySubscription( options?: AlertRulesListBySubscriptionOptionalParams ): Promise<AlertRulesListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.AlertRuleResource }, 201: { bodyMapper: Mappers.AlertRuleResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters1, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.ruleName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.ruleName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AlertRuleResource }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.ruleName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules/{ruleName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.AlertRuleResource }, 201: { bodyMapper: Mappers.AlertRuleResource }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.alertRulesResource, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.ruleName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/alertrules", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AlertRuleResourceCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Insights/alertrules", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AlertRuleResourceCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion1], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer };
the_stack