text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Disposable, commands, window, TreeView, ViewColumn, WebviewPanel } from "vscode";
import { TreeNode } from "../models/TreeNode";
import { Tree100DoCProvider, connectDoCTreeView } from "../tree/Tree100DoCProvider";
import { addLogToJson, editLogEntry, updateLogShare } from "./LogsUtil";
import {
checkDaysMilestones,
checkLanguageMilestonesAchieved,
checkCodeTimeMetricsMilestonesAchieved,
updateMilestoneShare,
checkSharesMilestones,
} from "./MilestonesUtil";
import { getAddLogHtmlString } from "./AddLogUtil";
import { getUpdatedDashboardHtmlString, getCertificateHtmlString } from "./DashboardUtil";
import { displayReadmeIfNotExists, displayLoginPromptIfNotLoggedIn, isLoggedIn, checkIfNameChanged } from "./Util";
import { getUpdatedMilestonesHtmlString } from "./MilestonesTemplateUtil";
import { fetchSummary } from "./SummaryDbUtil";
import { getUpdatedLogsHtml } from "./LogsTemplateUtil";
import { TrackerManager } from "../managers/TrackerManager";
import { deleteLogDay, syncLogs } from "./LogsUtil";
import { MilestoneEventManager } from "../managers/MilestoneEventManager";
import { YES_LABEL } from "./Constants";
import { restartChallenge } from "./SummaryUtil";
let currentTitle: string = "";
export function reloadCurrentView() {
if (currentTitle) {
switch (currentTitle) {
case "Logs":
commands.executeCommand("DoC.viewLogs");
break;
case "Dashboard":
commands.executeCommand("DoC.viewDashboard");
break;
case "Milestones":
commands.executeCommand("DoC.viewMilestones");
break;
}
}
}
export function createCommands(): { dispose: () => void } {
let cmds: any[] = [];
let currentPanel: WebviewPanel | undefined = undefined;
const Doc100SftwProvider = new Tree100DoCProvider();
const Doc100SftwTreeView: TreeView<TreeNode> = window.createTreeView("100-days-of-code-view", {
treeDataProvider: Doc100SftwProvider,
showCollapseAll: true,
});
Doc100SftwProvider.bindView(Doc100SftwTreeView);
cmds.push(connectDoCTreeView(Doc100SftwTreeView));
cmds.push(
commands.registerCommand("DoC.ViewReadme", () => {
displayReadmeIfNotExists(true);
})
);
cmds.push(
commands.registerCommand("DoC.revealTree", () => {
Doc100SftwProvider.revealTree();
})
);
cmds.push(
commands.registerCommand("DoC.viewLogs", async () => {
// check if the user has changed accounts
await checkIfNameChanged();
const generatedHtml = getUpdatedLogsHtml();
const title = "Logs";
if (currentPanel && title !== currentTitle) {
// dipose the previous one
currentPanel.dispose();
}
currentTitle = title;
if (!currentPanel) {
currentPanel = window.createWebviewPanel("100doc", title, ViewColumn.One, { enableScripts: true });
currentPanel.onDidDispose(() => {
currentPanel = undefined;
});
currentPanel.webview.onDidReceiveMessage(async (message) => {
if (!isLoggedIn()) {
displayLoginPromptIfNotLoggedIn();
}
switch (message.command) {
case "editLog":
const dayUpdate = message.value;
await editLogEntry(
parseInt(dayUpdate.day_number, 10),
parseInt(dayUpdate.unix_date, 10),
dayUpdate.title,
dayUpdate.description,
dayUpdate.links,
dayUpdate.hours
);
await syncLogs();
commands.executeCommand("DoC.viewLogs");
break;
case "addLog":
TrackerManager.getInstance().trackUIInteraction("click", "100doc_add_log_btn", "100doc_logs_view", "blue", "", "Add Log");
commands.executeCommand("DoC.addLog");
break;
case "incrementShare":
TrackerManager.getInstance().trackUIInteraction("click", "100doc_share_log_btn", "100doc_logs_view", "", "share", "");
updateLogShare(message.value);
checkSharesMilestones();
break;
case "deleteLog":
const selection = await window.showInformationMessage(
`Are you sure you want to delete this log, '${message.value.title}'?`,
{ modal: true },
...["Yes"]
);
if (selection && selection === "Yes") {
commands.executeCommand("DoC.deleteLog", message.value.unix_date);
}
break;
case "refreshView":
// refresh the logs then show it again
await syncLogs();
if (currentPanel) {
// dipose the previous one
currentPanel.dispose();
}
commands.executeCommand("DoC.viewLogs");
break;
case "logInToAccount":
commands.executeCommand("codetime.codeTimeExisting");
break;
}
});
}
currentPanel.webview.html = generatedHtml;
currentPanel.reveal(ViewColumn.One);
displayLoginPromptIfNotLoggedIn();
})
);
cmds.push(
commands.registerCommand("DoC.deleteLog", (unix_day: number) => {
// send the delete request
deleteLogDay(unix_day);
})
);
cmds.push(
commands.registerCommand("DoC.viewDashboard", async () => {
// check if the user has changed accounts
await checkIfNameChanged();
const generatedHtml = getUpdatedDashboardHtmlString();
const title = "Dashboard";
if (currentPanel && title !== currentTitle) {
// dipose the previous one
currentPanel.dispose();
}
currentTitle = title;
if (!currentPanel) {
currentPanel = window.createWebviewPanel("100doc", title, ViewColumn.One, { enableScripts: true });
currentPanel.onDidDispose(() => {
currentPanel = undefined;
});
currentPanel.webview.onDidReceiveMessage(async (message) => {
switch (message.command) {
case "Logs":
commands.executeCommand("DoC.viewLogs");
TrackerManager.getInstance().trackUIInteraction("click", "100doc_logs_btn", "100doc_dashboard_view", "", "", "View Logs");
break;
case "ShareProgress":
TrackerManager.getInstance().trackUIInteraction(
"click",
"100doc_share_progress_btn",
"100doc_dashboard_view",
"blue",
"",
"Share progress"
);
break;
case "Milestones":
commands.executeCommand("DoC.viewMilestones");
TrackerManager.getInstance().trackUIInteraction("click", "100doc_milestones_btn", "100doc_dashboard_view", "", "", "View Milestones");
break;
case "Certificate":
window
.showInputBox({
placeHolder: "Your name",
prompt: "Please enter your name for getting the certificate. Please make sure that you are connected to the internet.",
})
.then((text) => {
if (text) {
const panel = window.createWebviewPanel("Congratulations!", "Congratulations!", ViewColumn.One);
panel.webview.html = getCertificateHtmlString(text);
panel.reveal(ViewColumn.One);
}
});
case "refreshView":
// refresh the logs then show it again
await fetchSummary();
if (currentPanel) {
// dipose the previous one
currentPanel.dispose();
}
commands.executeCommand("DoC.viewDashboard");
break;
case "logInToAccount":
commands.executeCommand("codetime.codeTimeExisting");
break;
}
});
}
currentPanel.webview.html = generatedHtml;
currentPanel.reveal(ViewColumn.One);
displayLoginPromptIfNotLoggedIn();
})
);
cmds.push(
commands.registerCommand("DoC.viewMilestones", async () => {
// check if the user has changed accounts
await checkIfNameChanged();
if (isLoggedIn()) {
checkCodeTimeMetricsMilestonesAchieved();
checkLanguageMilestonesAchieved();
checkDaysMilestones();
}
const generatedHtml = getUpdatedMilestonesHtmlString();
const title = "Milestones";
if (currentPanel && title !== currentTitle) {
// dipose the previous one
currentPanel.dispose();
}
currentTitle = title;
if (!currentPanel) {
currentPanel = window.createWebviewPanel("100doc", title, ViewColumn.One, { enableScripts: true });
currentPanel.onDidDispose(() => {
currentPanel = undefined;
});
currentPanel.webview.onDidReceiveMessage(async (message) => {
switch (message.command) {
case "incrementShare":
TrackerManager.getInstance().trackUIInteraction("click", "100doc_share_milestone_btn", "100doc_milestones_view", "", "share", "");
updateMilestoneShare(message.value);
checkSharesMilestones();
break;
case "refreshView":
// refresh the milestones
await MilestoneEventManager.getInstance().fetchAllMilestones();
if (currentPanel) {
// dipose the previous one
currentPanel.dispose();
}
commands.executeCommand("DoC.viewMilestones");
break;
case "logInToAccount":
commands.executeCommand("codetime.codeTimeExisting");
break;
}
});
}
currentPanel.webview.html = generatedHtml;
currentPanel.reveal(ViewColumn.One);
displayLoginPromptIfNotLoggedIn();
})
);
cmds.push(
commands.registerCommand("DoC.addLog", () => {
const generatedHtml = getAddLogHtmlString();
const title = "Add Daily Progress Log";
if (currentPanel && title !== currentTitle) {
// dipose the previous one
currentPanel.dispose();
}
currentTitle = title;
if (!currentPanel) {
currentPanel = window.createWebviewPanel("100doc", title, ViewColumn.One, { enableScripts: true });
currentPanel.onDidDispose(() => {
currentPanel = undefined;
});
// handle submit or cancel
let log;
currentPanel.webview.onDidReceiveMessage(async (message) => {
switch (message.command) {
// no need to add a cancel, just show the logs as a default
case "log":
if (isLoggedIn()) {
log = message.value;
// this posts the log create/update to the server as well
await addLogToJson(log.title, log.description, log.hours, log.keystrokes, log.lines, log.links);
checkLanguageMilestonesAchieved();
checkDaysMilestones();
await syncLogs();
} else {
displayLoginPromptIfNotLoggedIn();
}
break;
case "logInToAccount":
commands.executeCommand("codetime.codeTimeExisting");
break;
}
commands.executeCommand("DoC.viewLogs");
});
}
currentPanel.webview.html = generatedHtml;
currentPanel.reveal(ViewColumn.One);
})
);
cmds.push(
commands.registerCommand("DoC.showInfoMessage", (tile: string, message: string, isModal: boolean, commandCallback: string) => {
window
.showInformationMessage(
message,
{
modal: isModal,
},
tile
)
.then((selection) => {
if (commandCallback && selection === tile) {
commands.executeCommand(commandCallback);
}
});
})
);
cmds.push(
commands.registerCommand("DoC.restartChallengeRound", () => {
if (!isLoggedIn()) {
displayLoginPromptIfNotLoggedIn();
return;
}
window
.showInformationMessage(
"Are you sure you want to restart the challenge? Once your challenge is restarted, you will not see your stats from your previous challenge.",
{
modal: true,
},
YES_LABEL
)
.then((selection) => {
if (selection === YES_LABEL) {
// set the new challenge round and create a new log based on the new round val
restartChallenge();
}
});
})
);
return Disposable.from(...cmds);
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* The metadata supported value detail.
*/
export interface MetadataSupportedValueDetail {
/**
* The id.
*/
id?: string;
/**
* The display name.
*/
displayName?: string;
}
/**
* The metadata entity contract.
*/
export interface MetadataEntity {
/**
* The resource Id of the metadata entity.
*/
id?: string;
/**
* The type of the metadata entity.
*/
type?: string;
/**
* The name of the metadata entity.
*/
name?: string;
/**
* The display name.
*/
displayName?: string;
/**
* The list of keys on which this entity depends on.
*/
dependsOn?: string[];
/**
* The list of scenarios applicable to this metadata entity.
*/
applicableScenarios?: Scenario[];
/**
* The list of supported values.
*/
supportedValues?: MetadataSupportedValueDetail[];
}
/**
* Advisor Digest configuration entity
*/
export interface DigestConfig {
/**
* Name of digest configuration. Value is case-insensitive and must be unique within a
* subscription.
*/
name?: string;
/**
* Action group resource id used by digest.
*/
actionGroupResourceId?: string;
/**
* Frequency that digest will be triggered, in days. Value must be between 7 and 30 days
* inclusive.
*/
frequency?: number;
/**
* Categories to send digest for. If categories are not provided, then digest will be sent for
* all categories.
*/
categories?: Category[];
/**
* Language for digest content body. Value must be ISO 639-1 code for one of Azure portal
* supported languages. Otherwise, it will be converted into one. Default value is English (en).
*/
language?: string;
/**
* State of digest configuration. Possible values include: 'Active', 'Disabled'
*/
state?: DigestConfigState;
}
/**
* An Azure resource.
*/
export interface Resource extends BaseResource {
/**
* The resource ID.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The name of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The type of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* The Advisor configuration data structure.
*/
export interface ConfigData extends Resource {
/**
* Exclude the resource from Advisor evaluations. Valid values: False (default) or True.
*/
exclude?: boolean;
/**
* Minimum percentage threshold for Advisor low CPU utilization evaluation. Valid only for
* subscriptions. Valid values: 5 (default), 10, 15 or 20. Possible values include: '5', '10',
* '15', '20'
*/
lowCpuThreshold?: CpuThreshold;
/**
* Advisor digest configuration. Valid only for subscriptions
*/
digests?: DigestConfig[];
}
/**
* ARM error response body.
*/
export interface ARMErrorResponseBody {
/**
* Gets or sets the string that describes the error in detail and provides debugging information.
*/
message?: string;
/**
* Gets or sets the string that can be used to programmatically identify the error.
*/
code?: string;
}
/**
* An interface representing ArmErrorResponse.
*/
export interface ArmErrorResponse {
error?: ARMErrorResponseBody;
}
/**
* A summary of the recommendation.
*/
export interface ShortDescription {
/**
* The issue or opportunity identified by the recommendation.
*/
problem?: string;
/**
* The remediation action suggested by the recommendation.
*/
solution?: string;
}
/**
* Recommendation resource metadata
*/
export interface ResourceMetadata {
/**
* Azure resource Id of the assessed resource
*/
resourceId?: string;
/**
* Source from which recommendation is generated
*/
source?: string;
}
/**
* Advisor Recommendation.
*/
export interface ResourceRecommendationBase extends Resource {
/**
* The category of the recommendation. Possible values include: 'HighAvailability', 'Security',
* 'Performance', 'Cost', 'OperationalExcellence'
*/
category?: Category;
/**
* The business impact of the recommendation. Possible values include: 'High', 'Medium', 'Low'
*/
impact?: Impact;
/**
* The resource type identified by Advisor.
*/
impactedField?: string;
/**
* The resource identified by Advisor.
*/
impactedValue?: string;
/**
* The most recent time that Advisor checked the validity of the recommendation.
*/
lastUpdated?: Date;
/**
* The recommendation metadata.
*/
metadata?: { [propertyName: string]: any };
/**
* The recommendation-type GUID.
*/
recommendationTypeId?: string;
/**
* The potential risk of not implementing the recommendation. Possible values include: 'Error',
* 'Warning', 'None'
*/
risk?: Risk;
/**
* A summary of the recommendation.
*/
shortDescription?: ShortDescription;
/**
* The list of snoozed and dismissed rules for the recommendation.
*/
suppressionIds?: string[];
/**
* Extended properties
*/
extendedProperties?: { [propertyName: string]: string };
/**
* Metadata of resource that was assessed
*/
resourceMetadata?: ResourceMetadata;
}
/**
* The operation supported by Advisor.
*/
export interface OperationDisplayInfo {
/**
* The description of the operation.
*/
description?: string;
/**
* The action that users can perform, based on their permission level.
*/
operation?: string;
/**
* Service provider: Microsoft Advisor.
*/
provider?: string;
/**
* Resource on which the operation is performed.
*/
resource?: string;
}
/**
* The operation supported by Advisor.
*/
export interface OperationEntity {
/**
* Operation name: {provider}/{resource}/{operation}.
*/
name?: string;
/**
* The operation supported by Advisor.
*/
display?: OperationDisplayInfo;
}
/**
* The details of the snoozed or dismissed rule; for example, the duration, name, and GUID
* associated with the rule.
*/
export interface SuppressionContract extends Resource {
/**
* The GUID of the suppression.
*/
suppressionId?: string;
/**
* The duration for which the suppression is valid.
*/
ttl?: string;
}
/**
* Optional Parameters.
*/
export interface RecommendationsListOptionalParams extends msRest.RequestOptionsBase {
/**
* The filter to apply to the recommendations.
*/
filter?: string;
/**
* The number of recommendations per page if a paged version of this API is being used.
*/
top?: number;
/**
* The page-continuation token to use with a paged version of this API.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface SuppressionsListOptionalParams extends msRest.RequestOptionsBase {
/**
* The number of suppressions per page if a paged version of this API is being used.
*/
top?: number;
/**
* The page-continuation token to use with a paged version of this API.
*/
skipToken?: string;
}
/**
* An interface representing AdvisorManagementClientOptions.
*/
export interface AdvisorManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* Defines headers for Generate operation.
*/
export interface RecommendationsGenerateHeaders {
/**
* The URL where the status of the asynchronous operation can be checked.
*/
location: string;
/**
* The amount of delay to use while the status of the operation is checked. The value is
* expressed in seconds.
*/
retryAfter: string;
}
/**
* @interface
* The list of metadata entities
* @extends Array<MetadataEntity>
*/
export interface MetadataEntityListResult extends Array<MetadataEntity> {
/**
* The link used to get the next page of metadata.
*/
nextLink?: string;
}
/**
* @interface
* The list of Advisor configurations.
* @extends Array<ConfigData>
*/
export interface ConfigurationListResult extends Array<ConfigData> {
/**
* The link used to get the next page of configurations.
*/
nextLink?: string;
}
/**
* @interface
* The list of Advisor recommendations.
* @extends Array<ResourceRecommendationBase>
*/
export interface ResourceRecommendationBaseListResult extends Array<ResourceRecommendationBase> {
/**
* The link used to get the next page of recommendations.
*/
nextLink?: string;
}
/**
* @interface
* The list of Advisor operations.
* @extends Array<OperationEntity>
*/
export interface OperationEntityListResult extends Array<OperationEntity> {
/**
* The link used to get the next page of operations.
*/
nextLink?: string;
}
/**
* @interface
* The list of Advisor suppressions.
* @extends Array<SuppressionContract>
*/
export interface SuppressionContractListResult extends Array<SuppressionContract> {
/**
* The link used to get the next page of suppressions.
*/
nextLink?: string;
}
/**
* Defines values for Scenario.
* Possible values include: 'Alerts'
* @readonly
* @enum {string}
*/
export type Scenario = 'Alerts';
/**
* Defines values for CpuThreshold.
* Possible values include: '5', '10', '15', '20'
* @readonly
* @enum {string}
*/
export type CpuThreshold = '5' | '10' | '15' | '20';
/**
* Defines values for Category.
* Possible values include: 'HighAvailability', 'Security', 'Performance', 'Cost',
* 'OperationalExcellence'
* @readonly
* @enum {string}
*/
export type Category = 'HighAvailability' | 'Security' | 'Performance' | 'Cost' | 'OperationalExcellence';
/**
* Defines values for DigestConfigState.
* Possible values include: 'Active', 'Disabled'
* @readonly
* @enum {string}
*/
export type DigestConfigState = 'Active' | 'Disabled';
/**
* Defines values for Impact.
* Possible values include: 'High', 'Medium', 'Low'
* @readonly
* @enum {string}
*/
export type Impact = 'High' | 'Medium' | 'Low';
/**
* Defines values for Risk.
* Possible values include: 'Error', 'Warning', 'None'
* @readonly
* @enum {string}
*/
export type Risk = 'Error' | 'Warning' | 'None';
/**
* Contains response data for the get operation.
*/
export type RecommendationMetadataGetResponse = {
/**
* The parsed response body.
*/
body: any;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: any;
};
};
/**
* Contains response data for the list operation.
*/
export type RecommendationMetadataListResponse = MetadataEntityListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: MetadataEntityListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type RecommendationMetadataListNextResponse = MetadataEntityListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: MetadataEntityListResult;
};
};
/**
* Contains response data for the listBySubscription operation.
*/
export type ConfigurationsListBySubscriptionResponse = ConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConfigurationListResult;
};
};
/**
* Contains response data for the createInSubscription operation.
*/
export type ConfigurationsCreateInSubscriptionResponse = ConfigData & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConfigData;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type ConfigurationsListByResourceGroupResponse = ConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConfigurationListResult;
};
};
/**
* Contains response data for the createInResourceGroup operation.
*/
export type ConfigurationsCreateInResourceGroupResponse = ConfigData & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConfigData;
};
};
/**
* Contains response data for the listBySubscriptionNext operation.
*/
export type ConfigurationsListBySubscriptionNextResponse = ConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConfigurationListResult;
};
};
/**
* Contains response data for the generate operation.
*/
export type RecommendationsGenerateResponse = RecommendationsGenerateHeaders & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The parsed HTTP response headers.
*/
parsedHeaders: RecommendationsGenerateHeaders;
};
};
/**
* Contains response data for the list operation.
*/
export type RecommendationsListResponse = ResourceRecommendationBaseListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ResourceRecommendationBaseListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type RecommendationsGetResponse = ResourceRecommendationBase & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ResourceRecommendationBase;
};
};
/**
* Contains response data for the listNext operation.
*/
export type RecommendationsListNextResponse = ResourceRecommendationBaseListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ResourceRecommendationBaseListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationEntityListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationEntityListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = OperationEntityListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationEntityListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type SuppressionsGetResponse = SuppressionContract & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SuppressionContract;
};
};
/**
* Contains response data for the create operation.
*/
export type SuppressionsCreateResponse = SuppressionContract & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SuppressionContract;
};
};
/**
* Contains response data for the list operation.
*/
export type SuppressionsListResponse = SuppressionContractListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SuppressionContractListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type SuppressionsListNextResponse = SuppressionContractListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SuppressionContractListResult;
};
}; | the_stack |
import {
Button,
Checkbox,
Code,
FormControl,
FormErrorMessage,
FormHelperText,
FormLabel,
Input,
Select,
Switch,
useDisclosure,
} from "@chakra-ui/react";
import {
DuplicateIcon,
LinkIcon,
PlusIcon,
TerminalIcon,
} from "@heroicons/react/outline";
import {
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
} from "@chakra-ui/react";
import { SQLDataSourceTypes } from "@/plugins/data-sources/abstract-sql-query-service/types";
import { WHITELISTED_IP_ADDRESS } from "@/lib/constants";
import { joiResolver } from "@hookform/resolvers/joi/dist/joi";
import { merge } from "lodash";
import { toast } from "react-toastify";
import {
useAddDataSourceMutation,
useCheckConnectionMutation,
} from "@/features/data-sources/api-slice";
import { useCopyToClipboard } from "react-use";
import { useForm } from "react-hook-form";
import { useProfile } from "@/hooks";
import { useRouter } from "next/router";
import BackButton from "@/features/records/components/BackButton";
import Layout from "@/components/Layout";
import PageWrapper from "@/components/PageWrapper";
import React, { memo, useEffect, useMemo, useState } from "react";
import URI from "urijs";
import getSchema from "@/plugins/data-sources/getSchema";
import isEmpty from "lodash/isEmpty";
import isUndefined from "lodash/isUndefined";
export type IFormFields = {
id?: number;
name: string;
type: SQLDataSourceTypes;
organizationId: number;
options: {
connectsWithSSH: boolean;
connectsWithSSHKey: boolean;
};
credentials: {
host: string;
port: number;
database: string;
user: string;
password?: string;
useSsl: boolean;
};
};
export type DefaultValueCredentials = {
host?: string;
port?: number | "";
database?: string;
user?: string;
password?: string;
useSsl?: boolean;
};
const NewDataSourceForm = ({
type,
placeholders = {},
defaultValues = {},
}: {
type: SQLDataSourceTypes;
placeholders?: {
name?: string;
type?: string;
organizationId?: string;
credentials?: {
host?: string;
port?: string;
database?: string;
user?: string;
password?: string;
};
ssh?: {
host?: string;
port?: string;
user?: string;
password?: string;
passphrase?: string;
};
};
defaultValues?: {
name?: string;
type?: string;
organizationId?: string;
options?: {
connectsWithSSH?: boolean;
connectsWithSSHKey?: boolean;
};
credentials?: DefaultValueCredentials;
ssh?: {
host?: string;
port?: number | "";
user?: string;
password?: string;
key?: any;
passphrase?: string;
};
};
}) => {
const router = useRouter();
const [addDataSource, { isLoading }] = useAddDataSourceMutation();
const { organizations } = useProfile();
defaultValues = merge(
{
name: "",
type: type,
organizationId: "",
options: {
connectsWithSSH: false,
connectsWithSSHKey: false,
},
credentials: {
host: "",
port: "",
database: "",
user: "",
password: "",
useSsl: true,
},
ssh: {
port: 22,
},
},
defaultValues
);
/**
* Init the form
*/
const schema = getSchema(type);
const { register, handleSubmit, formState, setValue, getValues, watch } =
useForm({
defaultValues,
resolver: joiResolver(schema),
});
const errors = useMemo(() => formState.errors, [formState.errors]);
const watcher = watch();
const formData = useMemo(() => getValues(), [watcher]);
/**
* Submit the form
*/
const onSubmit = async (formData: IFormFields) => {
let response;
try {
// Check the connection is successful before saving a data source.
const connectionSuccessful = await checkConnectionMethod();
if (connectionSuccessful) {
response = await addDataSource({ body: formData }).unwrap();
}
} catch (error) {}
if (response && response.ok) {
await router.push(`/data-sources/${response.data.id}`);
}
};
/**
* If we get some credentials through the url params, they must be removed after use
*/
useEffect(() => {
if (router.query.credentials) {
// reset the URL if we get the credentials through the params for added security
router.push(
{
pathname: router.pathname,
},
router.pathname,
{
shallow: true,
}
);
}
}, []);
/**
* Set the first org as selected
*/
useEffect(() => {
if (organizations && organizations.length > 0 && organizations[0].id) {
setValue("organizationId", organizations[0].id?.toString(), {
shouldDirty: true,
shouldTouch: true,
});
}
}, [organizations]);
/**
* Check the connection
*/
const [checkConnection, { isLoading: isChecking }] =
useCheckConnectionMutation();
const checkConnectionMethod = async () => {
const type = getValues("type");
const credentials = getValues("credentials");
const ssh = getValues("ssh");
const options = getValues("options");
let body: any = { type, credentials, options };
// Add the SSH credentials
if (formData?.options?.connectsWithSSH)
body = {
...body,
ssh,
};
if (
!isEmpty(getValues("credentials.host")) &&
!isEmpty(getValues("credentials.database")) &&
!isEmpty(getValues("credentials.user"))
) {
const response = await checkConnection({
body,
}).unwrap();
if ((response as any).ok) return true;
} else {
toast.error(
"Credentials are not complete. You have to input 'host', 'port', 'database' and 'user' in order to test connection."
);
}
return false;
};
const { isOpen, onOpen, onClose } = useDisclosure();
const [credentialsUrl, setCredentialsUrl] = useState<string | undefined>();
const fillCredentialsFromUrl = () => {
const uri = URI(credentialsUrl);
const credentials = getValues("credentials") || {};
if (uri.hostname()) credentials.host = uri.hostname();
if (uri.port()) credentials.port = parseInt(uri.port());
if (uri.path()) credentials.database = uri.path().replace("/", "");
if (uri.username()) credentials.user = uri.username();
if (uri.password()) credentials.password = uri.password();
setValue("credentials", credentials);
onClose();
};
const [state, copyToClipboard] = useCopyToClipboard();
return (
<Layout hideSidebar={true}>
<PageWrapper
heading="Add data source"
buttons={<BackButton href="/data-sources/new" />}
footer={
<PageWrapper.Footer
left={
<Button
colorScheme="blue"
size="sm"
variant="outline"
onClick={checkConnectionMethod}
leftIcon={<TerminalIcon className="h-4" />}
isLoading={isChecking}
>
Test connection
</Button>
}
center={
<Button
colorScheme="blue"
size="sm"
width="300px"
type="submit"
disabled={isLoading}
onClick={(e) => {
return handleSubmit(onSubmit)(e);
}}
leftIcon={<PlusIcon className="h-4" />}
isLoading={isLoading}
>
Create
</Button>
}
right={
<Button
colorScheme="blue"
size="sm"
variant="outline"
onClick={onOpen}
leftIcon={<LinkIcon className="h-4" />}
>
Paste from URL
</Button>
}
/>
}
>
<div className="relative flex flex-1 w-full h-full items center justify-center">
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Paste from URL</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Input
type="text"
placeholder="postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]"
value={credentialsUrl}
onChange={(e) => setCredentialsUrl(e.target.value)}
onKeyPress={(e) => {
if (e.key === "Enter" && !isEmpty(credentialsUrl))
fillCredentialsFromUrl();
}}
autoFocus
/>
</ModalBody>
<ModalFooter>
<Button
colorScheme="gray"
size="sm"
variant="outline"
mr={3}
onClick={onClose}
>
Close
</Button>
<Button
colorScheme="blue"
size="sm"
onClick={fillCredentialsFromUrl}
isDisabled={isEmpty(credentialsUrl)}
>
Apply
</Button>
</ModalFooter>
</ModalContent>
</Modal>
<form
onSubmit={handleSubmit(onSubmit)}
className="space-y-4 max-w-2xl"
>
<FormControl
id="name"
isInvalid={!isUndefined(errors?.name?.message)}
>
<FormLabel>Name</FormLabel>
<Input
type="text"
placeholder={placeholders.name}
{...register("name")}
autoFocus
/>
<FormHelperText>The name of your data source.</FormHelperText>
<FormErrorMessage>{errors?.name?.message}</FormErrorMessage>
</FormControl>
<FormControl
id="organization"
isInvalid={!isUndefined(errors?.organizationId?.message)}
>
<FormLabel>Organization</FormLabel>
<Select {...register("organizationId")}>
{organizations.map(({ id, name }) => (
<option key={id} value={id}>
{name}
</option>
))}
</Select>
<FormErrorMessage>
{errors?.organizationId?.message}
</FormErrorMessage>
</FormControl>
<div className="w-full flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
<div className="sm:w-3/4">
<FormControl
id="host"
isInvalid={!isUndefined(errors?.credentials?.host?.message)}
>
<FormLabel>Host</FormLabel>
<Input
type="text"
placeholder={placeholders?.credentials?.host}
{...register("credentials.host")}
/>
<FormErrorMessage>
{errors?.credentials?.host?.message}
</FormErrorMessage>
</FormControl>
</div>
<div className="flex-1">
<FormControl
id="port"
isInvalid={!isUndefined(errors?.credentials?.port?.message)}
>
<FormLabel>Port</FormLabel>
<Input
type="text"
placeholder={placeholders?.credentials?.port}
{...register("credentials.port")}
/>
<FormErrorMessage>
{errors?.credentials?.port?.message}
</FormErrorMessage>
</FormControl>
</div>
</div>
<FormControl
id="database"
isInvalid={!isUndefined(errors?.credentials?.database?.message)}
>
<FormLabel>Database name</FormLabel>
<Input
type="text"
placeholder={placeholders?.credentials?.database}
{...register("credentials.database")}
/>
<FormErrorMessage>
{errors?.credentials?.database?.message}
</FormErrorMessage>
</FormControl>
<div className="w-full flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
<div className="sm:w-1/2">
<FormControl
id="user"
isInvalid={!isUndefined(errors?.credentials?.user?.message)}
>
<FormLabel>Username</FormLabel>
<Input
type="text"
placeholder={placeholders?.credentials?.user}
{...register("credentials.user")}
/>
<FormErrorMessage>
{errors?.credentials?.user?.message}
</FormErrorMessage>
</FormControl>
</div>
<div className="sm:w-1/2">
<FormControl
id="password"
isInvalid={
!isUndefined(errors?.credentials?.password?.message)
}
>
<FormLabel>Password</FormLabel>
<Input
type="password"
placeholder={placeholders?.credentials?.password}
{...register("credentials.password")}
/>
<FormErrorMessage>
{errors?.credentials?.password?.message}
</FormErrorMessage>
</FormControl>
</div>
</div>
<div className="text-gray-600 text-sm">
The credentials are safely encrypted. We'll never display these
credentials ever again.
</div>
<FormControl id="credentials_useSsl">
<FormLabel htmlFor="credentials.useSsl">Use SSL</FormLabel>
<Checkbox
id="credentials.useSsl"
{...register("credentials.useSsl")}
/>
<FormErrorMessage>
{errors?.credentials?.useSsl?.message}
</FormErrorMessage>
</FormControl>
<div className="text-gray-800 text-">
Add our IP{" "}
<span
className="cursor-pointer"
onClick={() => {
copyToClipboard(WHITELISTED_IP_ADDRESS);
toast("📋 Copied to clipboard");
}}
>
<Code>{WHITELISTED_IP_ADDRESS}</Code>{" "}
<DuplicateIcon className="inline h-4" />
</span>{" "}
to your server's whitelist.
</div>
<FormControl display="flex" alignItems="center">
<FormLabel htmlFor="connect-with-ssh" mb="0">
Connect with SSH
</FormLabel>
<Switch
id="connect-with-ssh"
isChecked={formData?.options?.connectsWithSSH}
onChange={() =>
setValue(
"options",
{
...formData?.options,
connectsWithSSH: !formData?.options?.connectsWithSSH,
},
{
shouldTouch: true,
}
)
}
/>
</FormControl>
{formData?.options?.connectsWithSSH && (
<>
<div className="font-xl font-bold">SSH connection details</div>
<div className="w-full flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
<div className="sm:w-3/4">
<FormControl
id="host"
isInvalid={!isUndefined(errors?.ssh?.host?.message)}
>
<FormLabel>Host</FormLabel>
<Input
type="text"
placeholder={placeholders?.ssh?.host}
{...register("ssh.host")}
/>
<FormErrorMessage>
{errors?.ssh?.host?.message}
</FormErrorMessage>
</FormControl>
</div>
<div className="flex-1">
<FormControl
id="port"
isInvalid={!isUndefined(errors?.ssh?.port?.message)}
>
<FormLabel>Port</FormLabel>
<Input
type="number"
placeholder={placeholders?.ssh?.port}
{...register("ssh.port")}
/>
<FormErrorMessage>
{errors?.ssh?.port?.message}
</FormErrorMessage>
</FormControl>
</div>
</div>
<div className="w-full flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
<div className="sm:w-1/2">
<FormControl
id="user"
isInvalid={!isUndefined(errors?.ssh?.user?.message)}
>
<FormLabel>User</FormLabel>
<Input
type="text"
placeholder={placeholders?.ssh?.user}
{...register("ssh.user")}
/>
<FormErrorMessage>
{errors?.ssh?.user?.message}
</FormErrorMessage>
</FormControl>
</div>
<div className="sm:w-1/2">
<FormControl
id="password"
isInvalid={!isUndefined(errors?.ssh?.password?.message)}
>
<FormLabel>Password</FormLabel>
<Input
type="password"
disabled={formData.options.connectsWithSSHKey}
placeholder={placeholders?.ssh?.password}
{...register("ssh.password")}
/>
<FormErrorMessage>
{errors?.ssh?.password?.message}
</FormErrorMessage>
</FormControl>
</div>
</div>
<FormControl display="flex" alignItems="center">
<FormLabel htmlFor="connect-with-ssh-key" mb="0">
Connect using SSH key
</FormLabel>
<Switch
id="connect-with-key"
isChecked={formData?.options?.connectsWithSSHKey}
onChange={() =>
setValue(
"options",
{
...formData?.options,
connectsWithSSHKey:
!formData?.options?.connectsWithSSHKey,
},
{
shouldTouch: true,
}
)
}
/>
</FormControl>
{formData.options.connectsWithSSHKey && (
<div className="w-full flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
<div className="sm:w-1/2">
<FormControl
id="ssh-key"
isInvalid={!isUndefined(errors?.ssh?.key?.message)}
>
<FormLabel>SSH key</FormLabel>
<input type="file" {...register("ssh.key")} />
<FormErrorMessage>
{errors?.ssh?.key?.message}
</FormErrorMessage>
</FormControl>
</div>
<div className="sm:w-1/2">
<FormControl
id="passphrase"
isInvalid={
!isUndefined(errors?.ssh?.passphrase?.message)
}
>
<FormLabel>SSH key passphrase</FormLabel>
<Input
type="text"
placeholder={placeholders?.ssh?.passphrase}
{...register("ssh.passphrase")}
/>
<FormHelperText>
Leave empty if the key is not encrypted.
</FormHelperText>
<FormErrorMessage>
{errors?.ssh?.passphrase?.message}
</FormErrorMessage>
</FormControl>
</div>
</div>
)}
</>
)}
<input type="submit" className="hidden invisible" />
</form>
</div>
</PageWrapper>
</Layout>
);
};
export default memo(NewDataSourceForm); | the_stack |
import {
buildForm,
buildDescriptionField,
buildMultiField,
buildSection,
buildExternalDataProvider,
buildKeyValueField,
buildSubmitField,
buildCheckboxField,
buildCustomField,
buildSelectField,
buildDividerField,
buildRadioField,
buildTextField,
Form,
FormModes,
DefaultEvents,
StaticText,
buildSubSection,
getValueViaPath,
buildDataProviderItem,
FormValue,
} from '@island.is/application/core'
import { LogreglanLogo } from '../assets'
import { NationalRegistryUser, Teacher, UserProfile } from '../types/schema'
import { m } from '../lib/messages'
import { Juristiction } from '../types/schema'
import { format as formatKennitala } from 'kennitala'
import { QualityPhotoData, ConditionFn } from '../types'
import { StudentAssessment } from '@island.is/api/schema'
import { NO, YES } from '../lib/constants'
import {
DrivingLicenseApplicationFor,
B_FULL,
B_TEMP,
} from '../shared/constants'
import { hasYes } from '../utils'
// const ALLOW_FAKE_DATA = todo: serverside feature flag
const ALLOW_FAKE_DATA = false
const ALLOW_LICENSE_SELECTION = false
const allowFakeCondition = (result = YES) => (answers: FormValue) =>
getValueViaPath(answers, 'fakeData.useFakeData') === result
const allowLicenseSelection = () => ALLOW_LICENSE_SELECTION
const needsHealthCertificateCondition = (result = YES) => (
answers: FormValue,
) => {
return Object.values(answers?.healthDeclaration || {}).includes(result)
}
const isVisible = (...fns: ConditionFn[]) => (answers: FormValue) =>
fns.reduce((s, fn) => (!s ? false : fn(answers)), true)
const isApplicationForCondition = (result: DrivingLicenseApplicationFor) => (
answers: FormValue,
) => {
const applicationFor: string[] = getValueViaPath(answers, 'applicationFor', [
B_FULL,
]) as string[]
return applicationFor.includes(result)
}
const hasNoDrivingLicenseInOtherCountry = (answers: FormValue) =>
!hasYes(answers?.drivingLicenseInOtherCountry)
const chooseDistrictCommissionerDescription = ({
answers,
}: {
answers: FormValue
}) => {
const applicationFor = getValueViaPath(
answers,
'applicationFor',
B_FULL,
) as string
switch (applicationFor) {
case B_TEMP:
return m.chooseDistrictCommisionerForTempLicense.defaultMessage
case B_FULL:
return m.chooseDistrictCommisionerForFullLicense.defaultMessage
default:
return ''
}
}
export const application: Form = buildForm({
id: 'DrivingLicenseApplicationDraftForm',
title: m.applicationName,
logo: LogreglanLogo,
mode: FormModes.APPLYING,
renderLastScreenButton: true,
renderLastScreenBackButton: true,
children: [
buildSection({
id: 'externalData',
title: m.externalDataSection,
children: [
...(ALLOW_FAKE_DATA
? [
buildSubSection({
id: 'fakeData',
title: 'Gervigögn',
children: [
buildMultiField({
id: 'shouldFake',
title: 'Gervigögn',
children: [
buildDescriptionField({
id: 'gervigognDesc',
title: 'Viltu nota gervigögn?',
titleVariant: 'h5',
// Note: text is rendered by a markdown component.. and when
// it sees the indented spaces it seems to assume this is code
// and so it will wrap the text in a <code> block when the double
// spaces are not removed.
description: `
Ath. gervigögn eru eingöngu notuð í stað þess að sækja
forsendugögn í staging umhverfi (dev x-road) hjá RLS, auk þess
sem hægt er að senda inn umsóknina í "þykjó" - þeas. allt hagar sér
eins nema að RLS tekur ekki við umsókninni.
Öll önnur gögn eru ekki gervigögn og er þetta eingöngu gert
til að hægt sé að prófa ferlið án þess að vera með tilheyrandi
ökuréttindi í staging grunni RLS.
`.replace(/\s{2}/g, ''),
}),
buildRadioField({
id: 'fakeData.useFakeData',
title: '',
width: 'half',
options: [
{
value: YES,
label: 'Já',
},
{
value: NO,
label: 'Nei',
},
],
}),
buildRadioField({
id: 'fakeData.currentLicense',
title: 'Núverandi ökuréttindi umsækjanda',
width: 'half',
condition: allowFakeCondition(YES),
options: [
{
value: 'student',
label: 'Engin',
},
{
value: 'temp',
label: 'Bráðabirgðaskírteini',
},
],
}),
buildRadioField({
id: 'fakeData.qualityPhoto',
title: 'Gervimynd eða enga mynd?',
width: 'half',
condition: allowFakeCondition(YES),
options: [
{
value: YES,
label: 'Mynd',
},
{
value: NO,
label: 'Engin mynd',
},
],
}),
],
}),
],
}),
]
: []),
buildExternalDataProvider({
title: m.externalDataTitle,
id: 'approveExternalData',
subTitle: m.externalDataSubTitle,
checkboxLabel: m.externalDataAgreement,
dataProviders: [
buildDataProviderItem({
id: 'nationalRegistry',
type: 'NationalRegistryProvider',
title: m.nationalRegistryTitle,
subTitle: m.nationalRegistrySubTitle,
}),
buildDataProviderItem({
id: 'userProfile',
type: 'UserProfileProvider',
title: m.userProfileInformationTitle,
subTitle: m.userProfileInformationSubTitle,
}),
buildDataProviderItem({
id: 'currentLicense',
type: 'CurrentLicenseProvider',
title: m.infoFromLicenseRegistry,
subTitle: m.confirmationStatusOfEligability,
}),
buildDataProviderItem({
id: 'qualityPhoto',
type: 'QualityPhotoProvider',
title: '',
subTitle: '',
}),
buildDataProviderItem({
id: 'studentAssessment',
type: 'DrivingAssessmentProvider',
title: '',
}),
buildDataProviderItem({
id: 'juristictions',
type: 'JuristictionProvider',
title: '',
}),
buildDataProviderItem({
id: 'payment',
type: 'FeeInfoProvider',
title: '',
}),
buildDataProviderItem({
id: 'teachers',
type: 'TeachersProvider',
title: '',
}),
],
}),
],
}),
buildSection({
id: 'application',
title: m.applicationDrivingLicenseTitle,
condition: allowLicenseSelection,
children: [
buildMultiField({
id: 'info',
title: m.drivingLicenseApplyingForTitle,
children: [
buildRadioField({
id: 'applicationFor',
backgroundColor: 'white',
title: '',
description: '',
space: 0,
largeButtons: true,
options: [
{
label: m.applicationForTempLicenseTitle,
subLabel:
m.applicationForTempLicenseDescription.defaultMessage,
value: B_TEMP,
},
{
label: m.applicationForFullLicenseTitle,
subLabel:
m.applicationForFullLicenseDescription.defaultMessage,
value: B_FULL,
disabled: true,
},
],
}),
],
}),
],
}),
buildSection({
id: 'requirements',
title: m.applicationEligibilityTitle,
children: [
buildMultiField({
id: 'info',
title: m.eligibilityRequirementTitle,
children: [
buildCustomField({
title: m.eligibilityRequirementTitle,
component: 'EligibilitySummary',
id: 'eligsummary',
}),
],
}),
],
}),
buildSection({
id: 'infoStep',
title: m.informationTitle,
condition: isApplicationForCondition(B_TEMP),
children: [
buildMultiField({
id: 'info',
title: m.informationTitle,
space: 1,
children: [
buildKeyValueField({
label: m.drivingLicenseTypeRequested,
value: 'Almenn ökuréttindi - B flokkur (Fólksbifreið)',
}),
buildDividerField({
title: '',
color: 'dark400',
}),
buildKeyValueField({
label: m.informationApplicant,
value: ({ externalData: { nationalRegistry } }) =>
(nationalRegistry.data as NationalRegistryUser).fullName,
width: 'half',
}),
buildKeyValueField({
label: m.informationStreetAddress,
value: ({ externalData: { nationalRegistry } }) => {
const address = (nationalRegistry.data as NationalRegistryUser)
.address
if (!address) {
return ''
}
const { streetAddress, city } = address
return `${streetAddress}${city ? ', ' + city : ''}`
},
width: 'half',
}),
buildTextField({
id: 'email',
title: m.informationYourEmail,
placeholder: 'Netfang',
}),
buildDividerField({
title: '',
color: 'dark400',
}),
buildDescriptionField({
id: 'drivingInstructorTitle',
title: m.drivingInstructor,
titleVariant: 'h4',
description: m.chooseDrivingInstructor,
}),
buildSelectField({
id: 'drivingInstructor',
title: m.drivingInstructor,
disabled: false,
options: ({
externalData: {
teachers: { data },
},
}) => {
return (data as Teacher[]).map(({ name }) => ({
value: name,
label: name,
}))
},
}),
],
}),
],
}),
buildSection({
id: 'otherCountry',
title: m.foreignDrivingLicense,
condition: isApplicationForCondition(B_TEMP),
children: [
buildMultiField({
id: 'info',
title: m.drivingLicenseInOtherCountry,
space: 1,
children: [
buildRadioField({
id: 'drivingLicenseInOtherCountry',
backgroundColor: 'white',
title: '',
description: '',
space: 0,
largeButtons: true,
options: [
{
label: m.no,
subLabel: '',
value: NO,
},
{
label: m.yes,
subLabel: '',
value: YES,
},
],
}),
buildCheckboxField({
id: 'drivingLicenseDeprivedOrRestrictedInOtherCountry',
backgroundColor: 'white',
title: '',
condition: (answers) =>
hasYes(answers?.drivingLicenseInOtherCountry || []),
options: [
{
value: NO,
label: m.noDeprivedDrivingLicenseInOtherCountryTitle,
subLabel:
m.noDeprivedDrivingLicenseInOtherCountryDescription
.defaultMessage,
},
],
}),
],
}),
],
}),
buildSection({
id: 'otherCountrySelected',
title: 'Leiðbeiningar',
condition: (answer) => hasYes(answer?.drivingLicenseInOtherCountry),
children: [
buildCustomField({
condition: (answers) =>
hasYes(answers?.drivingLicenseInOtherCountry || []),
title: 'SubmitAndDecline',
component: 'SubmitAndDecline',
id: 'SubmitAndDecline',
}),
],
}),
buildSection({
id: 'photoStep',
title: m.applicationQualityPhotoTitle,
condition: isVisible(
isApplicationForCondition(B_FULL),
hasNoDrivingLicenseInOtherCountry,
),
children: [
buildMultiField({
id: 'info',
title: m.qualityPhotoTitle,
condition: (_, externalData) => {
return (
(externalData.qualityPhoto as QualityPhotoData)?.data?.success ===
true
)
},
children: [
buildCustomField({
title: m.eligibilityRequirementTitle,
component: 'QualityPhoto',
id: 'qphoto',
}),
buildRadioField({
id: 'willBringQualityPhoto',
title: '',
disabled: false,
options: [
{ value: NO, label: m.qualityPhotoNoAcknowledgement },
{ value: YES, label: m.qualityPhotoAcknowledgement },
],
}),
buildCustomField({
id: 'photdesc',
title: '',
component: 'Bullets',
condition: (answers) => hasYes(answers.willBringQualityPhoto),
}),
],
}),
buildMultiField({
id: 'info',
title: m.qualityPhotoTitle,
condition: (answers: FormValue, externalData) => {
return (
(externalData.qualityPhoto as QualityPhotoData)?.data?.success ===
false
)
},
children: [
buildCustomField({
title: m.eligibilityRequirementTitle,
component: 'QualityPhoto',
id: 'qphoto',
}),
buildCustomField({
id: 'photodescription',
title: '',
component: 'Bullets',
}),
buildCheckboxField({
id: 'willBringQualityPhoto',
title: '',
options: [
{
value: YES,
label: m.qualityPhotoAcknowledgement,
},
],
}),
],
}),
],
}),
buildSection({
id: 'user',
title: m.informationSectionTitle,
condition: hasNoDrivingLicenseInOtherCountry,
children: [
buildMultiField({
id: 'info',
title: m.pickupLocationTitle,
space: 1,
children: [
buildKeyValueField({
label: m.informationApplicant,
value: ({ externalData: { nationalRegistry } }) =>
(nationalRegistry.data as NationalRegistryUser).fullName,
}),
buildDividerField({
title: '',
color: 'dark400',
}),
buildDescriptionField({
id: 'afhending',
title: m.districtCommisionerTitle,
titleVariant: 'h4',
description: chooseDistrictCommissionerDescription,
}),
buildSelectField({
id: 'juristiction',
title: m.districtCommisionerPickup,
disabled: false,
options: ({
externalData: {
juristictions: { data },
},
}) => {
return (data as Juristiction[]).map(({ id, name, zip }) => ({
value: id,
label: name,
tooltip: `Póstnúmer ${zip}`,
}))
},
}),
],
}),
],
}),
buildSection({
id: 'healthDeclaration',
title: m.healthDeclarationSectionTitle,
condition: hasNoDrivingLicenseInOtherCountry,
children: [
buildMultiField({
id: 'overview',
title: m.healthDeclarationMultiFieldTitle,
space: 1,
children: [
buildCustomField(
{
id: 'healthDeclaration.usesContactGlasses',
title: '',
component: 'HealthDeclaration',
},
{
title: m.healthDeclarationMultiFieldSubTitle,
label: m.healthDeclaration1,
},
),
buildCustomField(
{
id: 'healthDeclaration.hasReducedPeripheralVision',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration2,
},
),
buildCustomField(
{
id: 'healthDeclaration.hasEpilepsy',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration3,
},
),
buildCustomField(
{
id: 'healthDeclaration.hasHeartDisease',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration4,
},
),
buildCustomField(
{
id: 'healthDeclaration.hasMentalIllness',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration5,
},
),
buildCustomField(
{
id: 'healthDeclaration.usesMedicalDrugs',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration6,
},
),
buildCustomField(
{
id: 'healthDeclaration.isAlcoholic',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration7,
},
),
buildCustomField(
{
id: 'healthDeclaration.hasDiabetes',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration8,
},
),
buildCustomField(
{
id: 'healthDeclaration.isDisabled',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration9,
},
),
buildCustomField(
{
id: 'healthDeclaration.hasOtherDiseases',
title: '',
component: 'HealthDeclaration',
},
{
label: m.healthDeclaration10,
},
),
],
}),
],
}),
buildSection({
id: 'overview',
title: m.overviewSectionTitle,
condition: hasNoDrivingLicenseInOtherCountry,
children: [
buildMultiField({
id: 'overview',
title: m.overviewMultiFieldTitle,
space: 1,
description: m.overviewMultiFieldDescription,
children: [
buildSubmitField({
id: 'submit',
placement: 'footer',
title: m.orderDrivingLicense,
refetchApplicationAfterSubmit: true,
actions: [
{
event: DefaultEvents.PAYMENT,
name: m.continue,
type: 'primary',
},
],
}),
buildKeyValueField({
label: m.overviewSubType,
value: ({ answers: { subType } }) => subType as string[],
}),
buildDividerField({}),
buildKeyValueField({
label: m.overviewName,
width: 'half',
value: ({ externalData: { nationalRegistry } }) =>
(nationalRegistry.data as NationalRegistryUser).fullName,
}),
buildKeyValueField({
label: m.overviewPhoneNumber,
width: 'half',
value: ({ externalData: { userProfile } }) =>
(userProfile.data as UserProfile).mobilePhoneNumber as string,
}),
buildKeyValueField({
label: m.overviewStreetAddress,
width: 'half',
value: ({ externalData: { nationalRegistry } }) =>
(nationalRegistry.data as NationalRegistryUser).address
?.streetAddress,
}),
buildKeyValueField({
label: m.overviewNationalId,
width: 'half',
value: ({ externalData: { nationalRegistry } }) =>
formatKennitala(
(nationalRegistry.data as NationalRegistryUser).nationalId,
),
}),
buildKeyValueField({
label: m.overviewPostalCode,
width: 'half',
value: ({ externalData: { nationalRegistry } }) =>
(nationalRegistry.data as NationalRegistryUser).address
?.postalCode,
}),
buildKeyValueField({
label: m.overviewEmail,
width: 'half',
value: ({ externalData: { userProfile } }) =>
(userProfile.data as UserProfile).email as string,
}),
buildKeyValueField({
label: m.overviewCity,
width: 'half',
value: ({ externalData: { nationalRegistry } }) =>
(nationalRegistry.data as NationalRegistryUser).address?.city,
}),
buildDividerField({}),
buildKeyValueField({
label: m.overviewTeacher,
width: 'half',
value: ({ externalData: { studentAssessment } }) =>
(studentAssessment.data as StudentAssessment).teacherName,
}),
buildDividerField({
condition: (answers) => hasYes(answers?.healthDeclaration || []),
}),
buildDescriptionField({
id: 'bringalong',
title: m.overviewBringAlongTitle,
titleVariant: 'h4',
description: '',
condition: needsHealthCertificateCondition(YES),
}),
buildCheckboxField({
id: 'certificate',
title: '',
large: false,
backgroundColor: 'white',
defaultValue: [],
options: [
{
value: YES,
label: m.overviewBringCertificateData,
},
],
condition: (answers) => hasYes(answers?.healthDeclaration || {}),
}),
buildDividerField({}),
buildKeyValueField({
label: m.overviewPaymentCharge,
value: ({ externalData, answers }) => {
const items = externalData.payment.data as {
priceAmount: number
chargeItemCode: string
}[]
const targetCode =
answers.applicationFor === B_TEMP ? 'AY114' : 'AY110'
const item = items.find(
({ chargeItemCode }) => chargeItemCode === targetCode,
)
return (item?.priceAmount?.toLocaleString('de-DE') +
' kr.') as StaticText
},
width: 'full',
}),
],
}),
],
}),
],
}) | the_stack |
import hoistStatics from 'hoist-non-react-statics';
import invariant from 'invariant';
import type { FunctionComponent } from 'react';
import React, { useMemo, useRef, useReducer, Component } from 'react';
import { isValidElementType } from 'react-is';
import { Subscription } from './Subscription';
import { useConsumerContext, useIsomorphicLayoutEffect } from './hooks';
import type { ConsumerContext } from './types';
// Define some constant arrays just to avoid re-creating these
const EMPTY_ARRAY: void[] = [];
const stringifyComponent = (Comp: any) => {
try {
return JSON.stringify(Comp);
} catch (err) {
return String(Comp);
}
};
function storeStateUpdatesReducer(state: any, action: any) {
const [, updateCount] = state;
return [action.payload, updateCount + 1];
}
const initStateUpdates = () => [null, 0];
export function connectAdvanced(
/*
selectorFactory is a func that is responsible for returning the selector function used to
compute new props from state, props, and dispatch. For example:
export default connectAdvanced((dispatch, options) => (state, props) => ({
thing: state.things[props.thingId],
saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)),
}))(YourComponent)
Access to dispatch is provided to the factory so selectorFactories can bind actionCreators
outside of their selector as an optimization. Options passed to connectAdvanced are passed to
the selectorFactory, along with displayName and WrappedComponent, as the second argument.
Note that selectorFactory is responsible for all caching/memoization of inbound and outbound
props. Do not use connectAdvanced directly without memoizing results between calls to your
selector, otherwise the Connect component will re-render on every state or props change.
*/
selectorFactory: (context: ConsumerContext, options: any) => any,
// options object:
{
// the func used to compute this HOC's displayName from the wrapped component's displayName.
// probably overridden by wrapper functions such as connect()
getDisplayName = (name: string) => `ConnectAdvanced(${name})`,
// shown in error messages
// probably overridden by wrapper functions such as connect()
methodName = 'connectAdvanced',
// stores to connect to
stores = [],
// determines whether this HOC subscribes to store changes
shouldHandleStateChanges = true,
// use React's forwardRef to expose a ref of the wrapped component
forwardRef = false,
// function used to schedule updates
schedule = (fn: Function) => fn(),
// is component and all toProps functions are pure, so they can be memoized
pure = true,
// additional options are passed through to the selectorFactory
...connectOptions
} = {}
) {
return function wrapWithConnect<T extends React.ComponentType>(WrappedComponent: T) {
if (process.env.NODE_ENV !== 'production') {
invariant(
isValidElementType(WrappedComponent),
`You must pass a component to the function returned by ` +
`${methodName}. Instead received ${stringifyComponent(WrappedComponent)}`
);
}
const wrappedComponentName =
(WrappedComponent as any).displayName || (WrappedComponent as any).name || 'Component';
const displayName = getDisplayName(wrappedComponentName);
const selectorFactoryOptions = {
...connectOptions,
pure,
getDisplayName,
methodName,
shouldHandleStateChanges,
displayName,
wrappedComponentName,
WrappedComponent,
};
// If we aren't running in "pure" mode, we don't want to memoize values.
// To avoid conditionally calling hooks, we fall back to a tiny wrapper
// that just executes the given callback immediately.
const usePureOnlyMemo = pure ? useMemo : (callback: Function) => callback();
const ConnectFunction: FunctionComponent<any> = (props) => {
const [forwardedRef, wrapperProps] = useMemo(() => {
// Distinguish between actual "data" props that were passed to the wrapper component,
// and values needed to control behavior (forwarded refs, alternate context instances).
// To maintain the wrapperProps object reference, memoize this destructuring.
// eslint-disable-next-line no-shadow
const { forwardedRef, ...wrapperProps } = props;
return [forwardedRef, wrapperProps];
}, [props]);
// Retrieve the store and ancestor subscription via context, if available
const contextValue = useConsumerContext();
invariant(
Boolean(contextValue),
`Could not find context in ` +
`"${displayName}". Either wrap the root component in a <Provider>, ` +
`or pass a custom React context provider to <Provider> and the corresponding ` +
`React context consumer to ${displayName} in connect options.`
);
const childPropsSelector = useMemo(() => {
// The child props selector needs the store reference as an input.
// Re-create this selector whenever the store changes.
return selectorFactory(contextValue, selectorFactoryOptions);
}, [contextValue]);
const subscription = useMemo(() => {
if (!shouldHandleStateChanges) return null;
return new Subscription(stores.map((store) => contextValue.getStore(store)));
}, [contextValue]);
useMemo(() => {
if (subscription && typeof window !== 'undefined') {
subscription.trySubscribe();
}
}, [subscription]);
// We need to force this wrapper component to re-render whenever a Redux store update
// causes a change to the calculated child component props (or we caught an error in mapState)
const [[previousStateUpdateResult], forceComponentUpdateDispatch] = useReducer(
storeStateUpdatesReducer,
EMPTY_ARRAY,
initStateUpdates
);
// Propagate any mapState/mapDispatch errors upwards
if (previousStateUpdateResult && previousStateUpdateResult.error) {
throw previousStateUpdateResult.error;
}
// Set up refs to coordinate values between the subscription effect and the render logic
const lastChildProps = useRef();
const lastWrapperProps = useRef(wrapperProps);
const childPropsFromStoreUpdate = useRef();
const renderIsScheduled = useRef(false);
const actualChildProps = usePureOnlyMemo(() => {
// Tricky logic here:
// - This render may have been triggered by a Redux store update that produced new child props
// - However, we may have gotten new wrapper props after that
// If we have new child props, and the same wrapper props, we know we should use the new child props as-is.
// But, if we have new wrapper props, those might change the child props, so we have to recalculate things.
// So, we'll use the child props from store update only if the wrapper props are the same as last time.
if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) {
return childPropsFromStoreUpdate.current;
}
// TODO We're reading the store directly in render() here. Bad idea?
// This will likely cause Bad Things (TM) to happen in Concurrent Mode.
// Note that we do this because on renders _not_ caused by store updates, we need the latest store state
// to determine what the child props should be.
return childPropsSelector(contextValue.getState(), wrapperProps);
}, [contextValue, previousStateUpdateResult, wrapperProps]);
// We need this to execute synchronously every time we re-render. However, React warns
// about useLayoutEffect in SSR, so we try to detect environment and fall back to
// just useEffect instead to avoid the warning, since neither will run anyway.
useIsomorphicLayoutEffect(() => {
// We want to capture the wrapper props and child props we used for later comparisons
lastWrapperProps.current = wrapperProps;
lastChildProps.current = actualChildProps;
// If the render was from a store update, clear out that reference and cascade the subscriber update
if (childPropsFromStoreUpdate.current) {
childPropsFromStoreUpdate.current = undefined;
}
});
// Our re-subscribe logic only runs when the store/subscription setup changes
useIsomorphicLayoutEffect(() => {
// If we're not subscribed to the store, nothing to do here
if (!subscription) return;
// Capture values for checking if and when this component unmounts
let didUnsubscribe = false;
let lastThrownError: Error | null = null;
// We'll run this callback every time a store subscription update propagates to this component
const checkForUpdates = () => {
renderIsScheduled.current = false;
if (didUnsubscribe) {
// Don't run stale listeners.
// Redux doesn't guarantee unsubscriptions happen until next dispatch.
return;
}
const latestStoreState = contextValue.getState();
let newChildProps;
let error;
try {
// Actually run the selector with the most recent store state and wrapper props
// to determine what the child props should be
newChildProps = childPropsSelector(latestStoreState, lastWrapperProps.current);
} catch (e) {
error = e;
lastThrownError = e;
}
if (!error) {
lastThrownError = null;
}
// If the child props haven't changed, nothing to do here - cascade the subscription update
if (newChildProps !== lastChildProps.current) {
// Save references to the new child props. Note that we track the "child props from store update"
// as a ref instead of a useState/useReducer because we need a way to determine if that value has
// been processed. If this went into useState/useReducer, we couldn't clear out the value without
// forcing another re-render, which we don't want.
lastChildProps.current = newChildProps;
childPropsFromStoreUpdate.current = newChildProps;
// If the child props _did_ change (or we caught an error), this wrapper component needs to re-render
forceComponentUpdateDispatch({
type: 'STORE_UPDATED',
payload: {
latestStoreState,
error,
},
});
}
};
// Actually subscribe to the nearest connected ancestor (or store)
subscription.setOnStateChange(() => {
if (!renderIsScheduled.current) {
renderIsScheduled.current = true;
schedule(checkForUpdates);
}
});
// Pull data from the store after first render in case the store has
// changed since we began.
checkForUpdates();
const unsubscribeWrapper = () => {
didUnsubscribe = true;
subscription.tryUnsubscribe();
if (lastThrownError) {
// It's possible that we caught an error due to a bad mapState function, but the
// parent re-rendered without this component and we're about to unmount.
// This shouldn't happen as long as we do top-down subscriptions correctly, but
// if we ever do those wrong, this throw will surface the error in our tests.
// In that case, throw the error from here so it doesn't get lost.
throw lastThrownError;
}
};
return unsubscribeWrapper;
}, [contextValue, subscription, childPropsSelector]);
// Now that all that's done, we can finally try to actually render the child component.
// We memoize the elements for the rendered child component as an optimization.
const renderedWrappedComponent = useMemo(
// eslint-disable-next-line react/jsx-props-no-spreading
() => <WrappedComponent {...actualChildProps} ref={forwardedRef} />,
[forwardedRef, actualChildProps]
);
return renderedWrappedComponent;
};
// If we're in "pure" mode, ensure our wrapper component only re-renders when incoming props have changed.
const Connect = pure ? React.memo(ConnectFunction) : ConnectFunction;
(Connect as any).WrappedComponent = WrappedComponent;
Connect.displayName = displayName;
if (forwardRef) {
const forwarded = React.forwardRef(function forwardConnectRef(props, ref) {
// eslint-disable-next-line react/jsx-props-no-spreading
return <Connect {...props} forwardedRef={ref} />;
});
forwarded.displayName = displayName;
(forwarded as any).WrappedComponent = WrappedComponent;
return (hoistStatics(forwarded, WrappedComponent) as any) as T;
}
return hoistStatics(Connect, WrappedComponent) as T;
};
} | the_stack |
import * as angular from 'angular';
import { ListItemSelectModeEnum } from './listItemSelectModeEnum';
import { ListItemTypeEnum } from './listItemTypeEnum';
import { ListLayoutEnum } from './listLayoutEnum';
/**
* @ngdoc interface
* @name IListScope
* @module officeuifabric.components.list
*
* @description
* Scope used by the list controller.
*
* @property {string} itemSelectMode - Specifies the list item selection mode used by the list
* @property {string} layout - Specifies how the list should be rendered
* @property {IListItemScope[]} items - Contains the data items that belong to the list
* @property {any[]} selectedItems - Contains the list of selected items
*/
export interface IListScope extends angular.IScope {
itemSelectMode?: string;
layout?: string;
items: IListItemScope[];
selectedItems: any[];
}
/**
* @ngdoc object
* @name ListController
* @requires $scope, $log
* @description
* List directive controller. Used to keep track of items selected in the list
*/
class ListController {
public static $inject: string[] = ['$scope', '$log'];
constructor(public $scope: IListScope, public $log: angular.ILogService) {
this.$scope.items = [];
if (!this.$scope.selectedItems) {
this.$scope.selectedItems = [];
}
}
get itemSelectMode(): string {
return this.$scope.itemSelectMode;
}
get selectedItems(): IListItemScope[] {
return this.$scope.selectedItems;
}
get items(): IListItemScope[] {
return this.$scope.items;
}
}
/**
* @ngdoc interface
* @name IListAttributes
* @module officeuifabric.components.list
*
* @description
* Attributes used by the list directive.
*
* @property {string} uifLayout - Specifies how the list is rendered.
* Possible values: list - items are rendered as a list
* grid - items are rendered as a grid
* @property {string} uifItemSelectMode - Specifies whether the list supports selecting items.
* Possible values: none - selecting items is not possible;
* single - only one item can be selected;
* multiple - multiple items can be selected;
* @property {string} uifSelectedItems - Specifies the name of the array used to keep track of the
* selected items
*/
export interface IListAttributes extends angular.IAttributes {
uifLayout?: string;
uifItemSelectMode?: string;
uifSelectedItems?: string;
}
/**
* @ngdoc directive
* @name uifList
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list>` is a directive used to display a list of items
*
* @see {link http://dev.office.com/fabric/components/list}
*
* @usage
*
* <uif-list uif-item-select-mode="single" uif-selected-items="selectedItems">
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}" uif-unseen="{{message.isUnseen}}" uif-item="message"
* uif-type="itemWithIcon">
* <uif-list-item-icon>
* <uif-icon uif-type="save"></uif-icon>
* </uif-list-item-icon>
* <uif-list-item-primary-text>{{message.sender.name}}</uif-list-item-primary-text>
* <uif-list-item-secondary-text>{{message.title}}</uif-list-item-secondary-text>
* <uif-list-item-tertiary-text>{{message.description}}</uif-list-item-tertiary-text>
* <uif-list-item-meta-text>{{message.time | date : 'shortTime'}}</uif-list-item-meta-text>
* <uif-list-item-selection-target></uif-list-item-selection-target>
* <uif-list-item-actions>
* <uif-list-item-action ng-click="mail(message)">
* <uif-icon uif-type="mail"></uif-icon>
* </uif-list-item-action>
* <uif-list-item-action ng-click="delete(message)">
* <uif-icon uif-type="trash"></uif-icon>
* </uif-list-item-action>
* <uif-list-item-action ng-click="pin(message)">
* <uif-icon uif-type="pinLeft"></uif-icon>
* </uif-list-item-action>
* </uif-list-item-actions>
* </uif-list-item>
* </uif-list>
*/
export class ListDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public replace: boolean = false;
public template: string = '<ul class="ms-List" ng-transclude></ul>';
public controller: any = ListController;
public controllerAs: string = 'list';
public scope: {} = {
selectedItems: '=?uifSelectedItems',
uifItemSelectMode: '@?',
uifLayout: '@?'
};
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListDirective();
return directive;
}
public link(scope: IListScope, instanceElement: angular.IAugmentedJQuery, attrs: IListAttributes, controller: ListController): void {
scope.$watch('uifLayout', (newValue: string, oldValue: string) => {
if (newValue !== undefined && newValue !== null) {
if (ListLayoutEnum[newValue] === undefined) {
controller.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.list. ' +
'The layout (\'' + newValue + '\') is not a valid option for \'uif-layout\'. ' +
'Supported options are listed here: ' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/list/listLayoutEnum.ts');
} else {
scope.layout = newValue;
}
}
// default layout mode to list
if (scope.layout === undefined) {
scope.layout = ListLayoutEnum[ListLayoutEnum.list];
}
if (scope.layout === ListLayoutEnum[ListLayoutEnum.grid]) {
instanceElement.children().eq(0).addClass('ms-List--grid');
} else {
instanceElement.children().eq(0).removeClass('ms-List--grid');
}
});
scope.$watch('uifItemSelectMode', (newValue: string, oldValue: string) => {
if (newValue !== undefined && newValue !== null) {
if (ListItemSelectModeEnum[newValue] === undefined) {
controller.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.list. ' +
' The selection mode (\'' + newValue + '\') is not a valid option for \'uif-item-select-mode\'. ' +
'Supported options are listed here: ' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/list/listItemSelectModeEnum.ts');
} else {
scope.itemSelectMode = attrs.uifItemSelectMode;
}
}
// default select mode to none
if (scope.itemSelectMode === undefined) {
scope.itemSelectMode = ListItemSelectModeEnum[ListItemSelectModeEnum.none];
}
// if the select mode changed...
if (newValue !== oldValue) {
// ... unselect all items
for (let i: number = 0; i < controller.items.length; i++) {
controller.items[i].selected = false;
}
// ... broadcast message the select mode changed
scope.$broadcast('list-item-select-mode-changed', newValue);
}
});
}
}
/**
* @ngdoc interface
* @name IListItemScope
* @module officeuifabric.components.list
*
* @description
* Scope used by the list item controller.
*
* @property {any} item - Contains data item bound to the list item
* @property {boolean} selected - Specifies whether the particular list item is selected or not
* @property {ListItemTypeEnum} type - Specifies how the list item should be rendered
* @property {boolean} unread - Specifies whether the particular list item is read or not
* @property (boolean) unseen - Specifies whether the particular list item is seen or not
* @property {(ev: any) => void} itemClick - event handler for clicking the list item
*/
export interface IListItemScope extends angular.IScope {
item: any;
selected: boolean;
type: ListItemTypeEnum;
unread: boolean;
unseen: boolean;
itemClick: (ev: any) => void;
}
/**
* @ngdoc object
* @name ListItemController
* @requires $scope, $log
* @description
* List Item directive controller
*/
class ListItemController {
public static $inject: string[] = ['$scope', '$log'];
constructor(public $scope: IListItemScope, public $log: angular.ILogService) {
}
}
/**
* @ngdoc interface
* @name IListItemAttributes
* @module officeuifabric.components.list
*
* @description
* Attributes used by the list item directive.
*
* @property {any} uifItem - Data item bound to the item
* @property {string} uifSelected - Specifies whether the particular item is selected or not
* @property {string} uifType - Specifies how the item should be rendered
* @property {string} uifUnread - Specifies whether the particular item is read or not
* @property {string} uifUnseen - Specifies whether the particular item is seen or not
*/
export interface IListItemAttributes extends angular.IAttributes {
uifItem: any;
uifSelected?: string;
uifType?: string;
uifUnread?: string;
uifUnseen?: string;
}
/**
* @ngdoc directive
* @name uifListItem
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item>` is a directive that represents an item in a list
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list uif-item-select-mode="single" uif-selected-items="selectedItems">
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}" uif-unseen="{{message.isUnseen}}" uif-item="message"
* uif-type="itemWithIcon">
* <uif-list-item-icon>
* <uif-icon uif-type="save"></uif-icon>
* </uif-list-item-icon>
* <uif-list-item-primary-text>{{message.sender.name}}</uif-list-item-primary-text>
* <uif-list-item-secondary-text>{{message.title}}</uif-list-item-secondary-text>
* <uif-list-item-tertiary-text>{{message.description}}</uif-list-item-tertiary-text>
* <uif-list-item-meta-text>{{message.time | date : 'shortTime'}}</uif-list-item-meta-text>
* <uif-list-item-selection-target></uif-list-item-selection-target>
* <uif-list-item-actions>
* <uif-list-item-action ng-click="mail(message)">
* <uif-icon uif-type="mail"></uif-icon>
* </uif-list-item-action>
* <uif-list-item-action ng-click="delete(message)">
* <uif-icon uif-type="trash"></uif-icon>
* </uif-list-item-action>
* <uif-list-item-action ng-click="pin(message)">
* <uif-icon uif-type="pinLeft"></uif-icon>
* </uif-list-item-action>
* </uif-list-item-actions>
* </uif-list-item>
* </uif-list>
*/
export class ListItemDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public replace: boolean = false;
public template: string = '<li class="ms-ListItem" ng-transclude></li>';
public require: string = '^uifList';
public scope: {} = {
item: '=uifItem',
uifType: '@?'
};
public controller: any = ListItemController;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemDirective();
return directive;
}
public link(scope: IListItemScope, instanceElement: angular.IAugmentedJQuery, attrs: IListItemAttributes, list: ListController): void {
if (attrs.uifSelected !== undefined && attrs.uifSelected !== null) {
let selectedString: string = attrs.uifSelected.toLowerCase();
if (selectedString !== 'true' && selectedString !== 'false') {
list.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.list. ' +
'\'' + attrs.uifSelected + '\' is not a valid boolean value. ' +
'Valid options are true|false.');
} else {
if (selectedString === 'true') {
scope.selected = true;
}
}
}
if (scope.item && list.selectedItems.length > 0) {
for (let i: number = 0; i < list.selectedItems.length; i++) {
if (list.selectedItems[i] === scope.item) {
scope.selected = true;
}
}
}
scope.$watch('uifType', (newValue: string, oldValue: string) => {
if (newValue !== undefined && newValue !== null) {
if (ListItemTypeEnum[newValue] === undefined) {
list.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.list. ' +
'The list item type (\'' + newValue + '\') is not a valid option for \'uif-type\'. ' +
'Supported options are listed here: ' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/list/listItemTypeEnum.ts');
}
}
// remove any decorators on the list item that may be present
instanceElement.children().eq(0).removeClass('ms-ListItem--image');
instanceElement.children().eq(0).removeClass('ms-ListItem--document');
// decorate list item with correct class based on type
switch (ListItemTypeEnum[attrs.uifType]) {
case ListItemTypeEnum.itemWithIcon:
instanceElement.children().eq(0).addClass('ms-ListItem--document');
break;
case ListItemTypeEnum.itemWithImage:
instanceElement.children().eq(0).addClass('ms-ListItem--image');
break;
default:
break;
}
// after the digest completes, check for presence of required elements depending on the uif-type of the item
scope.$evalAsync(() => {
switch (ListItemTypeEnum[attrs.uifType]) {
case ListItemTypeEnum.itemWithIcon:
if (instanceElement.children().find('uif-list-item-icon').length === 0) {
list.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.list. ' +
'List item type `itemWithIcon` requires the `uif-list-item-icon` directive. Without this the icon will not appear.');
}
break;
case ListItemTypeEnum.itemWithImage:
if (instanceElement.children().find('uif-list-item-image').length === 0) {
list.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.list. ' +
'List item type `itemWithImage` requires the `uif-list-item-image` directive. Without this the image will not appear.');
}
break;
default:
break;
}
});
});
if (attrs.uifUnread !== undefined &&
attrs.uifUnread !== null) {
let unreadString: string = attrs.uifUnread.toLowerCase();
if (unreadString !== 'true' && unreadString !== 'false') {
list.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.list. ' +
'\'' + attrs.uifUnread + '\' is not a valid boolean value. ' +
'Valid options are true|false.');
} else {
if (unreadString === 'true') {
scope.unread = true;
}
}
}
if (attrs.uifUnseen !== undefined &&
attrs.uifUnseen !== null) {
let unseenString: string = attrs.uifUnseen.toLowerCase();
if (unseenString !== 'true' && unseenString !== 'false') {
list.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.list. ' +
'\'' + attrs.uifUnseen + '\' is not a valid boolean value. ' +
'Valid options are true|false.');
} else {
if (unseenString === 'true') {
scope.unseen = true;
}
}
}
if (scope.item !== undefined) {
list.items.push(scope);
}
scope.itemClick = (ev: any): void => {
scope.selected = !scope.selected;
scope.$apply();
};
scope.$watch('selected', (newValue: boolean, oldValue: boolean, listItemScope: IListItemScope): void => {
if (newValue === true) {
if (list.itemSelectMode === ListItemSelectModeEnum[ListItemSelectModeEnum.single]) {
list.selectedItems.length = 0;
if (list.items) {
for (let i: number = 0; i < list.items.length; i++) {
if (list.items[i] !== listItemScope) {
list.items[i].selected = false;
}
}
}
}
// only add to the list if not yet exists. prevents conflicts
// with preselected items
let itemAlreadySelected: boolean = false;
for (let i: number = 0; i < list.selectedItems.length; i++) {
if (list.selectedItems[i] === listItemScope.item) {
itemAlreadySelected = true;
break;
}
}
if (!itemAlreadySelected) {
list.selectedItems.push(listItemScope.item);
}
instanceElement.children().eq(0).addClass('is-selected');
} else {
for (let i: number = 0; i < list.selectedItems.length; i++) {
if (list.selectedItems[i] === listItemScope.item) {
list.selectedItems.splice(i, 1);
break;
}
}
instanceElement.children().eq(0).removeClass('is-selected');
}
});
scope.$watch('unread', (newValue: boolean, oldValue: boolean, listItemScope: IListItemScope): void => {
if (newValue === true) {
instanceElement.children().eq(0).addClass('is-unread');
} else {
instanceElement.children().eq(0).removeClass('is-unread');
}
});
scope.$watch('unseen', (newValue: boolean, oldValue: boolean, listItemScope: IListItemScope): void => {
if (newValue === true) {
instanceElement.children().eq(0).addClass('is-unseen');
} else {
instanceElement.children().eq(0).removeClass('is-unseen');
}
});
if (list.itemSelectMode !== ListItemSelectModeEnum[ListItemSelectModeEnum.none]) {
updateItemSelectionModeDecoration(list.itemSelectMode);
}
// add event listener when selection mode on the list changes
scope.$on('list-item-select-mode-changed', (event: angular.IAngularEvent, selectionMode: string) => {
updateItemSelectionModeDecoration(selectionMode);
});
// update selection mode for item
function updateItemSelectionModeDecoration(selectionMode: string): void {
// if no selection mode, remove decorator allowing it to be selected ...
// else, add decorator & event handler if they aren't present
if (selectionMode === 'none') {
instanceElement.children().eq(0).removeClass('is-selectable');
} else if (!instanceElement.children().eq(0).hasClass('is-selectable')) {
instanceElement.on('click', scope.itemClick);
instanceElement.children().eq(0).addClass('is-selectable');
}
}
}
}
/**
* @ngdoc directive
* @name uifListItemPrimaryText
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-primary-text>` is a directive that represents the primary text of a list item (eg. e-mail sender)
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}" uif-unseen="{{message.isUnseen}}" uif-item="message">
* <uif-list-item-primary-text>{{message.sender.name}}</uif-list-item-primary-text>
* </uif-list-item>
*/
export class ListItemPrimaryTextDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<span class="ms-ListItem-primaryText" ng-transclude></span>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemPrimaryTextDirective();
return directive;
}
}
/**
* @ngdoc directive
* @name uifListItemSecondaryText
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-secondary-text>` is a directive that represents the secondary text of a list item (eg. e-mail subject)
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}" uif-unseen="{{message.isUnseen}}" uif-item="message">
* <uif-list-item-secondary-text>{{message.sender.name}}</uif-list-item-secondary-text>
* </uif-list-item>
*/
export class ListItemSecondaryTextDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<span class="ms-ListItem-secondaryText" ng-transclude></span>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemSecondaryTextDirective();
return directive;
}
}
/**
* @ngdoc directive
* @name uifListItemTertiartText
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-tertiary-text>` is a directive that represents the tertiary text of a list item (eg. e-mail short preview)
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}" uif-unseen="{{message.isUnseen}}" uif-item="message">
* <uif-list-item-tertiary-text>{{message.sender.name}}</uif-list-item-tertiary-text>
* </uif-list-item>
*/
export class ListItemTertiaryTextDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<span class="ms-ListItem-tertiaryText" ng-transclude></span>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemTertiaryTextDirective();
return directive;
}
}
/**
* @ngdoc directive
* @name uifListItemMetaText
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-meta-text>` is a directive that represents the meta text of a list item (eg. e-mail send time)
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}" uif-unseen="{{message.isUnseen}}" uif-item="message">
* <uif-list-item-meta-text>{{message.sender.name}}</uif-list-item-meta-text>
* </uif-list-item>
*/
export class ListItemMetaTextDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<span class="ms-ListItem-metaText" ng-transclude></span>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemMetaTextDirective();
return directive;
}
}
/**
* @ngdoc directive
* @name uifListItemImage
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-image>` is a directive that represents the image of a list item.
* This directive is required when list item type is set to `itemWithImage`.
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}"
* uif-unseen="{{message.isUnseen}}" uif-item="message" uif-type="itemWithImage">
* <uif-list-item-image>
* <img ng-src="{{message.image}}" />
* </uif-list-item-image>
* </uif-list-item>
*/
export class ListItemImageDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<div class="ms-ListItem-image" ng-transclude></div>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemImageDirective();
return directive;
}
}
/**
* @ngdoc directive
* @name uifListItemIcon
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-icon>` is a directive that represents the icon of a list item.
* This directive is required when list item type is set to `itemWithIcon`.
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}"
* uif-unseen="{{message.isUnseen}}" uif-item="message" uif-type="itemWithIcon">
* <uif-list-item-icon>
* <uif-icon uif-type="save"></uif-icon>
* </uif-list-item-icon>
* </uif-list-item>
*/
export class ListItemIconDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<div class="ms-ListItem-itemIcon" ng-transclude></div>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemIconDirective();
return directive;
}
}
/**
* @ngdoc directive
* @name uifListItemSelectionTarget
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-selection-target>` is a directive that represents the space used to display item selection box.
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}"
* uif-unseen="{{message.isUnseen}}" uif-item="message">
* <uif-list-item-selection-target></uif-list-item-selection-target>
* </uif-list-item>
*/
export class ListItemSelectionTargetDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<div class="ms-ListItem-selectionTarget" ng-transclude></div>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemSelectionTargetDirective();
return directive;
}
}
/**
* @ngdoc directive
* @name uifListItemActions
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-actions>` is a directive that wraps any actions specified on a list item.
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}"
* uif-unseen="{{message.isUnseen}}" uif-item="message" uif-type="itemWithIcon">
* <uif-list-item-actions>
* <uif-list-item-action ng-click="mail(message)">
* <uif-icon uif-type="mail"></uif-icon>
* </uif-list-item-action>
* <uif-list-item-action ng-click="delete(message)">
* <uif-icon uif-type="trash"></uif-icon>
* </uif-list-item-action>
* <uif-list-item-action ng-click="pin(message)">
* <uif-icon uif-type="pinLeft"></uif-icon>
* </uif-list-item-action>
* </uif-list-item-actions>
* </uif-list-item>
*/
export class ListItemActionsDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<div class="ms-ListItem-actions" ng-transclude></div>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemActionsDirective();
return directive;
}
}
/**
* @ngdoc directive
* @name uifListItemAction
* @module officeuifabric.components.list
*
* @restrict E
*
* @description
* `<uif-list-item-action>` is a directive that represent a single action on a list item
*
* @see {link http://dev.office.com/fabric/components/listitem}
*
* @usage
*
* <uif-list-item ng-repeat="message in messages" uif-unread="{{message.isUnread}}"
* uif-unseen="{{message.isUnseen}}" uif-item="message" uif-type="itemWithIcon">
* <uif-list-item-actions>
* <uif-list-item-action ng-click="mail(message)">
* <uif-icon uif-type="mail"></uif-icon>
* </uif-list-item-action>
* </uif-list-item-actions>
* </uif-list-item>
*/
export class ListItemActionDirective implements angular.IDirective {
public restrict: string = 'E';
public transclude: boolean = true;
public template: string = '<div class="ms-ListItem-action" ng-transclude></div>';
public replace: boolean = false;
public static factory(): angular.IDirectiveFactory {
const directive: angular.IDirectiveFactory = () => new ListItemActionDirective();
return directive;
}
}
/**
* @ngdoc module
* @name officeuifabric.components.list
*
* @description
* List
*/
export let module: angular.IModule = angular.module('officeuifabric.components.list', ['officeuifabric.components'])
.directive('uifList', ListDirective.factory())
.directive('uifListItem', ListItemDirective.factory())
.directive('uifListItemPrimaryText', ListItemPrimaryTextDirective.factory())
.directive('uifListItemSecondaryText', ListItemSecondaryTextDirective.factory())
.directive('uifListItemTertiaryText', ListItemTertiaryTextDirective.factory())
.directive('uifListItemMetaText', ListItemMetaTextDirective.factory())
.directive('uifListItemImage', ListItemImageDirective.factory())
.directive('uifListItemIcon', ListItemIconDirective.factory())
.directive('uifListItemSelectionTarget', ListItemSelectionTargetDirective.factory())
.directive('uifListItemActions', ListItemActionsDirective.factory())
.directive('uifListItemAction', ListItemActionDirective.factory()); | the_stack |
* @title: Sound
* @description:
* This sample shows how to load and play sounds from sources moving in a 3D environment.
* You can enable and disable the movement of the different 3D sources to hear the spatial difference.
* Sounds can also be played with reverb, echo and pitch filtering effects when supported.
*/
/*{{ javascript("jslib/aabbtree.js") }}*/
/*{{ javascript("jslib/camera.js") }}*/
/*{{ javascript("jslib/floor.js") }}*/
/*{{ javascript("jslib/geometry.js") }}*/
/*{{ javascript("jslib/material.js") }}*/
/*{{ javascript("jslib/light.js") }}*/
/*{{ javascript("jslib/scenenode.js") }}*/
/*{{ javascript("jslib/scene.js") }}*/
/*{{ javascript("jslib/vmath.js") }}*/
/*{{ javascript("jslib/effectmanager.js") }}*/
/*{{ javascript("jslib/shadermanager.js") }}*/
/*{{ javascript("jslib/texturemanager.js") }}*/
/*{{ javascript("jslib/renderingcommon.js") }}*/
/*{{ javascript("jslib/defaultrendering.js") }}*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/resourceloader.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/vertexbuffermanager.js") }}*/
/*{{ javascript("jslib/indexbuffermanager.js") }}*/
/*{{ javascript("jslib/services/turbulenzservices.js") }}*/
/*{{ javascript("jslib/services/turbulenzbridge.js") }}*/
/*{{ javascript("jslib/services/gamesession.js") }}*/
/*{{ javascript("jslib/services/mappingtable.js") }}*/
/*{{ javascript("scripts/motion.js") }}*/
/*{{ javascript("scripts/htmlcontrols.js") }}*/
/*{{ javascript("scripts/sceneloader.js") }}*/
/*global TurbulenzEngine: true */
/*global Motion: false */
/*global window: false */
/*global RequestHandler: false */
/*global TextureManager: false */
/*global ShaderManager: false */
/*global EffectManager: false */
/*global Camera: false */
/*global Scene: false */
/*global SceneLoader: false */
/*global Floor: false */
/*global HTMLControls: false */
/*global DefaultRendering: false */
/*global TurbulenzServices: false */
TurbulenzEngine.onload = function onloadFn()
{
var errorCallback = function errorCallback(msg)
{
window.alert(msg);
};
// Create the engine devices objects
var graphicsDeviceParameters = { };
var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters);
if (!graphicsDevice.shadingLanguageVersion)
{
errorCallback("No shading language support detected.\nPlease check your graphics drivers are up to date.");
graphicsDevice = null;
return;
}
// Clear the background color of the engine window
var clearColor = [0.95, 0.95, 1.0, 1.0];
if (graphicsDevice.beginFrame())
{
graphicsDevice.clear(clearColor);
graphicsDevice.endFrame();
}
var mathDeviceParameters = { };
var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters);
var soundDeviceParameters = {
linearDistance : false
};
var soundDevice = TurbulenzEngine.createSoundDevice(soundDeviceParameters);
if (!soundDevice)
{
errorCallback("No SoundDevice detected.");
return;
}
var requestHandlerParameters = {};
var requestHandler = RequestHandler.create(requestHandlerParameters);
var textureManager = TextureManager.create(graphicsDevice, requestHandler, null, errorCallback);
var shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback);
var effectManager = EffectManager.create();
var scene = Scene.create(mathDevice);
var sceneLoader = SceneLoader.create();
var renderer;
// Create world
var worldUp = mathDevice.v3BuildYAxis();
var floor = Floor.create(graphicsDevice, mathDevice);
// Create moving objects
var duck1 = Motion.create(mathDevice, "Duck01");
duck1.setCircularMovement(9.0, [0, 0, 0]);
duck1.setDuckMotion(0.1, 0.5, 0.3);
var duck1OrientAngle = -90;
duck1.setBaseOrientation(duck1OrientAngle);
var duck2 = Motion.create(mathDevice, "Duck02");
duck2.setCircularMovement(7.0, [0, 0, 0]);
duck2.setDuckMotion(0.2, 0.5, 0.3);
duck2.reverseDirection();
var duck2OrientAngle = 90;
duck2.setBaseOrientation(duck2OrientAngle);
// Create fixed position for camera
// The camera exists between the duck orbits. This is so the one duck passes in front and one behind.
var cameraPosition = mathDevice.v3Build(0.0, 2.0, -8.0);
var lookAtPosition = mathDevice.v3Build(0.0, 0.0, 100.0);
// Create a sound source for each object (different pitch)
var duck1SoundSource = soundDevice.createSource({
position : duck1.position,
relative : false,
pitch : 1.0
});
var duck2SoundSource = soundDevice.createSource({
position : duck2.position,
relative : false,
pitch : 1.5
});
// Set the interval between playing the sound (in seconds)
// The ratio of the intervals is approximately 1:2
// The slight variation is so the playing of the sounds don't coincide exactly
var duck1SoundInterval = 1.1;
var duck2SoundInterval = 1.9;
// Accumulates the time elapsed before the next sound is due
var duck1TimeElapsed = 0;
var duck2TimeElapsed = 0;
// Is the duck playing the sound
var duck1PlaySound = true;
var duck2PlaySound = true;
// The sound to play
var duck1QuackSound = null;
var duck2QuackSound = null;
// Sound Effects, Filters
var reverbOn = false;
var echoOn = false;
var lowPassOn = false;
// Create effects to apply to the source
var reverb = soundDevice.createEffect({
name : "DuckReverb",
type : "Reverb",
gain : 0.3
});
var echo = soundDevice.createEffect({
name : "DuckEcho",
type : "Echo",
damping : 0.78,
lrdelay : 0.24,
delay : 0.17,
gain : 0.3
});
var lowPassFilter = soundDevice.createFilter({
name : "CutoffLowPass",
type : "LowPass",
gainHF : 0.05
});
var reverbSlot = soundDevice.createEffectSlot({
effect : reverb,
gain : 0.1
});
var echoSlot = soundDevice.createEffectSlot({
effect : echo,
gain : 0.1
});
// Create a basic camera
var camera = Camera.create(mathDevice);
camera.lookAt(lookAtPosition, worldUp, cameraPosition);
camera.updateViewMatrix();
var addCustomSceneData = function addCustomSceneDataFn(sceneData)
{
var addModel = function addModelFn(modelName, modelGeometry, modelMaterial, modelSurface, modelPosition)
{
var modelMatrix = [1, 0, 0,
0, 1, 0,
0, 0, 1,
modelPosition[0], modelPosition[1], modelPosition[2]];
sceneData.nodes[modelName] =
{
geometryinstances : {
"default": {
geometry: modelGeometry,
surface : modelSurface,
material : modelMaterial,
render : true
}
},
matrix : modelMatrix,
dynamic : true,
disabled : false,
visible : true
};
};
// Removes the default duck node in the loaded scene
delete sceneData.nodes.LOD3sp;
addModel("Duck01", "LOD3spShape", "blinn3", "blinn3SG", duck1.position);
addModel("Duck02", "LOD3spShape", "blinn3", "blinn3SG", duck2.position);
};
// Controls
var htmlControls = HTMLControls.create();
htmlControls.addCheckboxControl({
id: "checkbox01",
value: "duck1Move",
isSelected: duck1.move,
fn: function ()
{
duck1.move = !duck1.move;
return duck1.move;
}
});
htmlControls.addCheckboxControl({
id: "checkbox02",
value: "duck1PlaySound",
isSelected: duck1PlaySound,
fn: function ()
{
duck1PlaySound = !duck1PlaySound;
return duck1PlaySound;
}
});
htmlControls.addCheckboxControl({
id: "checkbox03",
value: "duck2Move",
isSelected: duck2.move,
fn: function ()
{
duck2.move = !duck2.move;
return duck2.move;
}
});
htmlControls.addCheckboxControl({
id: "checkbox04",
value: "duck2PlaySound",
isSelected: duck2PlaySound,
fn: function ()
{
duck2PlaySound = !duck2PlaySound;
return duck2PlaySound;
}
});
htmlControls.addCheckboxControl({
id: "checkbox05",
value: "reverbOn",
isSelected: reverbOn,
fn: function ()
{
if (reverb && reverbSlot)
{
if (reverbOn)
{
// Set no effect slot and no filter on auxiliary send at index 0
reverbOn = !(duck1SoundSource.setAuxiliarySendFilter(0, null, null) &&
duck2SoundSource.setAuxiliarySendFilter(0, null, null));
}
else
{
// Set the reverb effect slot on auxiliary send at index 0, no filter
reverbOn = (duck1SoundSource.setAuxiliarySendFilter(0, reverbSlot, null) &&
duck2SoundSource.setAuxiliarySendFilter(0, reverbSlot, null));
}
}
return reverbOn;
}
});
htmlControls.addCheckboxControl({
id: "checkbox06",
value: "echoOn",
isSelected: echoOn,
fn: function ()
{
if (echo && echoSlot)
{
if (echoOn)
{
// Set no effect slot and no filter on auxiliary send at index 1
echoOn = !(duck1SoundSource.setAuxiliarySendFilter(1, null, null) &&
duck2SoundSource.setAuxiliarySendFilter(1, null, null));
}
else
{
// Set the reverb effect slot on auxiliary send at index 1, no filter
echoOn = (duck1SoundSource.setAuxiliarySendFilter(1, echoSlot, null) &&
duck2SoundSource.setAuxiliarySendFilter(1, echoSlot, null));
}
}
return echoOn;
}
});
htmlControls.addCheckboxControl({
id: "checkbox07",
value: "lowPassOn",
isSelected: lowPassOn,
fn: function ()
{
if (lowPassFilter)
{
if (lowPassOn)
{
// Set filter on direct output only
lowPassOn = !(duck1SoundSource.setDirectFilter(null) &&
duck2SoundSource.setDirectFilter(null));
}
else
{
// Set no filter on direct output only
lowPassOn = (duck1SoundSource.setDirectFilter(lowPassFilter) &&
duck2SoundSource.setDirectFilter(lowPassFilter));
}
}
return lowPassOn;
}
});
var slider01ID = "slider1";
var initialGain = soundDevice.listenerGain;
htmlControls.addSliderControl({
id: slider01ID,
value: initialGain,
max: 1.0,
min: 0,
step: 0.05,
fn: function ()
{
var val = this.value;
soundDevice.listenerGain = val;
htmlControls.updateSlider(slider01ID, val);
}
});
htmlControls.addButtonControl({
id: "button01",
value: "Duck 1",
fn: function ()
{
duck1.reverseDirection();
duck1OrientAngle = -duck1OrientAngle;
duck1.setBaseOrientation(duck1OrientAngle);
}
});
htmlControls.addButtonControl({
id: "button02",
value: "Duck 2",
fn: function ()
{
duck2.reverseDirection();
duck2OrientAngle = -duck2OrientAngle;
duck2.setBaseOrientation(duck2OrientAngle);
}
});
htmlControls.register();
var reverbButton = document.getElementById("checkbox05");
if (reverbButton)
{
reverbButton.disabled = !(reverb && reverbSlot);
}
var echoButton = document.getElementById("checkbox06");
if (echoButton)
{
echoButton.disabled = !(echo && echoSlot);
}
var lowpassButton = document.getElementById("checkbox07");
if (lowpassButton)
{
lowpassButton.disabled = !(lowPassFilter);
}
// Update listener position to match camera
// This must occur everytime the listener moves
soundDevice.listenerTransform = camera.matrix;
// Initialize the previous frame time
var previousFrameTime = TurbulenzEngine.time;
var intervalID;
var playSounds = function playSoundsFn(delta)
{
if (duck1PlaySound)
{
duck1TimeElapsed += delta;
if (duck1TimeElapsed > duck1SoundInterval)
{
// Play quack sound
duck1SoundSource.play(duck1QuackSound);
duck1TimeElapsed -= duck1SoundInterval;
}
}
if (duck2PlaySound)
{
duck2TimeElapsed += delta;
if (duck2TimeElapsed > duck2SoundInterval)
{
// Play quack sound
duck2SoundSource.play(duck2QuackSound);
duck2TimeElapsed -= duck2SoundInterval;
}
}
};
// Callback to draw extra debug information
function drawDebugCB()
{
floor.render(graphicsDevice, camera);
}
//
// Update
//
var update = function updateFn()
{
var currentTime = TurbulenzEngine.time;
var deltaTime = (currentTime - previousFrameTime);
if (deltaTime > 0.1)
{
deltaTime = 0.1;
}
// Update the aspect ratio of the camera in case of window resizes
var deviceWidth = graphicsDevice.width;
var deviceHeight = graphicsDevice.height;
var aspectRatio = (deviceWidth / deviceHeight);
if (aspectRatio !== camera.aspectRatio)
{
camera.aspectRatio = aspectRatio;
camera.updateProjectionMatrix();
}
camera.updateViewProjectionMatrix();
// Update duck movement and rotation
duck1.update(deltaTime);
duck2.update(deltaTime);
// Update sound source position
duck1SoundSource.position = duck1.position;
duck2SoundSource.position = duck2.position;
// Play sound if interval has elapsed
playSounds(deltaTime);
// Update duck1 position in scene
var duck1Node = scene.findNode("Duck01");
if (duck1Node)
{
duck1Node.setLocalTransform(duck1.matrix);
}
// Update duck2 position in scene
var duck2Node = scene.findNode("Duck02");
if (duck2Node)
{
duck2Node.setLocalTransform(duck2.matrix);
}
// Update scene
scene.update();
// Update renderer
renderer.update(graphicsDevice, camera, scene, currentTime);
soundDevice.update();
// Render frame
if (graphicsDevice.beginFrame())
{
if (renderer.updateBuffers(graphicsDevice, deviceWidth, deviceHeight))
{
renderer.draw(graphicsDevice, clearColor, null, null, drawDebugCB);
}
graphicsDevice.endFrame();
}
previousFrameTime = currentTime;
};
var loadingLoop = function loadingLoopFn()
{
if (sceneLoader.complete() && duck1QuackSound && duck2QuackSound)
{
TurbulenzEngine.clearInterval(intervalID);
renderer.updateShader(shaderManager);
intervalID = TurbulenzEngine.setInterval(update, 1000 / 60);
}
};
intervalID = TurbulenzEngine.setInterval(loadingLoop, 1000 / 10);
var loadAssets = function loadAssetsFn(mappingTable)
{
// Create the sound for the source to emit
var soundURL;
if (soundDevice.isSupported("FILEFORMAT_OGG"))
{
soundURL = mappingTable.getURL("sounds/duck.ogg");
}
else
{
soundURL = mappingTable.getURL("sounds/duck.mp3");
}
soundDevice.createSound({
src: soundURL,
onload : function (sound)
{
if (sound)
{
duck1QuackSound = sound;
duck2QuackSound = sound;
}
else
{
errorCallback('Failed to load sound.');
}
}
});
// Renderer for the scene (requires shader assets).
renderer = DefaultRendering.create(graphicsDevice,
mathDevice,
shaderManager,
effectManager);
renderer.setGlobalLightPosition(mathDevice.v3Build(0.5, 100.0, 0.5));
renderer.setAmbientColor(mathDevice.v3Build(0.3, 0.3, 0.4));
renderer.setDefaultTexture(textureManager.get("default"));
// Create & load duck scene
sceneLoader.load({ scene : scene,
append : true,
assetPath : "models/duck.dae",
keepLights : true,
baseScene : null,
baseMatrix : null,
skin : null,
graphicsDevice : graphicsDevice,
mathDevice : mathDevice,
textureManager : textureManager,
shaderManager : shaderManager,
effectManager : effectManager,
requestHandler : requestHandler,
preSceneLoadFn : addCustomSceneData
});
};
var mappingTableReceived = function mappingTableReceivedFn(mappingTable)
{
textureManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix);
shaderManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix);
sceneLoader.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix);
loadAssets(mappingTable);
};
var gameSessionCreated = function gameSessionCreatedFn(gameSession)
{
TurbulenzServices.createMappingTable(requestHandler,
gameSession,
mappingTableReceived);
};
var gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated);
// Create a scene destroy callback to run when the window is closed
TurbulenzEngine.onunload = function destroyScene()
{
TurbulenzEngine.clearInterval(intervalID);
if (gameSession)
{
gameSession.destroy();
gameSession = null;
}
clearColor = null;
worldUp = null;
floor = null;
if (renderer)
{
renderer.destroy();
renderer = null;
}
reverb = null;
echo = null;
lowPassFilter = null;
reverbSlot = null;
echoSlot = null;
duck1 = null;
duck2 = null;
if (duck1SoundSource)
{
duck1SoundSource.setDirectFilter(null);
duck1SoundSource.setAuxiliarySendFilter(0, null, null);
duck1SoundSource.setAuxiliarySendFilter(1, null, null);
duck1SoundSource.destroy();
duck1SoundSource = null;
}
if (duck2SoundSource)
{
duck2SoundSource.setDirectFilter(null);
duck2SoundSource.setAuxiliarySendFilter(0, null, null);
duck2SoundSource.setAuxiliarySendFilter(1, null, null);
duck2SoundSource.destroy();
duck2SoundSource = null;
}
if (duck1QuackSound)
{
duck1QuackSound.destroy();
duck1QuackSound = null;
}
if (duck2QuackSound)
{
duck2QuackSound.destroy();
duck2QuackSound = null;
}
if (scene)
{
scene.destroy();
scene = null;
}
requestHandler = null;
sceneLoader = null;
camera = null;
if (textureManager)
{
textureManager.destroy();
textureManager = null;
}
if (shaderManager)
{
shaderManager.destroy();
shaderManager = null;
}
effectManager = null;
TurbulenzEngine.flush();
graphicsDevice = null;
mathDevice = null;
soundDevice = null;
};
}; | the_stack |
import {Entity, Service, WhereAttributeSymbol, UpdateEntityItem, Schema} from ".";
import {expectType, expectError, expectAssignable, expectNotAssignable, expectNotType} from 'tsd';
let entityWithSK = new Entity({
model: {
entity: "abc",
service: "myservice",
version: "myversion"
},
attributes: {
attr1: {
type: "string",
default: "abc",
get: (val) => val + 123,
set: (val) => (val ?? "") + 456,
validate: (val) => !!val,
},
attr2: {
type: "string",
// default: () => "sfg",
// required: false,
validate: (val) => val.length > 0
},
attr3: {
type: ["123", "def", "ghi"] as const,
default: "def"
},
attr4: {
type: ["abc", "ghi"] as const,
required: true
},
attr5: {
type: "string"
},
attr6: {
type: "number",
default: () => 100,
get: (val) => val + 5,
set: (val) => (val ?? 0) + 5,
validate: (val) => true,
},
attr7: {
type: "any",
default: () => false,
get: (val) => ({key: "value"}),
set: (val) => (val ?? 0) + 5,
validate: (val) => true,
},
attr8: {
type: "boolean",
required: true,
get: (val) => !!val,
set: (val) => !!val,
validate: (val) => !!val,
},
attr9: {
type: "number"
},
attr10: {
type: "boolean"
}
},
indexes: {
myIndex: {
collection: "mycollection2",
pk: {
field: "pk",
composite: ["attr1"]
},
sk: {
field: "sk",
composite: ["attr2"]
}
},
myIndex2: {
collection: "mycollection1",
index: "gsi1",
pk: {
field: "gsipk1",
composite: ["attr6", "attr9"]
},
sk: {
field: "gsisk1",
composite: ["attr4", "attr5"]
}
},
myIndex3: {
collection: "mycollection",
index: "gsi2",
pk: {
field: "gsipk2",
composite: ["attr5"]
},
sk: {
field: "gsisk2",
composite: ["attr4", "attr3", "attr9"]
}
}
}
});
let entityWithoutSK = new Entity({
model: {
entity: "abc",
service: "myservice",
version: "myversion"
},
attributes: {
attr1: {
type: "string",
// default: "abc",
get: (val) => val + 123,
set: (val) => (val ?? "0") + 456,
validate: (val) => !!val,
},
attr2: {
type: "string",
// default: () => "sfg",
// required: false,
validate: (val) => val.length > 0
},
attr3: {
type: ["123", "def", "ghi"] as const,
default: "def"
},
attr4: {
type: ["abc", "def"] as const,
required: true
},
attr5: {
type: "string"
},
attr6: {
type: "number",
default: () => 100,
get: (val) => val + 5,
set: (val) => (val ?? 0) + 5,
validate: (val) => true,
},
attr7: {
type: "any",
default: () => false,
get: (val) => ({key: "value"}),
set: (val) => (val ?? 0) + 5,
validate: (val) => true,
},
attr8: {
type: "boolean",
required: true,
default: () => false,
get: (val) => !!val,
set: (val) => !!val,
validate: (val) => !!val,
},
attr9: {
type: "number"
}
},
indexes: {
myIndex: {
pk: {
field: "pk",
composite: ["attr1"]
}
},
myIndex2: {
index: "gsi1",
collection: "mycollection1",
pk: {
field: "gsipk1",
composite: ["attr6", "attr9"]
},
sk: {
field: "gsisk1",
composite: []
}
},
myIndex3: {
collection: "mycollection",
index: "gsi2",
pk: {
field: "gsipk2",
composite: ["attr5"]
},
sk: {
field: "gsisk2",
composite: []
}
}
}
});
let standAloneEntity = new Entity({
model: {
entity: "standalone",
service: "myservice",
version: "1"
},
attributes: {
prop1: {
type: "string",
default: "abc"
},
prop2: {
type: "string"
},
prop3: {
type: "string"
}
},
indexes: {
index1: {
pk: {
field: "pk",
composite: ["prop1", "prop2"]
},
sk: {
field: "sk",
composite: ["prop3"]
}
}
}
});
let normalEntity1 = new Entity({
model: {
entity: "normalEntity1",
service: "myservice",
version: "1"
},
attributes: {
prop1: {
type: "string",
default: "abc"
},
prop2: {
type: "string"
},
prop3: {
type: "string",
required: true
},
prop4: {
type: "number"
},
prop10: {
type: "boolean"
}
},
indexes: {
tableIndex: {
collection: "normalcollection",
pk: {
field: "pk",
composite: ["prop1", "prop2"]
},
sk: {
field: "sk",
composite: ["prop4"]
}
}
}
});
let normalEntity2 = new Entity({
model: {
entity: "normalEntity2",
service: "myservice",
version: "1"
},
attributes: {
prop1: {
type: "string"
},
prop2: {
type: "string"
},
prop3: {
type: "string",
required: true
},
prop5: {
type: "number"
},
attr6: {
type: "number",
default: () => 100,
get: (val) => val + 5,
set: (val) => (val ?? 0) + 5,
validate: (val) => true,
},
attr9: {
type: "number"
},
},
indexes: {
indexTable: {
collection: "normalcollection",
pk: {
field: "pk",
composite: ["prop1", "prop2"]
},
sk: {
field: "sk",
composite: ["prop5"]
}
},
anotherIndex: {
index: "gsi1",
collection: "mycollection1",
pk: {
field: "gsipk1",
composite: ["attr6", "attr9"]
},
sk: {
field: "gsisk1",
composite: []
}
}
}
});
type Item = {
attr1?: string;
attr2: string;
attr3?: "123" | "def" | "ghi" | undefined;
attr4: string;
attr5?: string;
attr6?: number;
attr7?: any;
attr8: boolean;
attr9?: number;
attr10?: boolean;
}
type ItemWithoutSK = {
attr1?: string;
attr2?: string;
attr3?: "123" | "def" | "ghi" | undefined;
attr4: string;
attr5?: string;
attr6?: number;
attr7?: any;
attr8: boolean;
attr9?: number;
}
const item: Item = {
attr1: "attr1",
attr2: "attr2",
attr3: "def",
attr4: "attr4",
attr5: "attr5",
attr6: 123,
attr7: "attr7",
attr8: true,
attr9: 456
} as const
type AttributeNames = "attr1" | "attr2" | "attr3" | "attr4" | "attr5" | "attr6" | "attr7" | "attr8" | "attr9";
const AttributeName = "" as AttributeNames;
type OperationNames = "eq" | "ne" | "gt" | "lt" | "gte" | "lte" | "between" | "begins" | "exists" | "notExists" | "contains" | "notContains" | "value" | "name";
type WithSKMyIndexCompositeAttributes = {
attr1: string;
attr2: string;
}
type WithSKMyIndex2CompositeAttributes = {
attr6: string;
attr4?: string;
attr5?: string;
}
type WithSKMyIndex3CompositeAttributes = {
attr5: string;
attr3?: "123" | "def" | "ghi";
attr4?: string;
attr9?: number;
}
type WithoutSKMyIndexCompositeAttributes = {
attr1: string;
}
type WithoutSKMyIndex2CompositeAttributes = {
attr6: number;
attr9: number;
}
type WithoutSKMyIndex3CompositeAttributes = {
attr5: string;
}
type Parameter<T extends (arg: any) => any> = T extends (arg: infer P) => any ? P : never;
type GetKeys = <T extends {[key: string]: any}>(obj: T) => keyof T;
let getKeys = ((val) => {}) as GetKeys;
/** Schema With SK **/
// Get
// Single
entityWithSK.get({attr1: "adg", attr2: "ada"});
entityWithoutSK.get({attr1: "abc"});
// Batch
type GetBatchParametersWithSK = Parameter<typeof entityWithSK.get>;
type GetBatchParametersWithoutSK = Parameter<typeof entityWithoutSK.get>;
expectAssignable<GetBatchParametersWithSK>([{attr1: "abc", attr2: "abd"}]);
expectAssignable<GetBatchParametersWithoutSK>([{attr1: "abc"}]);
// Invalid Get
expectError<GetBatchParametersWithSK>([{}]);
expectError<GetBatchParametersWithSK>([{attr1: "sdggd"}]);
expectError<GetBatchParametersWithSK>([{attr2: "sdggd"}]);
expectError<GetBatchParametersWithSK>({attr1: 1324, attr2: "adsga"});
expectError<GetBatchParametersWithoutSK>([{}]);
expectError<GetBatchParametersWithoutSK>([{attr2: "adsga"}]);
expectError<GetBatchParametersWithoutSK>({attr2: "adsga"});
expectError<GetBatchParametersWithoutSK>({attr1: 1324, attr2: "adsga"});
// Finishers
type GetParametersFinishers = "go" | "params" | "where";
let getSingleFinishersWithSK = getKeys(entityWithSK.get({attr1:"abc", attr2: "24"}));
let getBatchFinishersWithSK = getKeys(entityWithSK.get([{attr1:"abc", attr2: "24"}]));
let getSingleFinishersWithoutSK = getKeys(entityWithoutSK.get({attr1:"abc"}));
let getBatchFinishersWithoutSK = getKeys(entityWithoutSK.get([{attr1:"abc"}]));
expectAssignable<GetParametersFinishers>(getSingleFinishersWithSK);
expectAssignable<GetParametersFinishers>(getBatchFinishersWithSK);
expectAssignable<GetParametersFinishers>(getSingleFinishersWithoutSK);
expectAssignable<GetParametersFinishers>(getBatchFinishersWithoutSK);
entityWithSK.get([{attr1: "adg", attr2: "ada"}]).go({concurrency: 24});
entityWithSK.get([{attr1: "adg", attr2: "ada"}]).params({concurrency: 24});
entityWithoutSK.get([{attr1: "adg"}]).go({concurrency: 24});
entityWithoutSK.get([{attr1: "adg"}]).params({concurrency: 24});
let getSingleGoWithSK = entityWithSK.get({attr1: "adg", attr2: "ada"}).go;
let getSingleGoWithoutSK = entityWithoutSK.get({attr1: "adg"}).go;
let getSingleParamsWithSK = entityWithSK.get({attr1: "adg", attr2: "ada"}).params;
let getSingleParamsWithoutSK = entityWithoutSK.get({attr1: "adg"}).params;
let getBatchGoWithSK = entityWithSK.get([{attr1: "adg", attr2: "ada"}]).go;
let getBatchGoWithoutSK = entityWithoutSK.get([{attr1: "adg"}]).go;
let getBatchParamsWithSK = entityWithSK.get([{attr1: "adg", attr2: "ada"}]).params;
let getBatchParamsWithoutSK = entityWithoutSK.get([{attr1: "adg"}]).params;
type GetSingleGoParamsWithSK = Parameter<typeof getSingleGoWithSK>;
type GetSingleGoParamsWithoutSK = Parameter<typeof getSingleGoWithoutSK>;
type GetSingleParamsParamsWithSK = Parameter<typeof getSingleParamsWithSK>;
type GetSingleParamsParamsWithoutSK = Parameter<typeof getSingleParamsWithoutSK>;
type GetBatchGoParamsWithSK = Parameter<typeof getBatchGoWithSK>;
type GetBatchGoParamsWithoutSK = Parameter<typeof getBatchGoWithoutSK>;
type GetBatchParamsParamsWithSK = Parameter<typeof getBatchParamsWithSK>;
type GetBatchParamsParamsWithoutSK = Parameter<typeof getBatchParamsWithoutSK>;
expectAssignable<GetSingleGoParamsWithSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<GetSingleGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<GetSingleParamsParamsWithSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<GetSingleParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectError<GetSingleGoParamsWithSK>({concurrency: 10, unprocessed: "raw"});
expectError<GetSingleGoParamsWithoutSK>({concurrency: 10, unprocessed: "raw"});
expectError<GetSingleParamsParamsWithSK>({concurrency: 10, unprocessed: "raw"});
expectError<GetSingleParamsParamsWithoutSK>({concurrency: 10, unprocessed: "raw"});
expectAssignable<GetBatchGoParamsWithSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectAssignable<GetBatchGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectAssignable<GetBatchParamsParamsWithSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectAssignable<GetBatchParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
// Results
expectAssignable<Promise<Item>>(entityWithSK.get({attr1: "abc", attr2: "def"}).go());
expectAssignable<Promise<ItemWithoutSK>>(entityWithoutSK.get({attr1: "abc"}).go());
expectAssignable<"paramtest">(entityWithSK.get({attr1: "abc", attr2: "def"}).params<"paramtest">());
expectAssignable<"paramtest">(entityWithoutSK.get({attr1: "abc"}).params<"paramtest">());
expectAssignable<Promise<[WithSKMyIndexCompositeAttributes[], Item[]]>>(entityWithSK.get([{attr1: "abc", attr2: "def"}]).go());
expectAssignable<Promise<[WithoutSKMyIndexCompositeAttributes[], ItemWithoutSK[]]>>(entityWithoutSK.get([{attr1: "abc"}]).go());
// Delete
// Single
entityWithSK.delete({attr1: "adg", attr2: "ada"});
entityWithoutSK.delete({attr1: "adg"});
// Batch
type DeleteBatchParametersWithSK = Parameter<typeof entityWithSK.delete>;
type DeleteBatchParametersWithoutSK = Parameter<typeof entityWithoutSK.delete>;
expectError(entityWithSK.delete({}));
expectError(entityWithSK.delete({attr2: "abc"}));
expectError(entityWithoutSK.delete({}));
expectError(entityWithoutSK.delete({attr1: "13", attr2: "abc"}));
expectAssignable<DeleteBatchParametersWithSK>([{attr1: "abc", attr2: "abd"}]);
expectAssignable<DeleteBatchParametersWithoutSK>([{attr1: "abc"}]);
// Invalid Query
expectError<DeleteBatchParametersWithSK>({attr1: "sdggd"});
expectError<DeleteBatchParametersWithoutSK>([{}]);
expectError<DeleteBatchParametersWithSK>({attr1: 1324, attr2: "adsga"});
expectError<DeleteBatchParametersWithoutSK>({attr1: 1324, attr2: "adsga"});
// Finishers
type DeleteParametersFinishers = "go" | "params" | "where";
let deleteSingleFinishers = getKeys(entityWithSK.delete({attr1:"abc", attr2: "24"}));
let deleteSingleFinishersWithoutSK = getKeys(entityWithoutSK.delete({attr1:"abc"}));
let deleteBatchFinishers = getKeys(entityWithSK.delete([{attr1:"abc", attr2: "24"}]));
let deleteBatchFinishersWithoutSK = getKeys(entityWithoutSK.delete([{attr1:"abc"}]));
expectAssignable<DeleteParametersFinishers>(deleteSingleFinishers);
expectAssignable<DeleteParametersFinishers>(deleteSingleFinishersWithoutSK);
expectAssignable<DeleteParametersFinishers>(deleteBatchFinishers);
expectAssignable<DeleteParametersFinishers>(deleteBatchFinishersWithoutSK);
entityWithSK.delete([{attr1: "adg", attr2: "ada"}]).go({concurrency: 24});
entityWithoutSK.delete([{attr1: "adg"}]).go({concurrency: 24});
entityWithSK.delete([{attr1: "adg", attr2: "ada"}]).params({concurrency: 24});
entityWithoutSK.delete([{attr1: "adg"}]).params({concurrency: 24});
let deleteSingleGo = entityWithSK.delete({attr1: "adg", attr2: "ada"}).go;
let deleteSingleGoWithoutSK = entityWithoutSK.delete({attr1: "adg"}).go;
let deleteSingleParams = entityWithSK.delete({attr1: "adg", attr2: "ada"}).params;
let deleteSingleParamsWithoutSK = entityWithoutSK.delete({attr1: "adg"}).params;
let deleteBatchGo = entityWithSK.delete([{attr1: "adg", attr2: "ada"}]).go;
let deleteBatchGoWithoutSK = entityWithoutSK.delete([{attr1: "adg"}]).go;
let deleteBatchParams = entityWithSK.delete([{attr1: "adg", attr2: "ada"}]).params;
let deleteBatchParamsWithoutSK = entityWithoutSK.delete([{attr1: "adg"}]).params;
type DeleteSingleGoParams = Parameter<typeof deleteSingleGo>;
type DeleteSingleGoParamsWithoutSK = Parameter<typeof deleteSingleGoWithoutSK>;
type DeleteSingleParamsParams = Parameter<typeof deleteSingleParams>;
type DeleteSingleParamsParamsWithoutSK = Parameter<typeof deleteSingleParamsWithoutSK>;
type DeleteBatchGoParams = Parameter<typeof deleteBatchGo>;
type DeleteBatchGoParamsWithoutSK = Parameter<typeof deleteBatchGoWithoutSK>;
type DeleteBatchParamsParams = Parameter<typeof deleteBatchParams>;
type DeleteBatchParamsParamsWithoutSK = Parameter<typeof deleteBatchParamsWithoutSK>;
expectAssignable<DeleteSingleGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "all_old"});
expectAssignable<DeleteSingleGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "all_old"});
expectAssignable<DeleteSingleGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<DeleteSingleGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<DeleteSingleParamsParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "all_old"});
expectAssignable<DeleteSingleParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "all_old"});
expectAssignable<DeleteSingleParamsParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<DeleteSingleParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectError<DeleteSingleGoParams>({concurrency: 10, unprocessed: "raw"});
expectError<DeleteSingleGoParamsWithoutSK>({concurrency: 10, unprocessed: "raw"});
expectNotAssignable<DeleteSingleGoParams>({response: "updated_new"});
expectNotAssignable<DeleteSingleGoParamsWithoutSK>({response: "updated_new"});
expectError<DeleteSingleParamsParams>({concurrency: 10, unprocessed: "raw"});
expectError<DeleteSingleParamsParamsWithoutSK>({concurrency: 10, unprocessed: "raw"});
expectNotAssignable<DeleteSingleParamsParams>({response: "updated_new"});
expectNotAssignable<DeleteSingleParamsParamsWithoutSK>({response: "updated_new"});
expectAssignable<DeleteBatchGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectAssignable<DeleteBatchGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectAssignable<DeleteBatchParamsParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectAssignable<DeleteBatchParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
// Where
entityWithSK.delete({attr1: "asbc", attr2: "gdd"}).where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
entityWithoutSK.delete({attr1: "asbc"}).where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
// Results
expectAssignable<Promise<Item>>(entityWithSK.delete({attr1: "abc", attr2: "def"}).go({response: "all_old"}));
expectAssignable<Promise<ItemWithoutSK>>(entityWithoutSK.delete({attr1: "abc"}).go({response: "all_old"}));
expectAssignable<"paramtest">(entityWithSK.delete({attr1: "abc", attr2: "def"}).params<"paramtest">());
expectAssignable<"paramtest">(entityWithoutSK.delete({attr1: "abc"}).params<"paramtest">());
expectAssignable<Promise<WithoutSKMyIndexCompositeAttributes[]>>(entityWithoutSK.delete([{attr1: "abc"}]).go());
// Put
let putItemFull = {attr1: "abnc", attr2: "dsg", attr3: "def", attr4: "abc", attr5: "dbs", attr6: 13, attr7: {abc: "2345"}, attr8: true, attr9: 24, attr10: true} as const;
let putItemPartial = {attr1: "abnc", attr2: "dsg", attr4: "abc", attr8: true} as const;
let putItemWithoutSK = {attr1: "abnc", attr4: "abc", attr8: true, attr3: "def", attr5: "dbs", attr6: 13, attr9: 24, attr7: {abc: "2345"}} as const;
let putItemWithoutPK = {attr4: "abc", attr2: "def", attr8: true, attr3: "def", attr5: "dbs", attr6: 13, attr9: 24, attr7: {abc: "2345"}} as const;
// Single
entityWithSK.put(putItemFull);
entityWithoutSK.put({attr1: "abnc", attr2: "dsg", attr3: "def", attr4: "def", attr5: "dbs", attr6: 13, attr7: {abc: "2345"}, attr8: true, attr9: 24});
entityWithSK.put({attr1: "abnc", attr2: "dsg", attr3: "def", attr4: "abc", attr5: "dbs", attr6: 13, attr7: {abc: "2345"}, attr8: true, attr9: undefined, attr10: undefined});
entityWithoutSK.put(putItemPartial);
// Batch
type PutParametersWithSK = Parameter<typeof entityWithSK.put>;
type PutParametersWithoutSK = Parameter<typeof entityWithoutSK.put>;
expectAssignable<PutParametersWithSK>([putItemFull]);
expectAssignable<PutParametersWithoutSK>([putItemFull]);
expectAssignable<PutParametersWithSK>([putItemPartial]);
expectAssignable<PutParametersWithoutSK>([putItemPartial]);
// Invalid Query
expectError<PutParametersWithSK>([{}]);
expectError<PutParametersWithoutSK>([{}]);
expectError<PutParametersWithSK>([putItemWithoutSK]);
expectError<PutParametersWithSK>(putItemWithoutSK);
expectError<PutParametersWithSK>(putItemWithoutPK);
expectError<PutParametersWithoutSK>(putItemWithoutPK);
// Assignable because attr1 has a default
expectAssignable<PutParametersWithSK>([putItemWithoutPK]);
expectError<PutParametersWithoutSK>([putItemWithoutPK]);
expectError<PutParametersWithSK>([{attr1: "abnc", attr2: "dsg", attr4: "abc", attr8: "adef"}]);
expectError<PutParametersWithoutSK>([{attr1: "abnc", attr2: "dsg", attr4: "abc", attr8: "adef"}]);
// Finishers
type PutSingleFinishers = "go" | "params" | "where";
type PutBatchFinishers = "go" | "params" | "where" | "page";
let putSingleFinishers = getKeys(entityWithSK.put(putItemFull));
let putSingleFinishersWithoutSK = getKeys(entityWithoutSK.put(putItemFull));
let putBatchFinishers = getKeys(entityWithSK.put(putItemFull));
let putBatchFinishersWithoutSK = getKeys(entityWithoutSK.put(putItemFull));
let putSingleItem = entityWithSK.put(putItemFull);
let putSingleItemWithoutSK = entityWithoutSK.put(putItemFull);
let putBulkItem = entityWithSK.put([putItemFull]);
let putBulkItemWithoutSK = entityWithoutSK.put([putItemFull]);
expectAssignable<PutSingleFinishers>(putSingleFinishers);
expectAssignable<PutSingleFinishers>(putSingleFinishersWithoutSK);
expectAssignable<PutBatchFinishers>(putBatchFinishers);
expectAssignable<PutBatchFinishers>(putBatchFinishersWithoutSK);
type PutSingleGoParams = Parameter<typeof putSingleItem.go>;
type PutSingleGoParamsWithoutSK = Parameter<typeof putSingleItemWithoutSK.go>;
type PutSingleParamsParams = Parameter<typeof putSingleItem.params>;
type PutSingleParamsParamsWithoutSK = Parameter<typeof putSingleItemWithoutSK.params>;
type PutBatchGoParams = Parameter<typeof putBulkItem.go>;
type PutBatchGoParamsWithoutSK = Parameter<typeof putBulkItemWithoutSK.go>;
type PutBatchParamsParams = Parameter<typeof putBulkItem.params>;
type PutBatchParamsParamsWithoutSK = Parameter<typeof putBulkItemWithoutSK.params>;
expectAssignable<PutSingleGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "all_old"});
expectAssignable<PutSingleGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "all_old"});
expectAssignable<PutSingleParamsParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "all_old"});
expectAssignable<PutSingleParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "all_old"});
expectError<PutSingleGoParams>({concurrency: 10, unprocessed: "raw"});
expectError<PutSingleGoParamsWithoutSK>({concurrency: 10, unprocessed: "raw"});
expectError<PutSingleGoParams>({response: "updated_new"});
expectError<PutSingleGoParamsWithoutSK>({response: "updated_new"});
expectError<PutSingleParamsParams>({response: "updated_new"});
expectError<PutSingleParamsParamsWithoutSK>({response: "updated_new"});
expectError<PutSingleParamsParams>({concurrency: 10, unprocessed: "raw"});
expectError<PutSingleParamsParamsWithoutSK>({concurrency: 10, unprocessed: "raw"});
expectAssignable<PutBatchGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectAssignable<PutBatchGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectNotAssignable<PutBatchGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw", response: "all_old"});
expectNotAssignable<PutBatchGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw", response: "all_old"});
expectAssignable<PutBatchParamsParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectAssignable<PutBatchParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw"});
expectNotAssignable<PutBatchParamsParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw", response: "all_old"});
expectNotAssignable<PutBatchParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", concurrency: 10, unprocessed: "raw", response: "all_old"});
// Where
entityWithSK.put(putItemFull).where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
entityWithoutSK.put(putItemFull).where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
// Results
expectAssignable<Promise<Item>>(entityWithSK.put(putItemFull).go());
expectAssignable<Promise<ItemWithoutSK>>(entityWithoutSK.put(putItemFull).go());
expectAssignable<"paramtest">(entityWithSK.put(putItemFull).params<"paramtest">());
expectAssignable<"paramtest">(entityWithoutSK.put(putItemFull).params<"paramtest">());
expectAssignable<Promise<WithSKMyIndexCompositeAttributes[]>>(entityWithSK.put([putItemFull]).go());
expectAssignable<Promise<WithoutSKMyIndexCompositeAttributes[]>>(entityWithoutSK.put([putItemFull]).go());
// Create
let createItemFull = {attr1: "abnc", attr2: "dsg", attr4: "abc", attr8: true, attr3: "def", attr5: "dbs", attr6: 13, attr9: 24, attr7: {abc: "2345"}} as const;
let createItemPartial = {attr1: "abnc", attr2: "dsg", attr4: "abc", attr8: true} as const;
let createItemFullWithoutSK = {attr4: "abc", attr8: true, attr3: "def", attr5: "dbs", attr6: 13, attr9: 24, attr7: {abc: "2345"}} as const;
let createItemFullWithoutPK = {attr2: "dsg", attr4: "abc", attr8: true, attr3: "def", attr5: "dbs", attr6: 13, attr9: 24, attr7: {abc: "2345"}} as const;
// Single
entityWithSK.create(createItemFull);
entityWithSK.create(createItemFullWithoutPK);
entityWithoutSK.create(createItemFull);
entityWithSK.create(createItemPartial);
entityWithoutSK.create(createItemPartial);
// Batch
type CreateParametersWithSK = Parameter<typeof entityWithSK.create>;
type CreateParametersWithoutSK = Parameter<typeof entityWithoutSK.create>;
// batch not supported with create
expectError<CreateParametersWithSK>([createItemFull]);
expectError<CreateParametersWithoutSK>([createItemFull]);
// batch not supported with create
expectError<CreateParametersWithSK>([createItemPartial]);
expectError<CreateParametersWithoutSK>([createItemPartial]);
// Invalid Query
expectError<CreateParametersWithSK>({});
expectError<CreateParametersWithoutSK>({});
expectError<CreateParametersWithSK>(createItemFullWithoutSK);
// Assignable because attr1 has a default value
expectAssignable<CreateParametersWithSK>(createItemFullWithoutPK);
expectError<CreateParametersWithoutSK>(createItemFullWithoutPK);
// Missing required properties
expectError<CreateParametersWithSK>([{attr1: "abnc", attr2: "dsg", attr4: "abc", attr8: "adef"}]);
expectError<CreateParametersWithoutSK>([{attr1: "abnc", attr2: "dsg", attr4: "abc", attr8: "adef"}]);
// Finishers
type CreateSingleFinishers = "go" | "params" | "where";
let createSingleFinishers = getKeys(entityWithSK.create(putItemFull));
let createSingleFinishersWithoutSK = getKeys(entityWithoutSK.create(putItemFull));
let createItem = entityWithSK.put(createItemFull);
let createItemWithoutSK = entityWithoutSK.put(createItemFull);
expectAssignable<CreateSingleFinishers>(createSingleFinishers);
expectAssignable<CreateSingleFinishers>(createSingleFinishersWithoutSK);
type CreateGoParams = Parameter<typeof createItem.go>;
type CreateGoParamsWithoutSK = Parameter<typeof createItemWithoutSK.go>;
type CreateParamsParams = Parameter<typeof createItem.params>;
type CreateParamsParamsWithoutSK = Parameter<typeof createItemWithoutSK.params>;
expectAssignable<CreateGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<CreateGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<CreateParamsParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<CreateParamsParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectError<CreateGoParams>({concurrency: 10, unprocessed: "raw"});
expectError<CreateGoParamsWithoutSK>({concurrency: 10, unprocessed: "raw"});
expectError<CreateParamsParams>({concurrency: 10, unprocessed: "raw"});
expectError<CreateParamsParamsWithoutSK>({concurrency: 10, unprocessed: "raw"});
// Where
entityWithSK.create(putItemFull).where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
entityWithoutSK.create(putItemFull).where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
// Results
expectAssignable<Promise<Item>>(entityWithSK.create(putItemFull).go());
expectAssignable<Promise<ItemWithoutSK>>(entityWithoutSK.create(putItemFull).go());
expectAssignable<"paramtest">(entityWithSK.create(putItemFull).params<"paramtest">());
expectAssignable<"paramtest">(entityWithoutSK.create(putItemFull).params<"paramtest">());
// Update
let setItemFull = {attr4: "abc", attr8: true, attr3: "def", attr5: "dbs", attr6: 13, attr9: 24, attr7: {abc: "2345"}} as const;
let setFn = entityWithSK.update({attr1: "abc", attr2: "def"}).set;
let setFnWithoutSK = entityWithoutSK.update({attr1: "abc"}).set;
type SetParameters = Parameter<typeof setFn>;
type SetParametersWithoutSK = Parameter<typeof setFnWithoutSK>;
expectAssignable<SetParameters>(setItemFull);
expectAssignable<SetParametersWithoutSK>(setItemFull);
expectAssignable<SetParameters>({});
expectAssignable<SetParametersWithoutSK>({});
// Invalid Set
expectError<SetParameters>({attr1: "ff"});
expectError<SetParametersWithoutSK>({attr1: "ff"});
expectError<SetParameters>({attr6: "1234"});
expectError<SetParametersWithoutSK>({attr6: "1234"});
// Finishers
type UpdateParametersFinishers = "set" | "delete" | "remove" | "go" | "params" | "where" | "add" | "subtract" | "append" | "data";
let updateItem = entityWithSK.update({attr1: "abc", attr2: "def"}).set({});
let updateItemWithoutSK = entityWithoutSK.update({attr1: "abc"}).set({});
let updateFinishers = getKeys(updateItem);
let updateFinishersWithoutSK = getKeys(updateItemWithoutSK);
expectAssignable<UpdateParametersFinishers>(updateFinishers);
expectAssignable<UpdateParametersFinishers>(updateFinishersWithoutSK);
let updateGo = updateItem.go;
let updateGoWithoutSK = updateItemWithoutSK.go;
let updateParams = updateItem.params;
let updateParamsWithoutSK = updateItemWithoutSK.params;
type UpdateGoParams = Parameter<typeof updateGo>;
type UpdateGoParamsWithoutSK = Parameter<typeof updateGoWithoutSK>;
type UpdateParamsParams = Parameter<typeof updateParams>;
type UpdateParamsParamsWithoutSK = Parameter<typeof updateParamsWithoutSK>;
expectAssignable<UpdateGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "updated_new"});
expectAssignable<UpdateGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "updated_new"});
expectAssignable<UpdateParamsParams>({params: {}, table: "abc", response: "updated_new"});
expectAssignable<UpdateParamsParamsWithoutSK>({params: {}, table: "abc", response: "updated_new"});
// Where
updateItem.where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
updateItemWithoutSK.where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
// Patch
let patchItemFull = {attr4: "abc", attr8: true, attr3: "def", attr5: "dbs", attr6: 13, attr9: 24, attr7: {abc: "2345"}} as const;
let patchFn = entityWithSK.patch({attr1: "abc", attr2: "def"}).set;
let patchFnWithoutSK = entityWithoutSK.patch({attr1: "abc"}).set;
type PatchParameters = Parameter<typeof patchFn>;
type PatchParametersWithoutSK = Parameter<typeof patchFnWithoutSK>;
expectAssignable<PatchParameters>(patchItemFull);
expectAssignable<PatchParametersWithoutSK>(patchItemFull);
expectAssignable<PatchParameters>({});
expectAssignable<PatchParametersWithoutSK>({});
// Invalid Set
expectError<PatchParameters>({attr1: "ff"});
expectError<PatchParametersWithoutSK>({attr1: "ff"});
expectError<PatchParameters>({attr6: "1234"});
expectError<PatchParametersWithoutSK>({attr6: "1234"});
// Finishers
type PatchParametersFinishers = "set" | "delete" | "remove" | "go" | "params" | "where" | "add" | "subtract" | "append" | "data";
let patchItem = entityWithSK.patch({attr1: "abc", attr2: "def"}).set({});
let patchItemWithoutSK = entityWithoutSK.patch({attr1: "abc"}).set({});
let patchFinishers = getKeys(patchItem);
let patchFinishersWithoutSK = getKeys(patchItemWithoutSK);
expectAssignable<PatchParametersFinishers>(patchFinishers);
expectAssignable<PatchParametersFinishers>(patchFinishersWithoutSK);
let patchGo = patchItem.go;
let patchGoWithoutSK = patchItemWithoutSK.go;
let patchParams = patchItem.params;
let patchParamsWithoutSK = patchItemWithoutSK.params;
type PatchGoParams = Parameter<typeof patchGo>;
type PatchGoParamsWithoutSK = Parameter<typeof patchGoWithoutSK>;
type PatchParamsParams = Parameter<typeof patchParams>;
type PatchParamsParamsWithoutSK = Parameter<typeof patchParamsWithoutSK>;
expectAssignable<PatchGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "updated_new"});
expectAssignable<PatchGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc", response: "updated_new"});
expectAssignable<PatchParamsParams>({params: {}, table: "abc", response: "updated_new"});
expectAssignable<PatchParamsParamsWithoutSK>({params: {}, table: "abc", response: "updated_new"});
// Where
patchItem.where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
patchItemWithoutSK.where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
// Find
// Query
let findFn = entityWithSK.find;
let findFnWithoutSK = entityWithoutSK.find;
type FindParameters = Parameter<typeof findFn>;
type FindParametersWithoutSK = Parameter<typeof findFnWithoutSK>;
expectAssignable<keyof FindParameters>(AttributeName);
expectAssignable<keyof FindParametersWithoutSK>(AttributeName);
expectAssignable<FindParameters>({attr6: 13});
expectAssignable<FindParametersWithoutSK>({attr6: 13});
// Invalid query
expectError<FindParameters>({attr6: "ff"});
expectError<FindParametersWithoutSK>({attr6: "ff"});
expectError<FindParameters>({noexist: "ff"});
expectError<FindParametersWithoutSK>({noexist: "ff"});
// Where
findFn({}).where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
findFnWithoutSK({}).where((attr, op) => {
let opKeys = getKeys(op);
expectAssignable<keyof typeof attr>(AttributeName);
expectAssignable<OperationNames>(opKeys);
return "";
});
// Finishers
type FindParametersFinishers = "go" | "params" | "where" | "page";
let findFinishers = entityWithSK.find({});
let findFinishersWithoutSK = entityWithoutSK.find({});
let matchFinishers = entityWithSK.match({});
let matchFinishersWithoutSK = entityWithoutSK.match({});
let findFinisherKeys = getKeys(findFinishers);
let findFinisherKeysWithoutSK = getKeys(findFinishersWithoutSK);
let matchFinisherKeys = getKeys(matchFinishers);
let matchFinisherKeysWithoutSK = getKeys(matchFinishersWithoutSK);
expectAssignable<FindParametersFinishers>(findFinisherKeys);
expectAssignable<FindParametersFinishers>(findFinisherKeysWithoutSK);
expectAssignable<FindParametersFinishers>(matchFinisherKeys);
expectAssignable<FindParametersFinishers>(matchFinisherKeysWithoutSK);
let findGo = findFinishers.go;
let findGoWithoutSK = findFinishersWithoutSK.go;
let matchGo = matchFinishers.go;
let matchGoWithoutSK = matchFinishersWithoutSK.go;
let findParams = findFinishers.params;
let findParamsWithoutSK = findFinishersWithoutSK.params;
let matchParams = matchFinishers.params;
let matchParamsWithoutSK = matchFinishersWithoutSK.params;
type FindGoParams = Parameter<typeof findGo>;
type FindGoParamsWithoutSK = Parameter<typeof findGoWithoutSK>;
type MatchGoParams = Parameter<typeof matchGo>;
type MatchGoParamsWithoutSK = Parameter<typeof matchGoWithoutSK>;
type FindParamsParams = Parameter<typeof findParams>;
type FindParamsParamsWithoutSK = Parameter<typeof findParamsWithoutSK>;
type MatchParamsParams = Parameter<typeof matchParams>;
type MatchParamsParamsWithoutSK = Parameter<typeof matchParamsWithoutSK>;
expectAssignable<FindGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<FindGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<MatchGoParams>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<MatchGoParamsWithoutSK>({includeKeys: true, originalErr: true, params: {}, raw: true, table: "abc"});
expectAssignable<FindParamsParams>({params: {}, table: "abc"});
expectAssignable<FindParamsParamsWithoutSK>({params: {}, table: "abc"});
expectAssignable<MatchParamsParams>({params: {}, table: "abc"});
expectAssignable<MatchParamsParamsWithoutSK>({params: {}, table: "abc"});
// Page
let findPageFn = findFinishers.page;
let findPageFnWithoutSK = findFinishersWithoutSK.page;
let matchPageFn = matchFinishers.page;
let matchPageFnWithoutSK = matchFinishersWithoutSK.page;
let queryPageFn = entityWithSK.query.myIndex2({attr6: 123, attr9: 456}).page;
let queryPageFnWithoutSk = entityWithoutSK.query.myIndex2(({attr6: 123, attr9: 456})).page;
type FindPageParams = Parameters<typeof findPageFn>;
type FindPageParamsWithoutSK = Parameters<typeof findPageFnWithoutSK>;
type MatchPageParams = Parameters<typeof matchPageFn>;
type MatchPageParamsWithoutSK = Parameters<typeof matchPageFnWithoutSK>;
type QueryPageParams = Parameters<typeof queryPageFn>;
type QueryPageParamsWithoutSK = Parameters<typeof queryPageFnWithoutSk>;
type FindPageReturn = Promise<[WithSKMyIndexCompositeAttributes | null, Item[]]>;
type FindPageReturnWithoutSK = Promise<[WithoutSKMyIndexCompositeAttributes | null, ItemWithoutSK[]]>;
type MatchPageReturn = Promise<[WithSKMyIndexCompositeAttributes | null, Item[]]>;
type MatchPageReturnWithoutSK = Promise<[WithoutSKMyIndexCompositeAttributes | null, ItemWithoutSK[]]>;
type QueryPageReturn = Promise<[WithSKMyIndexCompositeAttributes | null, Item[]]>;
type QueryPageReturnWithoutSK = Promise<[WithoutSKMyIndexCompositeAttributes | null, ItemWithoutSK[]]>;
expectAssignable<FindPageParams>([{attr1: "abc", attr2: "def"}, {includeKeys: true, pager: "item", originalErr: true, params: {}, raw: true, table: "abc"}]);
expectAssignable<FindPageParamsWithoutSK>([{attr1: "abc"}, {includeKeys: true, pager: "raw", originalErr: true, params: {}, raw: true, table: "abc"}]);
expectAssignable<MatchPageParams>([{attr1: "abc", attr2: "def"}, {includeKeys: true, pager: "item", originalErr: true, params: {}, raw: true, table: "abc"}]);
expectAssignable<MatchPageParamsWithoutSK>([{attr1: "abc"}, {includeKeys: true, pager: "raw", originalErr: true, params: {}, raw: true, table: "abc"}]);
expectAssignable<QueryPageParams>([{attr1: "abc", attr2: "def", attr6: 123, attr9: 456, attr5: "xyz", attr4: "abc"}, {includeKeys: true, pager: "item", originalErr: true, params: {}, raw: true, table: "abc"}]);
expectAssignable<QueryPageParamsWithoutSK>([{attr1: "abc", attr6: 123, attr9: 456}, {includeKeys: true, pager: "raw", originalErr: true, params: {}, raw: true, table: "abc"}]);
expectAssignable<FindPageParams>([null]);
expectAssignable<FindPageParamsWithoutSK>([null]);
expectAssignable<MatchPageParams>([null]);
expectAssignable<MatchPageParamsWithoutSK>([null]);
expectAssignable<QueryPageParams>([null]);
expectAssignable<QueryPageParamsWithoutSK>([null]);
expectAssignable<FindPageParams>([]);
expectAssignable<FindPageParamsWithoutSK>([]);
expectAssignable<MatchPageParams>([]);
expectAssignable<MatchPageParamsWithoutSK>([]);
expectAssignable<QueryPageParams>([]);
expectAssignable<QueryPageParamsWithoutSK>([]);
expectAssignable<FindPageReturn>(findPageFn());
expectAssignable<FindPageReturnWithoutSK>(findPageFnWithoutSK());
expectAssignable<MatchPageReturn>(matchPageFn());
expectAssignable<MatchPageReturnWithoutSK>(matchPageFnWithoutSK());
expectAssignable<QueryPageReturn>(queryPageFn());
expectAssignable<QueryPageReturnWithoutSK>(queryPageFnWithoutSk());
// Queries
type AccessPatternNames = "myIndex" | "myIndex2" | "myIndex3";
let accessPatternNames = getKeys(entityWithSK.query);
let accessPatternNamesWithoutSK = getKeys(entityWithoutSK.query);
expectType<AccessPatternNames>(accessPatternNames);
expectType<AccessPatternNames>(accessPatternNamesWithoutSK);
type MyIndexCompositeAttributes = Parameter<typeof entityWithSK.query.myIndex>;
type MyIndexCompositeAttributesWithoutSK = Parameter<typeof entityWithoutSK.query.myIndex>;
let myIndexBegins = entityWithSK.query.myIndex({attr1: "abc"}).begins;
// Begins does not exist on Find because the user has tossed out knowledge of order/indexes
expectError(entityWithoutSK.query.myIndex({attr1: "abc"}).begins);
type MyIndexRemaining = Parameter<typeof myIndexBegins>;
expectAssignable<MyIndexCompositeAttributes>({attr1: "abd"});
expectAssignable<MyIndexCompositeAttributesWithoutSK>({attr1: "abd"});
expectAssignable<MyIndexCompositeAttributes>({attr1: "abd", attr2: "def"});
expectAssignable<MyIndexCompositeAttributesWithoutSK>({attr1: "abd"});
expectAssignable<MyIndexRemaining>({});
expectAssignable<MyIndexRemaining>({attr2: "abc"});
// attr1 not supplied
expectError<MyIndexCompositeAttributes>({attr2: "abc"});
expectError<MyIndexCompositeAttributesWithoutSK>({attr2: "abc"});
// attr2 is a strin, not number
expectError<MyIndexCompositeAttributes>({attr1: "abd", attr2: 133});
expectError<MyIndexCompositeAttributesWithoutSK>({attr1: 243});
// attr3 is not a pk or sk
expectError<MyIndexCompositeAttributes>({attr1: "abd", attr2: "def", attr3: "should_not_work"});
expectError<MyIndexCompositeAttributesWithoutSK>({attr1: "abd", attr2: "def", attr3: "should_not_work"});
// attr1 was already used in the query method
expectError<MyIndexRemaining>({attr1: "abd"});
// attr2 is a string not number (this tests the 'remaining' composite attributes which should also enforce type)
expectError<MyIndexRemaining>({attr2: 1243});
// require at least PK
expectError(entityWithSK.query.myIndex({}));
expectError(entityWithoutSK.query.myIndex({}));
// attr6 should be number
expectError(entityWithSK.query.myIndex2({attr6: "45"}));
expectError(entityWithoutSK.query.myIndex2({attr6: "45"}));
entityWithSK.query
.myIndex({attr1: "abc", attr2: "def"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex({attr1: "abc"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex2({attr6: 45, attr9: 454, attr4: "abc", attr5: "def"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex2({attr6: 45, attr9: 24})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex3({attr5: "dgdagad"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithoutSK.query
.myIndex({attr1: "abc"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithoutSK.query
.myIndex2({attr6: 53, attr9: 35})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithoutSK.query
.myIndex3({attr5: "dgdagad"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
// Query Operations
entityWithSK.query
.myIndex({attr1: "abc"})
.begins({attr2: "asf"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex2({attr6: 45, attr9: 34, attr4: "abc"})
.begins({attr5: "db"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex3({attr5: "dgdagad"})
.between({attr4: "abc", attr9: 3, attr3: "def"}, {attr4: "abc", attr9: 4, attr3: "def"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex({attr1: "abc"})
.gte({attr2: "asf"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex2({attr6: 45, attr9: 33, attr4: "abc"})
.gt({attr5: "abd"})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex3({attr5: "dgdagad"})
.lte({attr4: "abc", attr9: 3})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex3({attr5: "dgdagad"})
.lt({attr4: "abc", attr9: 3})
.go({params: {}})
.then(a => a.map(val => val.attr4))
entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${name(attr6)} = ${value(attr6, 12)}
AND ${exists(attr6)}
AND ${notExists(attr6)}
AND ${begins(attr6, 35)}
AND ${between(attr6, 1, 10)}
AND ${contains(attr6, 14)}
AND ${eq(attr6, 14)}
AND ${gt(attr6, 14)}
AND ${gte(attr6, 14)}
AND ${lt(attr6, 14)}
AND ${lte(attr6, 14)}
AND ${notContains(attr6, 14)}
`)
// Query Operations (Except with Type Errors)
// This one ensures that an SK value in the index method still is type checked
expectError(entityWithSK.query
.myIndex({attr1: "452", attr2: 245})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex2({attr6: "45"})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex3({attr5: 426})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithoutSK.query
.myIndex({attr1: 246})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithoutSK.query
.myIndex2({attr6: 24, attr9: "1"})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithoutSK.query
.myIndex3({attr5: 346})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
// Query Operations
expectError(entityWithSK.query
.myIndex({attr1: "abc"})
.begins({attr2: 42})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex2({attr6: 45, attr4: "abc"})
.begins({attr5: 462})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex3({attr5: "dgdagad"})
.between({attr4: "abc", attr9: "3", attr3: "def"}, {attr4: "abc", attr9: "4", attr3: "def"})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex({attr1: "abc"})
.gte({attr2: 462})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex2({attr6: 45, attr4: "abc"})
.gt({attr5: 246})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex3({attr5: "dgdagad"})
.lte({attr4: "abc", attr9: "3"})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex3({attr5: "dgdagad"})
.lt({attr4: "abc", attr9: "3"})
.go({params: {}})
.then(a => a.map(val => val.attr4)))
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${name(attr6)} = ${value()}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${exists()}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${notExists()}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${begins(attr6, "35")}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${between(attr6, "1", 10)}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${between(attr6, 1, "10")}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${contains(attr6, "14")}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${eq(attr6, "14")}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${gt(attr6, "14")}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${gte(attr6, "14")}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${lt(attr6, "14")}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${lte(attr6, "14")}
`));
expectError(entityWithSK.query
.myIndex({attr1: "abc", attr2: "db"})
.where(({attr6}, {value, name, exists, begins, between, contains, eq, gt, gte, lt, lte, notContains, notExists}) => `
${notContains(attr6, "14")}
`));
// Invalid cases
expectError(() => new Service({abc: "123"}));
// Service with no Entities
let nullCaseService = new Service({});
type nullCollections = typeof nullCaseService.collections;
type nullEntities = typeof nullCaseService.collections;
expectType<nullCollections>({});
expectType<nullEntities>({});
// Service with no Collections
let serviceNoCollections = new Service({standAloneEntity});
type noEntityCollections = typeof serviceNoCollections.collections;
expectType<noEntityCollections>({});
// Service no shared entity collections
let serviceNoShared = new Service({
entityWithoutSK,
standAloneEntity,
normalEntity1,
});
let expectNoSharedCollections = "" as "normalcollection" | "mycollection" | "mycollection1"
type NoSharedCollectionsList = keyof typeof serviceNoShared.collections;
expectType<NoSharedCollectionsList>(expectNoSharedCollections);
type NoSharedCollectionParameter1 = Parameter<typeof serviceNoShared.collections.mycollection>;
expectType<NoSharedCollectionParameter1>({attr5: "string"});
expectError<NoSharedCollectionParameter1>({});
expectError<NoSharedCollectionParameter1>({attr5: 123});
expectError<NoSharedCollectionParameter1>({attr1: "123"});
type NoSharedCollectionParameter2 = Parameter<typeof serviceNoShared.collections.normalcollection>;
expectType<NoSharedCollectionParameter2>({prop2: "abc", prop1: "def"});
expectError<NoSharedCollectionParameter2>({});
expectError<NoSharedCollectionParameter2>({prop2: "abc"});
expectError<NoSharedCollectionParameter2>({prop1: "abc"});
expectError<NoSharedCollectionParameter2>({prop1: 35});
expectError<NoSharedCollectionParameter2>({prop2: 35});
expectError<NoSharedCollectionParameter2>({prop3: "35"});
// Service with complex collections
let complexService = new Service({
entityWithoutSK,
entityWithSK,
standAloneEntity,
normalEntity1,
normalEntity2
});
let expectSharedCollections = "" as "normalcollection" | "mycollection" | "mycollection1" | "mycollection2"
type SharedCollectionsList = keyof typeof complexService.collections;
expectType<SharedCollectionsList>(expectSharedCollections);
type SharedCollectionParameter1 = Parameter<typeof complexService.collections.mycollection>;
// success
complexService.collections.mycollection({attr5: "abc"});
// failure - no collection composite attributes
expectError<SharedCollectionParameter1>({});
// failure - incorrect entity composite attribute types
expectError<SharedCollectionParameter1>({attr5: 123});
// failure - incorrect entity composite attribute properties
expectError<SharedCollectionParameter1>({attr1: "123"});
type SharedCollectionParameter2 = Parameter<typeof complexService.collections.normalcollection>;
// success
complexService.collections.normalcollection({prop2: "abc", prop1: "def"});
// failure - no collection composite attributes
expectError<SharedCollectionParameter2>({});
// failure - incomplete composite attributes
expectError<SharedCollectionParameter2>({prop2: "abc"});
// failure - incomplete composite attributes
expectError<SharedCollectionParameter2>({prop1: "abc"});
// failure - incorrect entity composite attribute types
expectError<SharedCollectionParameter2>({prop1: 35});
// failure - incorrect entity composite attribute types
expectError<SharedCollectionParameter2>({prop2: 35});
// failure - incorrect entity composite attribute properties
expectError<SharedCollectionParameter2>({prop3: "35"});
let chainMethods = complexService.collections.normalcollection({prop2: "abc", prop1: "def"});
type AfterQueryChainMethods = keyof typeof chainMethods;
let expectedAfterQueryChainMethods = "" as "where" | "go" | "params" | "page"
expectType<AfterQueryChainMethods>(expectedAfterQueryChainMethods);
// .go params
type GoParams = Parameter<typeof chainMethods.go>;
expectAssignable<GoParams>({table: "df", raw: true, params: {}, originalErr: true, includeKeys: true});
complexService.collections
.normalcollection({prop2: "abc", prop1: "def"})
.go()
.then(values => {
// .go response includes only related entities
type NormalCollectionRelatedEntities = keyof typeof values;
let expectedEntities = "" as "normalEntity1" | "normalEntity2";
expectType<NormalCollectionRelatedEntities>(expectedEntities);
values.normalEntity1.map(item => {
expectError(item.attr1);
expectError(item.attr2);
expectError(item.attr3);
expectError(item.attr4);
expectError(item.attr5);
expectError(item.attr6);
expectError(item.attr7);
expectError(item.attr8);
expectError(item.attr9);
expectError(item.attr10);
expectType<string>(item.prop1);
expectType<string>(item.prop2);
expectType<string>(item.prop3);
expectType<number>(item.prop4);
expectType<boolean|undefined>(item.prop10);
let itemKeys = "" as "prop1" | "prop2" | "prop3" | "prop4" | "prop10";
expectType<keyof typeof item>(itemKeys);
});
values.normalEntity2.map(item => {
expectType<string>(item.prop1);
expectType<string>(item.prop2);
expectType<string>(item.prop3);
expectType<number>(item.prop5);
expectType<number|undefined>(item.attr9);
expectType<number|undefined>(item.attr6);
expectNotAssignable<{attr1: any}>(item);
expectNotAssignable<{attr2: any}>(item);
expectNotAssignable<{attr3: any}>(item);
expectNotAssignable<{attr4: any}>(item);
expectNotAssignable<{attr5: any}>(item);
expectNotAssignable<{attr6: any}>(item);
expectNotAssignable<{attr7: any}>(item);
expectNotAssignable<{attr8: any}>(item);
expectNotAssignable<{attr9: any}>(item);
expectNotAssignable<{attr10: any}>(item);
expectNotAssignable<{prop10: any}>(item);
let itemKeys = "" as "prop1" | "prop2" | "prop3" | "prop5" | "attr9" | "attr6";
expectType<keyof typeof item>(itemKeys);
});
});
complexService.collections
.mycollection({attr5: "sgad"})
.go()
.then(values => {
// .go response includes only related entities
type NormalCollectionRelatedEntities = keyof typeof values;
let expectedEntities = "" as "entityWithSK" | "entityWithoutSK";
expectType<NormalCollectionRelatedEntities>(expectedEntities);
values.entityWithSK.map(item => {
expectType<string>(item.attr1);
expectType<string>(item.attr2);
expectType<"123" | "def" | "ghi"|undefined>(item.attr3);
expectType<"abc" | "ghi">(item.attr4);
expectType<string|undefined>(item.attr5);
expectType<number|undefined>(item.attr6);
expectType<any>(item.attr7);
expectType<boolean>(item.attr8);
expectType<number|undefined>(item.attr9);
expectType<boolean|undefined>(item.attr10);
// .go response related entities correct items
let itemKeys = "" as "attr1" |"attr2" |"attr3" |"attr4" |"attr5" |"attr6" |"attr7" |"attr8" |"attr9" | "attr10";
expectType<keyof typeof item>(itemKeys);
});
values.entityWithoutSK.map(item => {
item.attr2
expectType<string>(item.attr1);
expectType<string | undefined>(item.attr2);
expectType<"123" | "def" | "ghi" | undefined>(item.attr3);
expectType<"abc" | "def">(item.attr4);
expectType<string|undefined>(item.attr5);
expectType<number|undefined>(item.attr6);
expectType<any>(item.attr7);
expectType<boolean>(item.attr8);
expectType<number|undefined>(item.attr9);
// .go response related entities correct items
let itemKeys = "" as "attr1" |"attr2" |"attr3" |"attr4" |"attr5" |"attr6" |"attr7" |"attr8" |"attr9";
expectType<keyof typeof item>(itemKeys);
});
});
let serviceWhere = complexService.collections
.mycollection1({attr6: 13, attr9: 54})
.where((attr, op) => {
let opKeys = getKeys(op);
expectType<OperationNames>(opKeys);
op.eq(attr.attr9, 455);
op.eq(attr.prop5, 455);
expectAssignable<{attr1: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{attr2: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{attr3: WhereAttributeSymbol<"123" | "def" | "ghi">}>(attr);
expectAssignable<{attr4: WhereAttributeSymbol<"abc" | "def" | "ghi">}>(attr);
expectAssignable<{attr5: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{attr6: WhereAttributeSymbol<number>}>(attr);
expectAssignable<{attr7: WhereAttributeSymbol<any>}>(attr);
expectAssignable<{attr8: WhereAttributeSymbol<boolean>}>(attr);
expectAssignable<{attr9: WhereAttributeSymbol<number>}>(attr);
expectAssignable<{attr10: WhereAttributeSymbol<boolean>}>(attr);
expectAssignable<{prop1: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{prop2: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{prop3: WhereAttributeSymbol<string>}>(attr);
expectNotAssignable<{prop4: WhereAttributeSymbol<number>}>(attr);
expectAssignable<{prop5: WhereAttributeSymbol<number>}>(attr);
expectNotAssignable<{prop10: WhereAttributeSymbol<boolean>}>(attr);
return "";
})
.go()
.then((items) => {
items.normalEntity2.map(item => {
let keys = "" as keyof typeof item;
expectType<"prop1" | "prop2" | "prop3" | "prop5" | "attr6" | "attr9">(keys);
expectType<string>(item.prop1);
expectType<string>(item.prop2);
expectType<string>(item.prop3);
expectType<number>(item.prop5);
expectType<number|undefined>(item.attr6);
expectType<number|undefined>(item.attr9);
});
items.entityWithSK.map((item) => {
let keys = "" as keyof typeof item;
expectType<"attr1" | "attr2" | "attr3" | "attr4" | "attr5" | "attr6" | "attr7" | "attr8" | "attr9" | "attr10">(keys);
expectType<string>(item.attr1);
expectType<string>(item.attr2);
expectType<"123" | "def" | "ghi" | undefined>(item.attr3);
expectType<"abc" | "ghi">(item.attr4);
expectType<string | undefined>(item.attr5);
expectType<number | undefined>(item.attr6);
expectType<any>(item.attr7);
expectType<boolean>(item.attr8);
expectType<number | undefined>(item.attr9);
expectType<boolean | undefined>(item.attr10);
});
items.entityWithoutSK.map((item) => {
let keys = "" as keyof typeof item;
expectType<"attr1" | "attr2" | "attr3" | "attr4" | "attr5" | "attr6" | "attr7" | "attr8" | "attr9">(keys);
expectType<string>(item.attr1);
expectType<string | undefined>(item.attr2);
expectType<"123" | "def" | "ghi" | undefined>(item.attr3);
expectType<"abc" | "def">(item.attr4);
expectType<string | undefined>(item.attr5);
expectType<number | undefined>(item.attr6);
expectType<any>(item.attr7);
expectType<boolean>(item.attr8);
expectType<number | undefined>(item.attr9);
});
});
complexService.collections.normalcollection({prop1: "abc", prop2: "def"})
.where((attr, op) => {
let opKeys = getKeys(op);
expectType<OperationNames>(opKeys);
expectNotAssignable<{attr1: WhereAttributeSymbol<string>}>(attr);
expectNotAssignable<{attr2: WhereAttributeSymbol<string>}>(attr);
expectNotAssignable<{attr3: WhereAttributeSymbol<"123" | "def" | "ghi">}>(attr);
expectNotAssignable<{attr4: WhereAttributeSymbol<"abc" | "def" | "ghi">}>(attr);
expectNotAssignable<{attr5: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{attr6: WhereAttributeSymbol<number>}>(attr);
expectNotAssignable<{attr7: WhereAttributeSymbol<any>}>(attr);
expectNotAssignable<{attr8: WhereAttributeSymbol<boolean>}>(attr);
expectAssignable<{attr9: WhereAttributeSymbol<number>}>(attr);
expectNotAssignable<{attr10: WhereAttributeSymbol<boolean>}>(attr);
expectAssignable<{prop1: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{prop2: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{prop3: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{prop4: WhereAttributeSymbol<number>}>(attr);
expectAssignable<{prop5: WhereAttributeSymbol<number>}>(attr);
expectAssignable<{prop10: WhereAttributeSymbol<boolean>}>(attr);;
return op.eq(attr.prop1, "db");
})
.go()
.then((items) => {
items.normalEntity1.map(item => {
let keys = "" as keyof typeof item;
expectType<"prop1" | "prop2" | "prop3" | "prop4" | "prop10">(keys);
expectType<string>(item.prop1);
expectType<string>(item.prop2);
expectType<string>(item.prop3);
expectType<number>(item.prop4);
expectType<boolean | undefined>(item.prop10);
});
items.normalEntity2.map(item => {
let keys = "" as keyof typeof item;
expectType<"prop1" | "prop2" | "prop3" | "prop5" | "attr6" | "attr9">(keys);
expectType<string>(item.prop1);
expectType<string>(item.prop2);
expectType<string>(item.prop3);
expectType<number>(item.prop5);
expectType<number|undefined>(item.attr6);
expectType<number|undefined>(item.attr9);
});
});
complexService.collections.mycollection2({attr1: "abc"})
.where((attr, op) => {
let opKeys = getKeys(op);
expectType<OperationNames>(opKeys);
expectAssignable<{attr1: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{attr2: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{attr3: WhereAttributeSymbol<"123" | "def" | "ghi">}>(attr);
expectAssignable<{attr4: WhereAttributeSymbol<"abc" | "def" | "ghi">}>(attr);
expectAssignable<{attr5: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{attr6: WhereAttributeSymbol<number>}>(attr);
expectAssignable<{attr7: WhereAttributeSymbol<any>}>(attr);
expectAssignable<{attr8: WhereAttributeSymbol<boolean>}>(attr);
expectAssignable<{attr9: WhereAttributeSymbol<number>}>(attr);
expectAssignable<{attr10: WhereAttributeSymbol<boolean>}>(attr);
expectNotAssignable<{prop1: WhereAttributeSymbol<string>}>(attr);
expectNotAssignable<{prop2: WhereAttributeSymbol<string>}>(attr);
expectNotAssignable<{prop3: WhereAttributeSymbol<string>}>(attr);
expectNotAssignable<{prop4: WhereAttributeSymbol<number>}>(attr);
expectNotAssignable<{prop5: WhereAttributeSymbol<number>}>(attr);
expectNotAssignable<{prop10: WhereAttributeSymbol<boolean>}>(attr);
return op.eq(attr.attr9, 768);
})
.go()
.then(results => {
results.entityWithSK.map((item) => {
let keys = "" as keyof typeof item;
expectType<"attr1" | "attr2" | "attr3" | "attr4" | "attr5" | "attr6" | "attr7" | "attr8" | "attr9" | "attr10">(keys);
expectType<string>(item.attr1);
expectType<string>(item.attr2);
expectType<"123" | "def" | "ghi" | undefined>(item.attr3);
expectType<"abc" | "ghi">(item.attr4);
expectType<string | undefined>(item.attr5);
expectType<number | undefined>(item.attr6);
expectType<any>(item.attr7);
expectType<boolean>(item.attr8);
expectType<number | undefined>(item.attr9);
expectType<boolean | undefined>(item.attr10);
});
});
let entityWithHiddenAttributes1 = new Entity({
model: {
entity: "e1",
service: "s1",
version: "1"
},
attributes: {
prop1: {
type: "string"
},
prop2: {
type: "string"
},
prop3: {
type: "string",
hidden: true
}
},
indexes: {
record: {
collection: "collection1",
pk: {
field: "pk",
composite: ["prop1"]
},
sk: {
field: "sk",
composite: ["prop2"]
}
}
}
});
let entityWithHiddenAttributes2 = new Entity({
model: {
entity: "e2",
service: "s1",
version: "1"
},
attributes: {
prop1: {
type: "string"
},
prop2: {
type: "string"
},
prop4: {
type: "string",
hidden: true
},
prop5: {
type: "string",
}
},
indexes: {
record: {
collection: "collection1",
pk: {
field: "pk",
composite: ["prop1"]
},
sk: {
field: "sk",
composite: ["prop2"]
}
}
}
});
const serviceWithHiddenAttributes = new Service({
e1: entityWithHiddenAttributes1,
e2: entityWithHiddenAttributes2
});
type Entity1WithHiddenAttribute = {
prop1: string;
prop2: string;
};
let entity1WithHiddenAttributeKey = "" as keyof Entity1WithHiddenAttribute;
type Entity2WithHiddenAttribute = {
prop1: string;
prop2: string;
prop5: string | undefined;
};
let entity2WithHiddenAttributeKey = "" as keyof Entity2WithHiddenAttribute;
entityWithHiddenAttributes1
.get({prop1: "abc", prop2: "def"})
.where((attr, op) => {
expectAssignable<{prop3: WhereAttributeSymbol<string>}>(attr);
return op.eq(attr.prop3, "abc");
})
.go()
.then(value => {
if (value !== null) {
expectType<keyof typeof value>(entity1WithHiddenAttributeKey);
expectType<Entity1WithHiddenAttribute>(value);
}
});
entityWithHiddenAttributes1
.query.record({prop1: "abc"})
.where((attr, op) => {
expectAssignable<{prop3: WhereAttributeSymbol<string>}>(attr);
return op.eq(attr.prop3, "abc");
})
.go()
.then(values => {
return values.map(value => {
expectType<keyof typeof value>(entity1WithHiddenAttributeKey);
expectType<Entity1WithHiddenAttribute>(value);
});
});
serviceWithHiddenAttributes.collections
.collection1({prop1: "abc"})
.where((attr, op) => {
expectAssignable<{prop3: WhereAttributeSymbol<string>}>(attr);
expectAssignable<{prop4: WhereAttributeSymbol<string>}>(attr);
return `${op.eq(attr.prop3, "abc")} AND ${op.eq(attr.prop4, "def")}`
})
.go()
.then(results => {
results.e1.map(value => {
expectType<keyof typeof value>(entity1WithHiddenAttributeKey);
expectType<Entity1WithHiddenAttribute>(value);
});
results.e2.map(value => {
expectType<keyof typeof value>(entity2WithHiddenAttributeKey);
expectType<string>(value.prop1);
expectType<string>(value.prop2);
expectType<string | undefined>(value.prop5);
});
})
let entityWithRequiredAttribute = new Entity({
model: {
entity: "e1",
service: "s1",
version: "1"
},
attributes: {
prop1: {
type: "string"
},
prop2: {
type: "string"
},
prop3: {
type: "string",
required: true
},
prop4: {
type: "number",
required: true,
},
prop5: {
type: "any",
required: true
},
prop6: {
type: "map",
properties: {
nested1: {
type: "string",
required: true
}
},
required: true,
},
prop7: {
type: "list",
items: {
type: "string",
required: true
},
required: true,
},
prop8: {
type: "string",
required: true,
default: "abc"
},
prop9: {
type: "map",
properties: {
nested1: {
type: "string",
required: true,
default: () => "abc"
},
nested2: {
type: "string",
required: true,
default: "abc"
}
},
default: {},
required: true,
},
prop10: {
type: "list",
items: {
type: "string",
},
required: true,
default: []
},
},
indexes: {
record: {
collection: "collection1",
pk: {
field: "pk",
composite: ["prop1"]
},
sk: {
field: "sk",
composite: ["prop2"]
}
}
}
});
// required attributes, as object and array, without required (but defaulted attributes)
entityWithRequiredAttribute.put({
prop1: "abc",
prop2: "def",
prop3: "ghi",
prop4: 123,
prop5: {anyVal: ["anyItem"]},
prop6: {
nested1: "abc"
},
prop7: []
});
// required attributes, as object and array, without required (but defaulted attributes)
entityWithRequiredAttribute.put([{
prop1: "abc",
prop2: "def",
prop3: "ghi",
prop4: 123,
prop5: {anyVal: ["anyItem"]},
prop6: {
nested1: "abc"
},
prop7: []
}]);
// required attributes, as object and array, without required (but defaulted attributes)
entityWithRequiredAttribute.create({
prop1: "abc",
prop2: "def",
prop3: "ghi",
prop4: 123,
prop5: {anyVal: ["anyItem"]},
prop6: {
nested1: "abc"
},
prop7: []
});
// create doesnt allow for bulk
expectError(() => {
entityWithRequiredAttribute.create([{
prop1: "abc",
prop2: "def",
prop3: "ghi",
prop4: 123,
prop5: {anyVal: ["anyItem"]},
prop6: {
nested1: "abc"
},
prop7: []
}]);
});
// missing `nested1` on `prop6`
expectError(() => {
entityWithRequiredAttribute.put({
prop1: "abc",
prop2: "def",
prop3: "ghi",
prop4: 123,
prop5: {anyVal: ["anyItem"]},
prop6: {},
prop7: []
});
})
// missing `nested1` on `prop6`
expectError(() => {
entityWithRequiredAttribute.put([{
prop1: "abc",
prop2: "def",
prop3: "ghi",
prop4: 123,
prop5: {anyVal: ["anyItem"]},
prop6: {},
prop7: []
}]);
})
// missing `nested1` on `prop6`
expectError(() => {
entityWithRequiredAttribute.create({
prop1: "abc",
prop2: "def",
prop3: "ghi",
prop4: 123,
prop5: {anyVal: ["anyItem"]},
prop6: {},
prop7: []
});
});
// no removing required attributes
expectError(() => {
entityWithRequiredAttribute
.update({prop1: "abc", prop2: "def"})
.remove(['prop3'])
});
// no removing required attributes
expectError(() => {
entityWithRequiredAttribute
.update({prop1: "abc", prop2: "def"})
.remove(['prop5'])
});
// no removing required attributes
expectError(() => {
entityWithRequiredAttribute
.update({prop1: "abc", prop2: "def"})
.remove(['prop6'])
});
// no removing required attributes
expectError(() => {
entityWithRequiredAttribute
.update({prop1: "abc", prop2: "def"})
.remove(['prop7'])
});
let entityWithReadOnlyAttribute = new Entity({
model: {
entity: "e1",
service: "s1",
version: "1"
},
attributes: {
prop1: {
type: "string"
},
prop2: {
type: "string"
},
prop3: {
type: "string",
readOnly: true
},
prop4: {
type: "string"
},
prop5: {
type: "number"
},
prop6: {
type: "any"
},
prop7: {
type: "string"
},
prop8: {
type: ["abc", "def"] as const
},
prop9: {
type: "number",
readOnly: true,
},
prop10: {
type: "any",
readOnly: true
}
},
indexes: {
record: {
collection: "collection1",
pk: {
field: "pk",
composite: ["prop1"]
},
sk: {
field: "sk",
composite: ["prop2"]
}
}
}
});
entityWithReadOnlyAttribute.put({prop1: "abc", prop2: "def", prop3: "ghi"}).params();
entityWithReadOnlyAttribute.create({prop1: "abc", prop2: "def", prop3: "ghi"}).params();
// readonly
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.set({prop3: "abc"})
.params();
});
// readonly
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.add({prop9: 13})
.params();
});
// readonly
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.subtract({prop9: 13})
.params();
});
// readonly
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.delete({prop10: "13"})
.params();
});
// readonly
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.append({prop10: ["abc"]})
.params();
});
// bad type - not number
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.add({prop7: 13})
.params();
});
// bad type - not number
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.subtract({prop7: 13})
.params();
});
// bad type - not string
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
// prop7 is string not number
.data(({prop7}, {set}) => set(prop7, 5))
.params();
});
// bad type - incorrect enum
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
// prop8 is enum with values ["abc", "def"]
.data(({prop8}, {set}) => set(prop8, "ghi"))
.params();
});
// bad type - not number
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.data(({prop7}, {subtract}) => subtract(prop7, 5))
.params();
});
// bad type - not number
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.data(({prop7}, {add}) => add(prop7, 5))
.params();
});
// bad type - not any
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.data(({prop7}, {del}) => del(prop7, 5))
.params();
});
// bad type - not any
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.data(({prop7}, op) => op.delete(prop7, 5))
.params();
});
// bad type - not any
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.delete({prop7: "13", prop5: 24})
.params();
});
// bad type - not any
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.delete({prop5: 24})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.append({prop7: "13", prop5: 24})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.append({prop5: 24})
.params();
});
// readonly
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.remove(["prop3"])
.params();
});
// readonly
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.data(({prop3}, {remove}) => {
remove(prop3)
})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.data(({prop5}, {append}) => {
append(prop5, 25)
})
.params();
});
// patch
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.set({prop3: "abc"})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.add({prop7: 13})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.subtract({prop7: 13})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.delete({prop7: "13", prop5: 24})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.delete({prop5: 24})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.append({prop7: "13", prop5: 24})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.append({prop5: 24})
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.remove(["prop3"])
.params();
});
expectError(() => {
entityWithReadOnlyAttribute
.patch({prop1: "abc", prop2: "def"})
.remove(["prop3"])
.params();
});
let setItemValue = {} as UpdateEntityItem<typeof entityWithReadOnlyAttribute>
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.set(setItemValue)
.params();
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.remove([
"prop4"
])
.params();
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.add({
prop5: 13,
})
.params();
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.subtract({
prop5: 13,
})
.params();
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.append({
prop6: ["value"]
})
.params();
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.delete({
prop6: ["value"]
})
.params();
// full chain with duplicates
entityWithReadOnlyAttribute
.update({prop1: "abc", prop2: "def"})
.set(setItemValue)
.remove([
"prop4"
])
.add({
prop5: 13,
})
.subtract({
prop5: 13,
})
.append({
prop6: ["value"]
})
.delete({
prop6: ["value"]
})
.set(setItemValue)
.remove([
"prop4"
])
.data((attr, op) => {
op.set(attr.prop4, "abc");
op.set(attr.prop5, 134);
op.set(attr.prop6, "def")
op.set(attr.prop6, 123)
op.set(attr.prop6, true)
op.set(attr.prop6[1], true)
op.set(attr.prop6.prop1, true)
op.set(attr.prop8, "def")
op.remove(attr.prop4);
op.remove(attr.prop5);
op.remove(attr.prop6);
op.remove(attr.prop6);
op.remove(attr.prop6);
op.remove(attr.prop6[1]);
op.remove(attr.prop6.prop1);
op.remove(attr.prop8)
op.append(attr.prop6, ["abc"]);
op.append(attr.prop6, ["abc"]);
op.append(attr.prop6, ["abc"]);
op.append(attr.prop6[1], ["abc"]);
op.append(attr.prop6.prop1, ["abc"]);
op.delete(attr.prop6, ["abc"]);
op.delete(attr.prop6, ["abc"]);
op.delete(attr.prop6, ["abc"]);
op.delete(attr.prop6[1], ["abc"]);
op.delete(attr.prop6.prop1, ["abc"]);
op.del(attr.prop6, ["abc"]);
op.del(attr.prop6, ["abc"]);
op.del(attr.prop6, ["abc"]);
op.del(attr.prop6[1], ["abc"]);
op.del(attr.prop6.prop1, ["abc"]);
op.name(attr.prop4);
op.name(attr.prop5);
op.name(attr.prop6);
op.name(attr.prop6);
op.name(attr.prop6);
op.name(attr.prop6[1]);
op.name(attr.prop6.prop1);
op.name(attr.prop8);
op.value(attr.prop4, "abc");
op.value(attr.prop5, 134);
op.value(attr.prop6, "abc");
op.value(attr.prop6, "abc");
op.value(attr.prop6, "abc");
op.value(attr.prop6[1], "abc");
op.value(attr.prop6.prop1, "abc");
op.value(attr.prop8, "abc");
})
.add({
prop5: 13,
})
.subtract({
prop5: 13,
})
.append({
prop6: ["value"]
})
.delete({
prop6: ["value"]
})
.params();
type MyCollection1Pager = {
attr5?: string | undefined;
attr9?: number | undefined;
attr6?: number | undefined;
attr1?: string | undefined;
attr2?: string | undefined;
prop1?: string | undefined;
prop2?: string | undefined;
prop5?: number | undefined;
__edb_e__?: string | undefined;
__edb_v__?: string | undefined;
attr4?: "abc" | "def" | "ghi" | undefined;
}
type Collection1EntityNames = "entityWithSK" | "normalEntity2" | "entityWithoutSK";
const names = "" as Collection1EntityNames;
complexService.collections
.mycollection1({attr9: 123, attr6: 245})
.page()
.then(([next, results]) => {
expectType<string | undefined>(next?.attr1);
expectType<string | undefined>(next?.attr2);
expectType<number | undefined>(next?.attr6);
expectType<number | undefined>(next?.attr9);
expectType<"abc" | "def" | "ghi" | undefined>(next?.attr4);
expectType<string | undefined>(next?.attr5);
expectType<number | undefined>(next?.prop5);
expectType<string | undefined>(next?.prop1);
expectType<string | undefined>(next?.prop2);
expectType<string | undefined>(next?.__edb_e__);
expectType<string | undefined>(next?.__edb_v__);
expectAssignable<typeof next>({
attr1: "abc",
attr2: "abc",
attr6: 27,
attr9: 89,
attr4: "abc",
attr5: "abc",
__edb_e__: "entityWithSK",
__edb_v__: "1"
});
expectAssignable<typeof next>({
prop1: "abc",
prop2: "abc",
attr6: 27,
attr9: 89,
prop5: 12,
__edb_e__: "normalEntity2",
__edb_v__: "1"
});
expectAssignable<typeof next>({
attr1: "abc",
attr6: 27,
attr9: 89,
__edb_e__: "entityWithoutSK",
__edb_v__: "1"
});
expectType<keyof typeof results>(names);
expectNotType<any>(next);
})
complexService.collections
.mycollection1({attr9: 123, attr6: 245})
.page(null)
const nextPage = {} as MyCollection1Pager;
complexService.collections
.mycollection1({attr9: 123, attr6: 245})
.page(nextPage, {})
complexService.entities
.entityWithSK.remove({attr1: "abc", attr2: "def"})
.where((attr, op) => op.eq(attr.attr9, 14))
.go();
const entityWithMultipleCollections1 = new Entity({
model: {
entity: "entity1",
service: "myservice",
version: "myversion"
},
attributes: {
attr1: {
type: "string",
},
attr2: {
type: "string",
}
},
indexes: {
myIndex: {
collection: ["outercollection", "innercollection"] as const,
pk: {
field: "pk",
composite: ["attr1"]
},
sk: {
field: "sk",
composite: ["attr2"]
}
},
}
})
const entityWithMultipleCollections2 = new Entity({
model: {
entity: "entity2",
service: "myservice",
version: "myversion"
},
attributes: {
attr1: {
type: "string",
},
attr2: {
type: "string",
}
},
indexes: {
myIndex: {
collection: ["outercollection", "innercollection"] as const,
pk: {
field: "pk",
composite: ["attr1"]
},
sk: {
field: "sk",
composite: ["attr2"]
}
},
myIndex2: {
index: "index2",
collection: ["extracollection"] as const,
pk: {
field: "index2pk",
composite: ["attr1"]
},
sk: {
field: "index2sk",
composite: ["attr2"]
}
},
}
});
const entityWithMultipleCollections3 = new Entity({
model: {
entity: "entity3",
service: "myservice",
version: "myversion"
},
attributes: {
attr1: {
type: "string",
},
attr2: {
type: "string",
}
},
indexes: {
myIndex: {
collection: "outercollection" as const,
pk: {
field: "pk",
composite: ["attr1"]
},
sk: {
field: "sk",
composite: ["attr2"]
}
},
myIndex2: {
index: "index2",
collection: "extracollection" as const,
pk: {
field: "index2pk",
composite: ["attr1"]
},
sk: {
field: "index2sk",
composite: ["attr2"]
}
},
}
});
const serviceWithMultipleCollections = new Service({entityWithMultipleCollections3, entityWithMultipleCollections1, entityWithMultipleCollections2});
type OuterCollectionEntities = "entityWithMultipleCollections2" | "entityWithMultipleCollections3" | "entityWithMultipleCollections1";
type InnerCollectionEntities = "entityWithMultipleCollections1" | "entityWithMultipleCollections2";
type ExtraCollectionEntities = "entityWithMultipleCollections2" | "entityWithMultipleCollections3";
serviceWithMultipleCollections.collections
.outercollection({attr1: "abc"})
.go()
.then(values => {
const keys = "" as keyof typeof values;
expectType<OuterCollectionEntities>(keys);
})
serviceWithMultipleCollections.collections
.innercollection({attr1: "abc"})
.go()
.then(values => {
const keys = "" as keyof typeof values;
expectType<InnerCollectionEntities>(keys);
})
serviceWithMultipleCollections.collections
.extracollection({attr1: "abc"})
.go()
.then(values => {
const keys = "" as keyof typeof values;
expectType<ExtraCollectionEntities>(keys);
})
const entityWithWatchAll = new Entity({
model: {
entity: "withwatchall",
service: "service",
version: "1"
},
attributes: {
prop1: {
type: "string"
},
prop2: {
type: "string"
},
prop3: {
type: "string",
watch: "*",
set: (value) => {
return value;
}
},
},
indexes: {
record: {
pk: {
field: "pk",
composite: ["prop1"]
},
sk: {
field: "sk",
composite: ["prop2"]
}
}
}
});
const entityWithComplexShapes = new Entity({
model: {
entity: "entity",
service: "service",
version: "1"
},
attributes: {
prop1: {
type: "string",
label: "props"
},
prop2: {
type: "string",
},
prop3: {
type: "map",
properties: {
val1: {
type: "string"
}
}
},
prop4: {
type: "list",
items: {
type: "map",
properties: {
val2: {
type: "number",
},
val3: {
type: "list",
items: {
type: "string"
}
},
val4: {
type: "set",
items: "number"
}
}
}
},
prop5: {
type: "set",
items: "string"
},
prop6: {
type: "set",
items: "string"
}
},
indexes: {
record: {
collection: "mops",
pk: {
field: "pk",
composite: ["prop1"]
},
sk: {
field: "sk",
composite: ["prop2"]
}
}
}
});
const entityWithComplexShapesRequired = new Entity({
model: {
entity: "entity",
service: "service",
version: "1"
},
attributes: {
prop1: {
type: "string",
label: "props"
},
prop2: {
type: "string",
},
attr3: {
type: "map",
properties: {
val1: {
type: "string",
required: true
}
},
required: true
},
attr4: {
type: "list",
items: {
type: "map",
properties: {
val2: {
type: "number",
required: true
},
val3: {
type: "list",
items: {
type: "string",
required: true
},
required: true
},
val4: {
type: "set",
items: "number",
required: true
}
}
},
required: true
},
attr5: {
type: "set",
items: "string",
required: true
},
attr6: {
type: "set",
items: "string",
required: true
}
},
indexes: {
record: {
collection: "mops",
pk: {
field: "pk",
composite: ["prop1"]
},
sk: {
field: "sk",
composite: ["prop2"]
}
}
}
});
const entityWithComplexShapesRequiredOnEdge = new Entity({
model: {
entity: "entity",
service: "service",
version: "1"
},
attributes: {
prop1: {
type: "string",
label: "props"
},
prop2: {
type: "string",
},
attrz3: {
type: "map",
properties: {
val1: {
type: "string",
required: true,
validate: /./gi
}
}
},
attrz4: {
type: "list",
items: {
type: "map",
properties: {
val2: {
type: "number",
required: true,
},
val3: {
type: "list",
items: {
type: "string",
required: true
},
},
val4: {
type: "set",
items: "number",
},
val5: {
type: "map",
properties: {
val6: {
type: "string",
required: true
}
}
}
}
},
},
attrz5: {
type: "set",
items: "string",
},
attrz6: {
type: "set",
items: "string",
}
},
indexes: {
record: {
collection: "mops",
pk: {
field: "pk",
composite: ["prop1"]
},
sk: {
field: "sk",
composite: ["prop2"]
}
}
}
});
const complexShapeService = new Service({
ent1: entityWithComplexShapesRequiredOnEdge,
ent2: entityWithComplexShapes,
ent3: entityWithComplexShapesRequired
});
const parsed = entityWithComplexShapes.parse({});
entityWithComplexShapes.query
.record({prop1: "abc"})
.go()
.then((data) => {
expectType<typeof data>(
entityWithComplexShapes.parse({
Items: []
})
)
})
entityWithComplexShapes.get({prop1: "abc", prop2: "def"}).go().then(data => {
expectType<typeof parsed>(data);
if (data === null) {
return null;
}
data.prop3?.val1;
let int = 0;
if (Array.isArray(data.prop4)) {
for (let value of data.prop4) {
if (typeof value === "string") {
if (isNaN(parseInt(value))) {
int += 0;
} else {
int += parseInt(value);
}
} else if (typeof value === "number") {
int += value;
} else if (Array.isArray(value)) {
for (let val of value) {
int += val.val2
}
} else {
expectType<number|undefined>(value.val2);
int += value?.val2 ?? 0;
}
}
}
return data.prop3?.val1
});
entityWithComplexShapes
.get({prop1: "abc", prop2: "def"})
.go()
.then(data => {
if (data !== null) {
data.prop5?.map(values => values);
data.prop6?.map(values => values);
}
})
entityWithComplexShapes
.update({prop1: "abc", prop2: "def"})
.set({
prop4: [{
val2: 789,
val3: ["123"],
val4: [123, 456]
}],
prop5: ["abc"]
})
.go()
entityWithComplexShapes
.put({
prop1: "abc",
prop2: "def",
prop4: [{
val2: 789,
val3: ["123"],
val4: [123, 456]
}],
prop5: ["abc"]
})
.go()
entityWithComplexShapes
.update({prop1: "abc", prop2: "def"})
.set({
prop4: [{
val2: 789,
val3: ["123"],
// val4: [1, 2, 3]
}],
prop5: ["abc"]
})
.where(({prop5}, {eq}) => eq(prop5, ["abc"]))
.where(({prop1}, {eq}) => eq(prop1, "abc"))
.go();
entityWithComplexShapes
.update({prop1: "abc", prop2: "def"})
.append({
prop4: [{
val2: 789,
val3: ["123"],
val4: [1, 2, 3]
}],
})
.data(({prop5, prop4}, {add, append, remove}) => {
add(prop5, ["abc"]);
append(prop4[0].val3, ["123"]);
append(prop4, [{
val2: 789,
val3: ["123"],
val4: [1, 2, 3]
}]);
add(prop4[0].val2, 789);
add(prop4[0].val4, [1]);
remove(prop4[0].val4);
remove(prop4[0].val3);
remove(prop4[0].val2);
})
.go()
expectError(() => {
entityWithComplexShapes
.update({prop1: "abc", prop2: "def"})
.append({
prop4: [{
val2: 789,
val3: ["123"],
val4: [1, 2, 3]
}],
prop5: ["abc"]
})
.go()
});
expectError(() => {
entityWithComplexShapes
.update({prop1: "abc", prop2: "def"})
.data(({prop1}, {remove}) => {
remove(prop1);
})
.go()
});
entityWithComplexShapes
.update({prop1: "abc", prop2: "def"})
.set({
prop4: [{
val2: 789,
val3: ["123"],
val4: [1, 2, 3]
}],
prop5: ["abc"]
})
.go()
entityWithComplexShapesRequired.put({
prop1: "abc",
prop2: "def",
attr3: {
val1: "abc",
},
attr4: [{
val2: 789,
val3: ["123"],
val4: [1, 2, 3]
}],
attr5: ["abc"],
attr6: ["abdbdb"],
});
expectError(() => {
entityWithComplexShapesRequired.put({});
})
expectError(() => {
entityWithComplexShapesRequired.put({prop1: "abc", prop2: "def"});
});
complexShapeService.collections
.mops({prop1: "abc"})
.where((a, op) => {
op.eq(a.attr3.val1, "abd");
expectError(() => op.eq(a.attr3, "abc"));
expectError(() => op.eq(a.attr3.val2, "abc"));
expectError(() => op.eq(a.attr3.val1, 123));
op.between(a.attr4[0].val2, 789, 888);
expectError(() => op.eq(a.attr4, "abc"));
expectError(() => op.eq(a.attr4.val2, "abc"));
expectError(() => op.eq(a.attr4[0].val2, "456"));
op.between(a.attr4[0].val3[1], "xyz", "123");
// expectNotAssignable<"abc">(a.attr4[1].val3[1]);
// expectNotAssignable<typeof (a.attr4[1].val3)>(["abc"]);
// expectError(() => op.eq(a.attr4[1].val3["def"], "xyz"));
op.gte(a.attr5, ["abc"]);
op.eq(a.attrz3.val1, "abd");
expectError(() => op.eq(a.attrz3, "abc"))
expectError(() => op.eq(a.attrz3.val2, "abc"))
expectError(() => op.eq(a.attrz3.val1, 123));
op.between(a.attrz4[0].val2, 789, 888);
// expectNotAssignable<"abc">(a.attrz4[1].val3[1]);
// expectNotAssignable<["abc"]>(a.attrz4[1].val3);
expectError(() => op.eq(a.attrz4[0].val2, "456"));
op.between(a.attrz4[0].val3[1], "xyz", "123");
// expectError(() => op.eq(a.attr4[1].val3[1], "abc"));
// expectError(() => op.eq(a.attr4[1].val3["def"], "xyz"));
op.gte(a.attrz5, ["abc"]);
op.eq(a.prop3.val1, "abd");
expectError(() => op.eq(a.attrz3, "abc"))
expectError(() => op.eq(a.attrz3.val2, "abc"))
expectError(() => op.eq(a.attrz3.val1, 123))
op.between(a.prop4[0].val2, 789, 888);
op.between(a.prop4[0].val3[1], "xyz", "123");
op.gte(a.prop5, ["abc"])
op.eq(a.prop2, "def");
op.contains(a.prop4[1].val3[2], "123");
return "";
})
const complex = new Entity({
model: {
entity: "user",
service: "versioncontrol",
version: "1"
},
attributes: {
stringVal: {
type: "string",
default: () => "abc",
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
enumVal: {
type: ["abc", "def"] as const,
validate: (value: "abc" | "def") => value !== undefined,
default: () => "abc",
get: (value: "abc" | "def") => {
return value;
},
set: (value?: "abc" | "def") => {
return value;
}
},
numVal: {
type: "number",
validate: (value) => value !== undefined,
default: () => 123,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
boolValue: {
type: "boolean",
validate: (value) => value !== undefined,
default: () => true,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
stringSetValue: {
type: "set",
items: "string",
validate: (value) => value !== undefined,
default: () => ["abc"],
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
numberSetValue: {
type: "set",
items: "number",
validate: (value) => value !== undefined,
default: () => [1],
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
stringListValue: {
type: "list",
items: {
type: "string",
default: "abc",
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
default: ["abc"],
validate: (value: string[]) => value !== undefined,
get: (value: string[]) => {
return value;
},
set: (value?: string[]) => {
return value;
}
},
numberListValue: {
type: "list",
items: {
type: "number",
validate: (value) => value !== undefined,
default: 0,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
default: [],
validate: (value: number[]) => value !== undefined,
get: (value: number[]) => {
return value;
},
set: (value?: number[]) => {
return value;
}
},
mapListValue: {
type: "list",
items: {
type: "map",
properties: {
stringVal: {
type: "string",
default: "def",
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
numVal: {
type: "number",
default: 5,
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
boolValue: {
type: "boolean",
default: false,
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
enumVal: {
type: ["abc", "def"] as const,
validate: (value: "abc" | "def") => value !== undefined,
default: () => "abc",
get: (value: "abc" | "def") => {
return value;
},
set: (value?: "abc" | "def") => {
return value;
}
},
},
validate: (value) => value !== undefined,
default: {
stringVal: "abc",
numVal: 123,
boolValue: false,
},
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
get: (value: any) => {
return value;
},
set: (value: any) => {
return value;
}
},
mapValue: {
type: "map",
properties: {
stringVal: {
type: "string",
default: () => "abc",
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
numVal: {
type: "number",
default: () => 10,
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
boolValue: {
type: "boolean",
default: () => false,
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
enumVal: {
type: ["abc", "def"] as const,
validate: (value: "abc" | "def") => value !== undefined,
default: () => "abc",
get: (value: "abc" | "def") => {
return value;
},
set: (value?: "abc" | "def") => {
return value;
}
},
stringListValue: {
type: "list",
items: {
type: "string",
default: "abc",
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
default: [],
validate: (value: string[]) => value !== undefined,
get: (value: string[]) => {
return value;
},
set: (value?: string[]) => {
return value;
}
},
numberListValue: {
type: "list",
items: {
type: "number",
default: () => 100,
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
default: [123, 123],
validate: (value: number[]) => value !== undefined,
get: (value: number[]) => {
return value;
},
set: (value?: number[]) => {
return value;
}
},
mapListValue: {
type: "list",
items: {
type: "map",
properties: {
stringVal: {
type: "string",
default: "def",
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
numVal: {
type: "number",
default: 100,
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
boolValue: {
type: "boolean",
default: () => false,
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
stringSetValue: {
type: "set",
items: "string",
default: ["abc"],
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
numberSetValue: {
type: "set",
items: "number",
default: [5],
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
enumVal: {
type: ["abc", "def"] as const,
validate: (value: "abc" | "def") => value !== undefined,
default: () => "abc",
get: (value: "abc" | "def") => {
return value;
},
set: (value?: "abc" | "def") => {
return value;
}
},
},
default: () => ({
stringVal: "anx",
numVal: 13,
boolValue: true,
emumValue: "abc",
stringSetValue: ["def"],
numberSetValue: [10],
}),
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
},
default: [],
validate: (value: Record<string, any>[]) => value !== undefined,
get: (value: Record<string, any>[]) => {
return value;
},
set: (value?: Record<string, any>[]) => {
return value;
}
},
},
default: () => undefined,
validate: (value) => value !== undefined,
get: (value) => {
return value;
},
set: (value) => {
return value;
}
}
},
indexes: {
user: {
collection: "complexShapes",
pk: {
composite: ["username"],
field: "pk"
},
sk: {
composite: [],
field: "sk"
}
},
_: {
collection: "owned",
index: "gsi1pk-gsi1sk-index",
pk: {
composite: ["username"],
field: "gsi1pk"
},
sk: {
field: "gsi1sk",
composite: []
}
}
}
}, {table: "abc"});
const mapTests = new Entity({
model: {
entity: "mapTests",
service: "tests",
version: "1"
},
attributes: {
username: {
type: "string"
},
mapObject: {
type: "map",
properties: {
minimal: {
type: "string"
},
required: {
type: "string",
required: true
},
hidden: {
type: "string",
hidden: true
},
readOnly: {
type: "string",
readOnly: true
},
anotherMap: {
type: "map",
properties: {
minimal: {
type: "string"
},
required: {
type: "string",
required: true
},
hidden: {
type: "string",
hidden: true
},
readOnly: {
type: "string",
readOnly: true
}
}
}
}
}
},
indexes: {
user: {
collection: "complexShapes",
pk: {
composite: ["username"],
field: "pk"
},
sk: {
composite: [],
field: "sk"
}
}
}
});
const complexAttributeService = new Service({mapTests, complex});
mapTests
.get({username: "test"})
.go()
.then(data => {
if (data && data.mapObject !== undefined) {
expectNotAssignable<string>(data.mapObject.hidden);
expectType<undefined|string>(data.mapObject.minimal);
expectType<undefined|string>(data.mapObject.readOnly);
expectType<string>(data.mapObject.required);
}
});
type MapTestPutParameters = Parameter<typeof mapTests.put>;
// just the key is fine because `mapObject` is not required
expectAssignable<MapTestPutParameters>([{username: "abc"}]);
// with mapObject present, `required` is required
mapTests.put({username: "abc", mapObject: {required: "val"}});
mapTests.put([{username: "abc", mapObject: {required: "val"}}]);
expectError(() => {
mapTests.put({username: "abc", mapObject: {minimal: "abc"}});
});
expectError(() => {
mapTests.put([{username: "abc", mapObject: {minimal: "abc"}}]);
});
// with anotherMap present, `required` is required
mapTests.put({username: "abc", mapObject: {required: "val", anotherMap: {required: "def"}}});
mapTests.put([{username: "abc", mapObject: {required: "val", anotherMap: {required: "def"}}}]);
expectError(() => {
mapTests.put({username: "abc", mapObject: {minimal: "abc", required: "def", anotherMap: {}}});
});
expectError(() => {
mapTests.put([{username: "abc", mapObject: {minimal: "abc", required: "def", anotherMap: {}}}]);
});
//
mapTests.update({username: "abc"}).data((attr, op) => {
expectError(() => op.set(attr.mapObject.readOnly, "abc"));
expectError(() => op.set(attr.mapObject.anotherMap.readOnly, "abc"));
op.set(attr.mapObject.minimal, "abc");
op.set(attr.mapObject.anotherMap.minimal, "abc");
op.set(attr.mapObject.hidden, "abc");
op.set(attr.mapObject.anotherMap.hidden, "abc");
op.set(attr.mapObject.required, "abc");
op.set(attr.mapObject.anotherMap.required, "abc");
// START SHOULD FAIL :(
// expectError(() => op.remove(attr.mapObject.readOnly));
// expectError(() => op.remove(attr.mapObject.required));
// expectError(() => op.set(attr.mapObject, {}));
// expectError(() => op.set(attr.mapObject, {minimal: "abc"}));
// END SHOULD FAIL :(
op.set(attr.mapObject, {required: "anc"});
});
expectError(() => mapTests.update({username: "abc"}).remove(["username"]));
complexAttributeService.collections
.complexShapes({username: "abc"})
.where((attr, op) => {
op.eq(attr.mapObject.minimal, "abc");
op.eq(attr.numberListValue[0], 123)
op.eq(attr.mapListValue[1].enumVal, "def");
op.eq(attr.mapListValue[1].numVal, 345);
return "";
})
.go()
// `value` operation should return the type of value for more constrained usage
complex.update({username: "abc"})
.data((attr, op) => {
const numberValue = op.value(attr.numVal, 10);
op.set(attr.numVal, numberValue);
op.set(attr.mapValue.numVal, numberValue);
expectError(() => op.set(attr.mapValue.stringVal, numberValue));
})
.where((attr, op) => {
const num = 10;
const numberValue = op.value(attr.numVal, num);
op.eq(attr.numVal, numberValue);
op.eq(attr.mapValue.numVal, numberValue);
expectError(() => op.eq(attr.mapValue.stringVal, numberValue));
return "";
})
.go()
// casing property on schema
const casingEntity = new Entity({
model: {
service: "MallStoreDirectory",
entity: "MallStores",
version: "1",
},
attributes: {
id: {
type: "string",
field: "id",
},
mall: {
type: "string",
required: true,
field: "mall",
},
stores: {
type: "number",
},
value: {
type: "string"
}
},
indexes: {
store: {
collection: ["myCollection"],
pk: {
field: "parition_key",
composite: ["id"],
casing: "lower",
},
sk: {
field: "sort_key",
composite: ["mall", "stores"],
casing: "upper",
}
},
other: {
index: "idx1",
collection: "otherCollection",
pk: {
field: "parition_key_idx1",
composite: ["mall"],
casing: "upper",
},
sk: {
field: "sort_key_idx1",
composite: ["id", "stores"],
casing: "default",
}
}
}
}, {table: "StoreDirectory"});
type RequiredIndexOptions = Required<Schema<any, any, any>["indexes"][string]>;
type PKCasingOptions = RequiredIndexOptions["pk"]["casing"];
type SKCasingOptions = RequiredIndexOptions["sk"]["casing"];
const allCasingOptions = "" as "default" | "upper" | "lower" | "none" | undefined;
expectAssignable<PKCasingOptions>(allCasingOptions);
expectAssignable<SKCasingOptions>(allCasingOptions);
expectError<PKCasingOptions>("not_available");
expectError<SKCasingOptions>("not_available");
type AvailableParsingOptions = Parameters<typeof casingEntity.parse>[1]
expectAssignable<AvailableParsingOptions>(undefined);
expectAssignable<AvailableParsingOptions>({});
expectAssignable<AvailableParsingOptions>({ignoreOwnership: true});
expectAssignable<AvailableParsingOptions>({ignoreOwnership: false}); | the_stack |
import {Series} from 'uplot';
import {DataSeriesExtended, DataSeries, SnapToValue, ProcessingSettings, ProcessingInterpolation} from '../types';
import {TooltipSection} from '../plugins/tooltip/types';
/**
* Finds index of point in ranges of Y-Axis values.
* Returns index of starting range when idx < Y <= idx next
*
* @param {TooltipSection} section - tooltip section
* @param {number} value - Y value of cursor
* @param {boolean} stickToRanges - if true, then always return index of range
* @returns {number | null}
*/
export const findInRange = (section: TooltipSection, value: number, stickToRanges = true): number | null => {
const positive = value >= 0;
let max = -Infinity,
maxIdx = null;
let min = Infinity,
minIdx = null;
const diffs: Array<number | null> = [];
let result: number | null = null;
section.rows.forEach((row) => {
const {displayY: y, rowIdx} = row;
let diff: number | null;
if (y !== null) {
if (y > max) {
max = y;
maxIdx = row.rowIdx;
}
if (y < min) {
min = y;
minIdx = row.rowIdx;
}
}
if (y === null || (positive ? y < 0 : y >= 0)) {
diff = null;
} else if (positive) {
diff = value > y ? null : y - value;
} else {
diff = value < y ? null : Math.abs(y - value);
}
const currentMin = result === null ? Infinity : (diffs[result] as number);
const nextMin = diff === null ? currentMin : Math.min(currentMin, diff);
if ((diff !== null && currentMin === diff) || nextMin !== currentMin) {
result = rowIdx;
}
});
if (result === null && stickToRanges) {
return value >= max ? maxIdx : value <= min ? minIdx : null;
}
return result;
};
/* Gets sum of all values of given data index by all series */
export const getSumByIdx = (series: DataSeriesExtended[], seriesOptions: Series[], idx: number, scale: string) => {
let sum = 0;
let i = 0;
while (i < series.length) {
const serie = series[i];
const opts = seriesOptions[seriesOptions.length - i - 1];
i += 1;
if (opts.scale !== scale || opts.show === false) {
continue;
}
const value = serie[idx];
sum += typeof value === 'number' ? value : 0;
}
return sum;
};
/**
* Finds index of nearest non-null point in range of Y-Axis values
*
* @param {TooltipSection} section
* @param {number} value
* @returns {number | null}
*/
export const findSticky = (section: TooltipSection, value: number): number | null => {
const ranges = section.rows.map((x) => x.displayY);
let nearestIndex;
let nearestValue;
let i = 0;
while (!nearestValue && i < ranges.length) {
const r = ranges[i];
if (r !== null) {
nearestIndex = i;
nearestValue = Math.abs(r - (value || 0));
}
i += 1;
}
if (!nearestValue || nearestIndex === undefined) {
return null;
}
for (i = nearestIndex + 1; i < ranges.length; i++) {
const v = ranges[i];
if (v === null) {
continue;
}
const diff = Math.abs(v - value);
if (nearestValue > diff) {
nearestValue = diff;
nearestIndex = i;
}
}
return nearestIndex;
};
export const getUnitSuffix = (value: number): [number, string] => {
if (value >= 1e18) {
return [1e18, 'E'];
} else if (value >= 1e15) {
return [1e15, 'P'];
} else if (value >= 1e12) {
return [1e12, 'T'];
} else if (value >= 1e9) {
return [1e9, 'G'];
} else if (value >= 1e6) {
return [1e6, 'M'];
} else if (value >= 1e3) {
return [1e3, 'K'];
}
return [1, ''];
};
/* Number.toFixed() wihout rounding */
export function toFixed(num: number, fixed: number) {
if (fixed === 0) {
return parseInt(num as unknown as string);
}
if (Number.isInteger(num)) {
return num + '.' + '0'.repeat(fixed);
}
const [int, frac] = num.toString().split('.');
return frac.length >= fixed ? `${int}.${frac.slice(0, fixed)}` : `${int}.${frac}${'0'.repeat(fixed - frac.length)}`;
}
/**
* Finds nearest non-null value's index in data series by given direction
*
* @param {DataSeriesExtended} data - Series data
* @param {Series} series - Series options
* @param {number} idx - cursor index
* @param {SnapToValue | false} defaultSnapTo - default value for direction
* @param {unknown} skipValue - value to skip
* @returns {number}
*/
export function findDataIdx(
data: DataSeriesExtended,
series: Series,
idx: number,
defaultSnapTo: SnapToValue | false = 'closest',
skipValue: unknown = null,
) {
let corL = idx,
corR = idx;
const direction = series.snapToValues ?? defaultSnapTo;
if (direction === false) {
return idx;
}
if (direction === 'left' || direction === 'closest') {
for (let i = idx - 1; i >= 0; i--) {
if (data[i] !== skipValue) {
corL = i;
break;
}
}
}
if (direction === 'right' || direction === 'closest') {
for (let i = idx + 1; i < data.length; i++) {
if (data[i] !== skipValue) {
corR = i;
break;
}
}
}
if (direction === 'left') {
return corL;
}
if (direction === 'right') {
return corR;
}
return corR - idx > idx - corL ? corL : corR;
}
/*
* Interpolation function
*/
const interpolateImpl = (
timeline: number[],
y1: number | null,
y2: number | null,
x1: number,
x2: number,
xIdx: number,
iGroup: number[],
type: ProcessingInterpolation['type'] | number = 'linear',
) => {
let result = null;
const x = timeline[xIdx];
switch (type) {
case 'linear': {
if (y1 === null || y2 === null) {
return null;
}
result = y1 + ((x - x1) * (y2 - y1)) / (x2 - x1);
if (isNaN(result) || Math.abs(result) === Infinity) {
result = null;
}
break;
}
case 'previous': {
result = y1;
break;
}
case 'next': {
result = y2;
break;
}
case 'left': {
result = iGroup[iGroup.length - 1] === timeline.length - 1 || y2 === null ? null : y1;
break;
}
case 'right': {
result = iGroup[0] === 0 ? null : y2;
break;
}
case 'closest': {
const lD = Math.abs(x1 - timeline[xIdx]);
const rD = Math.abs(x2 - timeline[xIdx]);
result = lD < rD ? y1 : y2;
break;
}
default: {
result = type;
}
}
return result;
};
export const genId = () => Math.random().toString(36).substr(2, 9).replace(/^\d+/, '');
/**
* Processing data series to:
* 1. Find missing data and interpolate these points
* 2. Find string special values to convert them to nulls
*
* @param {DataSeriesExtended[]} series
* @param {number[]} timeline
* @param {ProcessingSettings} settings
* @returns {DataSeries[]}
*/
export const preprocess = (
series: DataSeriesExtended[],
timeline: number[],
settings: ProcessingSettings,
): DataSeries[] => {
const result = [];
const nullValues = settings.nullValues || {};
const interpolation = settings.interpolation;
for (let sIdx = 0; sIdx < series.length; sIdx++) {
const line = series[sIdx];
const resultLine = [];
let iGroup = [];
let y1 = null,
y2 = null,
x1,
x2;
for (let idx = 0; idx < line.length; idx++) {
let val = line[idx];
if (interpolation && val === interpolation.value) {
iGroup.push(idx);
continue;
}
if (nullValues[val as string]) {
val = null;
}
if (iGroup.length) {
y2 = val;
x2 = timeline[idx];
for (const iIdx of iGroup) {
resultLine[iIdx] = interpolateImpl(
timeline,
y1 as number | null,
y2 as number | null,
x1 || timeline[0],
x2 || timeline[timeline.length - 1],
iIdx,
iGroup,
interpolation && interpolation.type,
);
}
iGroup = [];
}
y1 = val;
x1 = timeline[idx];
resultLine.push(val);
}
y2 = null;
if (iGroup.length) {
for (const iIdx of iGroup) {
resultLine.push(
interpolateImpl(
timeline,
y1 as number | null,
y2 as number | null,
x1 || timeline[0],
x2 || timeline[timeline.length - 1],
iIdx,
iGroup,
interpolation && interpolation.type,
),
);
}
}
result.push(resultLine);
}
return result as DataSeries[];
};
export const exec = <T, ArgsT extends unknown[]>(s: T | ((...a: ArgsT) => T), ...args: ArgsT) => {
return typeof s === 'function' ? (s as (...a: ArgsT) => T)(...args) : s;
};
export function debounce<T extends Array<unknown> = []>(func: (...args: T) => void, timeout = 300) {
let timer: ReturnType<typeof setTimeout>;
return (...args: T) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), timeout);
};
}
export const assignKeys = <T>(keys: (keyof T)[], f: T, t: T) => {
keys.forEach((key) => {
if (t[key] !== undefined) {
f[key] = t[key];
}
});
}; | the_stack |
import {Flags, descriptor2typestr, forwardResult, initString, reescapeJVMName, getTypes} from './util';
import * as util from './util';
import ByteStream from './ByteStream';
import {IAttribute, makeAttributes, Signature, RuntimeVisibleAnnotations, Code, Exceptions} from './attributes';
import {ConstantPool, ConstUTF8, MethodReference, InterfaceMethodReference} from './ConstantPool';
import {ReferenceClassData, ArrayClassData, ClassData} from './ClassData';
import {JVMThread, annotateOpcode, BytecodeStackFrame} from './threading';
import assert from './assert';
import {ThreadStatus, OpcodeLayoutType, OpCode, OpcodeLayouts, MethodHandleReferenceKind} from './enums';
import Monitor from './Monitor';
import StringOutputStream from './StringOutputStream';
import * as JVMTypes from '../includes/JVMTypes';
import global from './global';
import {JitInfo, opJitInfo} from './jit';
declare var RELEASE: boolean;
if (typeof RELEASE === 'undefined') global.RELEASE = false;
var trapped_methods: { [clsName: string]: { [methodName: string]: Function } } = {
'java/lang/ref/Reference': {
// NOP, because we don't do our own GC and also this starts a thread?!?!?!
'<clinit>()V': function (thread: JVMThread): void { }
},
'java/lang/System': {
'loadLibrary(Ljava/lang/String;)V': function (thread: JVMThread, libName: JVMTypes.java_lang_String): void {
// Some libraries test if native libraries are available,
// and expect an exception if they are not.
// List all of the native libraries we support.
var lib = libName.toString();
switch (lib) {
case 'zip':
case 'net':
case 'nio':
case 'awt':
case 'fontmanager':
case 'management':
return;
default:
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', `no ${lib} in java.library.path`);
break;
}
}
},
'java/lang/Terminator': {
'setup()V': function (thread: JVMThread): void {
// XXX: We should probably fix this; we support threads now.
// Historically: NOP'd because we didn't support threads.
}
},
'java/nio/charset/Charset$3': {
// this is trapped and NOP'ed for speed
'run()Ljava/lang/Object;': function (thread: JVMThread, javaThis: JVMTypes.java_nio_charset_Charset$3): JVMTypes.java_lang_Object {
return null;
}
},
'sun/nio/fs/DefaultFileSystemProvider': {
// OpenJDK doesn't know what the "Doppio" platform is. Tell it to use the Linux file system.
'create()Ljava/nio/file/spi/FileSystemProvider;': function(thread: JVMThread): void {
thread.setStatus(ThreadStatus.ASYNC_WAITING);
var dfsp: ReferenceClassData<JVMTypes.sun_nio_fs_DefaultFileSystemProvider> = <any> thread.getBsCl().getInitializedClass(thread, 'Lsun/nio/fs/DefaultFileSystemProvider;'),
dfspCls: typeof JVMTypes.sun_nio_fs_DefaultFileSystemProvider = <any> dfsp.getConstructor(thread);
dfspCls['createProvider(Ljava/lang/String;)Ljava/nio/file/spi/FileSystemProvider;'](thread, [thread.getJVM().internString('sun.nio.fs.LinuxFileSystemProvider')], forwardResult(thread));
}
}
};
function getTrappedMethod(clsName: string, methSig: string): Function {
clsName = descriptor2typestr(clsName);
if (trapped_methods.hasOwnProperty(clsName) && trapped_methods[clsName].hasOwnProperty(methSig)) {
return trapped_methods[clsName][methSig];
}
return null;
}
/**
* Shared functionality between Method and Field objects, as they are
* represented similarly in class files.
*/
export class AbstractMethodField {
/**
* The declaring class of this method or field.
*/
public cls: ReferenceClassData<JVMTypes.java_lang_Object>;
/**
* The method / field's index in its defining class's method/field array.
*/
public slot: number;
/**
* The method / field's flags (e.g. static).
*/
public accessFlags: Flags;
/**
* The name of the field, without the descriptor or owning class.
*/
public name: string;
/**
* The method/field's type descriptor.
* e.g.:
* public String foo; => Ljava/lang/String;
* public void foo(String bar); => (Ljava/lang/String;)V
*/
public rawDescriptor: string;
/**
* Any attributes on this method or field.
*/
public attrs: IAttribute[];
/**
* Constructs a field or method object from raw class data.
*/
constructor(cls: ReferenceClassData<JVMTypes.java_lang_Object>, constantPool: ConstantPool, slot: number, byteStream: ByteStream) {
this.cls = cls;
this.slot = slot;
this.accessFlags = new Flags(byteStream.getUint16());
this.name = (<ConstUTF8> constantPool.get(byteStream.getUint16())).value;
this.rawDescriptor = (<ConstUTF8> constantPool.get(byteStream.getUint16())).value;
this.attrs = makeAttributes(byteStream, constantPool);
}
public getAttribute(name: string): IAttribute {
for (var i = 0; i < this.attrs.length; i++) {
var attr = this.attrs[i];
if (attr.getName() === name) {
return attr;
}
}
return null;
}
public getAttributes(name: string): IAttribute[] {
return this.attrs.filter((attr) => attr.getName() === name);
}
/**
* Get the particular type of annotation as a JVM byte array. Returns null
* if the annotation does not exist.
*/
protected getAnnotationType(thread: JVMThread, name: string): JVMTypes.JVMArray<number> {
var annotation = <{ rawBytes: Buffer }> <any> this.getAttribute(name);
if (annotation === null) {
return null;
}
var byteArrCons = (<ArrayClassData<number>> thread.getBsCl().getInitializedClass(thread, '[B')).getConstructor(thread),
rv = new byteArrCons(thread, 0);
// TODO: Convert to typed array.
var i: number, len = annotation.rawBytes.length, arr = new Array(len);
for (i = 0; i < len; i++) {
arr[i] = annotation.rawBytes.readInt8(i);
}
rv.array = arr;
return rv;
}
// To satiate TypeScript. Consider it an 'abstract' method.
public parseDescriptor(raw_descriptor: string): void {
throw new Error("Unimplemented error.");
}
}
export class Field extends AbstractMethodField {
/**
* The field's full name, which includes the defining class
* (e.g. java/lang/String/value).
*/
public fullName: string;
constructor(cls: ReferenceClassData<JVMTypes.java_lang_Object>, constantPool: ConstantPool, slot: number, byteStream: ByteStream) {
super(cls, constantPool, slot, byteStream);
this.fullName = `${descriptor2typestr(cls.getInternalName())}/${this.name}`;
}
/**
* Calls cb with the reflectedField if it succeeds. Calls cb with null if it
* fails.
*/
public reflector(thread: JVMThread, cb: (reflectedField: JVMTypes.java_lang_reflect_Field) => void): void {
var signatureAttr = <Signature> this.getAttribute("Signature"),
jvm = thread.getJVM(),
bsCl = thread.getBsCl();
var createObj = (typeObj: JVMTypes.java_lang_Class): JVMTypes.java_lang_reflect_Field => {
var fieldCls = <ReferenceClassData<JVMTypes.java_lang_reflect_Field>> bsCl.getInitializedClass(thread, 'Ljava/lang/reflect/Field;'),
fieldObj = new (fieldCls.getConstructor(thread))(thread);
fieldObj['java/lang/reflect/Field/clazz'] = this.cls.getClassObject(thread);
fieldObj['java/lang/reflect/Field/name'] = jvm.internString(this.name);
fieldObj['java/lang/reflect/Field/type'] = typeObj;
fieldObj['java/lang/reflect/Field/modifiers'] = this.accessFlags.getRawByte();
fieldObj['java/lang/reflect/Field/slot'] = this.slot;
fieldObj['java/lang/reflect/Field/signature'] = signatureAttr !== null ? initString(bsCl, signatureAttr.sig) : null;
fieldObj['java/lang/reflect/Field/annotations'] = this.getAnnotationType(thread, 'RuntimeVisibleAnnotations');
return fieldObj;
};
// Our field's type may not be loaded, so we asynchronously load it here.
// In the future, we can speed up reflection by having a synchronous_reflector
// method that we can try first, and which may fail.
this.cls.getLoader().resolveClass(thread, this.rawDescriptor, (cdata: ClassData) => {
if (cdata != null) {
cb(createObj(cdata.getClassObject(thread)));
} else {
cb(null);
}
});
}
private getDefaultFieldValue(): string {
var desc = this.rawDescriptor;
if (desc === 'J') return 'gLongZero';
var c = desc[0];
if (c === '[' || c === 'L') return 'null';
return '0';
}
/**
* Outputs a JavaScript field assignment for this field.
*/
public outputJavaScriptField(jsConsName: string, outputStream: StringOutputStream): void {
if (this.accessFlags.isStatic()) {
outputStream.write(`${jsConsName}["${reescapeJVMName(this.fullName)}"] = cls._getInitialStaticFieldValue(thread, "${reescapeJVMName(this.name)}");\n`);
} else {
outputStream.write(`this["${reescapeJVMName(this.fullName)}"] = ${this.getDefaultFieldValue()};\n`);
}
}
}
const opcodeSize: number[] = function() {
const table: number[] = [];
table[OpcodeLayoutType.OPCODE_ONLY] = 1;
table[OpcodeLayoutType.CONSTANT_POOL_UINT8] = 2;
table[OpcodeLayoutType.CONSTANT_POOL] = 3;
table[OpcodeLayoutType.CONSTANT_POOL_AND_UINT8_VALUE] = 4;
table[OpcodeLayoutType.UINT8_VALUE] = 2;
table[OpcodeLayoutType.UINT8_AND_INT8_VALUE] = 3;
table[OpcodeLayoutType.INT8_VALUE] = 2;
table[OpcodeLayoutType.INT16_VALUE] = 3;
table[OpcodeLayoutType.INT32_VALUE] = 5;
table[OpcodeLayoutType.ARRAY_TYPE] = 2;
table[OpcodeLayoutType.WIDE] = 1;
return table;
}();
class TraceInfo {
pops: string[] = [];
pushes: string[] = [];
prefixEmit: string = "";
onErrorPushes: string[];
constructor(public pc: number, public jitInfo: JitInfo) {
}
}
class Trace {
private infos: TraceInfo[] = [];
private endPc: number = -1;
constructor(public startPC: number, private code: Buffer, private method: Method) {
}
/**
* Emits a PC update statement at the end of the trace.
*/
public emitEndPC(pc: number): void {
this.endPc = pc;
}
public addOp(pc: number, jitInfo: JitInfo) {
this.infos.push(new TraceInfo(pc, jitInfo));
}
public close(thread: JVMThread): Function {
if (this.infos.length > 1) {
const symbolicStack: string[] = [];
let symbolCount = 0;
// Ensure that the last statement sets the PC if the
// last opcode doesn't.
let emitted = this.endPc > -1 ? `f.pc=${this.endPc};` : "";
for (let i = 0; i < this.infos.length; i++) {
const info = this.infos[i];
const jitInfo = info.jitInfo;
const pops = info.pops;
const normalizedPops = jitInfo.pops < 0 ? Math.min(-jitInfo.pops, symbolicStack.length) : jitInfo.pops;
for (let j = 0; j < normalizedPops; j++) {
if (symbolicStack.length > 0) {
pops.push(symbolicStack.pop());
} else {
const symbol = "s" + symbolCount++;
info.prefixEmit += `var ${symbol} = f.opStack.pop();`;
pops.push(symbol);
}
}
info.onErrorPushes = symbolicStack.slice();
const pushes = info.pushes;
for (let j = 0; j < jitInfo.pushes; j++) {
const symbol = "s" + symbolCount++;
symbolicStack.push(symbol);
pushes.push(symbol);
}
}
if (symbolicStack.length === 1) {
emitted += `f.opStack.push(${symbolicStack[0]});`;
} else if (symbolicStack.length > 1) {
emitted += `f.opStack.pushAll(${symbolicStack.join(',')});`;
}
for (let i = this.infos.length-1; i >= 0; i--) {
const info = this.infos[i];
const jitInfo = info.jitInfo;
emitted = info.prefixEmit + jitInfo.emit(info.pops, info.pushes, ""+i, emitted, this.code, info.pc, info.onErrorPushes, this.method);
}
if (!RELEASE && thread.getJVM().shouldPrintJITCompilation()) {
console.log(`Emitted trace of ${this.infos.length} ops: ` + emitted);
}
// f = frame, t = thread, u = util
return new Function("f", "t", "u", emitted);
} else {
if (!RELEASE && thread.getJVM().shouldPrintJITCompilation()) {
console.log(`Trace was cancelled`);
}
return null;
}
}
}
export class Method extends AbstractMethodField {
/**
* The method's parameters, if any, in descriptor form.
*/
public parameterTypes: string[];
/**
* The method's return type in descriptor form.
*/
public returnType: string;
/**
* The method's signature, e.g. bar()V
*/
public signature: string;
/**
* The method's signature, including defining class; e.g. java/lang/String/bar()V
*/
public fullSignature: string;
/**
* The number of JVM words required to store the parameters (e.g. longs/doubles take up 2 words).
* Does not include the "this" argument to non-static functions.
*/
private parameterWords: number;
/**
* Code is either a function, or a CodeAttribute.
* TODO: Differentiate between NativeMethod objects and BytecodeMethod objects.
*/
private code: any;
/**
* number of basic block entries
*/
private numBBEntries = 0;
private compiledFunctions: Function[] = [];
private failedCompile: boolean[] = [];
constructor(cls: ReferenceClassData<JVMTypes.java_lang_Object>, constantPool: ConstantPool, slot: number, byteStream: ByteStream) {
super(cls, constantPool, slot, byteStream);
var parsedDescriptor = getTypes(this.rawDescriptor), i: number,
p: string;
this.signature = this.name + this.rawDescriptor;
this.fullSignature = `${descriptor2typestr(this.cls.getInternalName())}/${this.signature}`;
this.returnType = parsedDescriptor.pop();
this.parameterTypes = parsedDescriptor;
this.parameterWords = parsedDescriptor.length;
// Double count doubles / longs.
for (i = 0; i < this.parameterTypes.length; i++) {
p = this.parameterTypes[i];
if (p === 'D' || p === 'J') {
this.parameterWords++;
}
}
// Initialize 'code' property.
var clsName = this.cls.getInternalName();
if (getTrappedMethod(clsName, this.signature) !== null) {
this.code = getTrappedMethod(clsName, this.signature);
this.accessFlags.setNative(true);
} else if (this.accessFlags.isNative()) {
if (this.signature.indexOf('registerNatives()V', 0) < 0 && this.signature.indexOf('initIDs()V', 0) < 0) {
// The first version of the native method attempts to fetch itself and
// rewrite itself.
var self = this;
this.code = function(thread: JVMThread) {
// Try to fetch the native method.
var jvm = thread.getJVM(),
c = jvm.getNative(clsName, self.signature);
if (c == null) {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', `Native method '${self.getFullSignature()}' not implemented.\nPlease fix or file a bug at https://github.com/plasma-umass/doppio/issues`);
} else {
self.code = c;
return c.apply(self, arguments);
}
};
} else {
// Stub out initIDs and registerNatives.
this.code = () => { };
}
} else if (!this.accessFlags.isAbstract()) {
this.code = this.getAttribute('Code');
const codeLength = this.code.code.length;
// jit threshold. we countdown to zero from here.
this.numBBEntries = codeLength > 3 ? 200 : 1000 * codeLength;
}
}
public incrBBEntries() {
// Optimisiation: we countdown to zero, instead of storing a positive limit in a separate variable
this.numBBEntries--;
}
/**
* Checks if the method is a default method.
* A default method is a public non-abstract instance method, that
* is, a non-static method with a body, declared in an interface
* type.
*/
public isDefault(): boolean {
return (this.accessFlags.isPublic() && !this.accessFlags.isAbstract() && !this.accessFlags.isStatic() && this.cls.accessFlags.isInterface());
}
public getFullSignature(): string {
return `${this.cls.getExternalName()}.${this.name}${this.rawDescriptor}`;
}
/**
* Checks if this particular method should be hidden in stack frames.
* Used by OpenJDK's lambda implementation to hide lambda boilerplate.
*/
public isHidden(): boolean {
var rva: RuntimeVisibleAnnotations = <any> this.getAttribute('RuntimeVisibleAnnotations');
return rva !== null && rva.isHidden;
}
/**
* Checks if this particular method has the CallerSensitive annotation.
*/
public isCallerSensitive(): boolean {
var rva: RuntimeVisibleAnnotations = <any> this.getAttribute('RuntimeVisibleAnnotations');
return rva !== null && rva.isCallerSensitive;
}
/**
* Get the number of machine words (32-bit words) required to store the
* parameters to this function. Includes adding in a machine word for 'this'
* for non-static functions.
*/
public getParamWordSize(): number {
return this.parameterWords;
}
public getCodeAttribute(): Code {
assert(!this.accessFlags.isNative() && !this.accessFlags.isAbstract());
return this.code;
}
public getOp(pc: number, codeBuffer: Buffer, thread: JVMThread): any {
if (this.numBBEntries <= 0) {
if (!this.failedCompile[pc]) {
const cachedCompiledFunction = this.compiledFunctions[pc];
if (!cachedCompiledFunction) {
const compiledFunction = this.jitCompileFrom(pc, thread);
if (compiledFunction) {
return compiledFunction;
} else {
this.failedCompile[pc] = true;
}
} else {
return cachedCompiledFunction;
}
}
}
return codeBuffer[pc];
}
private makeInvokeStaticJitInfo(code: Buffer, pc: number) : JitInfo {
const index = code.readUInt16BE(pc + 1);
const methodReference = <MethodReference | InterfaceMethodReference> this.cls.constantPool.get(index);
const paramSize = methodReference.paramWordSize;
return {hasBranch: true, pops: -paramSize, pushes: 0, emit: (pops, pushes, suffix, onSuccess) => {
const argInitialiser = paramSize > pops.length ? `f.opStack.sliceAndDropFromTop(${paramSize - pops.length});` : `[${pops.reduce((a,b) => b + ',' + a, '')}];`;
let argMaker = `var args${suffix}=` + argInitialiser;
if ((paramSize > pops.length) && (pops.length > 0)) {
argMaker += `args${suffix}.push(${pops.slice().reverse().join(',')});`;
}
return argMaker + `
var methodReference${suffix}=f.method.cls.constantPool.get(${index});
f.pc=${pc};
methodReference${suffix}.jsConstructor[methodReference${suffix}.fullSignature](t,args${suffix});
f.returnToThreadLoop=true;
${onSuccess}`;
}};
}
private makeInvokeVirtualJitInfo(code: Buffer, pc: number) : JitInfo {
const index = code.readUInt16BE(pc + 1);
const methodReference = <MethodReference | InterfaceMethodReference> this.cls.constantPool.get(index);
const paramSize = methodReference.paramWordSize;
return {hasBranch: true, pops: -(paramSize + 1), pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes);
const argInitialiser = paramSize > pops.length ? `f.opStack.sliceAndDropFromTop(${paramSize - pops.length});` : `[${pops.slice(0, paramSize).reduce((a,b) => b + ',' + a, '')}];`;
let argMaker = `var args${suffix}=` + argInitialiser;
if ((paramSize > pops.length) && (pops.length > 0)) {
argMaker += `args${suffix}.push(${pops.slice().reverse().join(',')});`;
}
return argMaker + `var obj${suffix}=${(paramSize+1)===pops.length?pops[paramSize]:"f.opStack.pop()"};f.pc=${pc};
if(!u.isNull(t,f,obj${suffix})){obj${suffix}['${methodReference.signature}'](t,args${suffix});f.returnToThreadLoop=true;${onSuccess}}else{${onError}}`;
}};
}
private makeInvokeNonVirtualJitInfo(code: Buffer, pc: number) : JitInfo {
const index = code.readUInt16BE(pc + 1);
const methodReference = <MethodReference | InterfaceMethodReference> this.cls.constantPool.get(index);
const paramSize = methodReference.paramWordSize;
return {hasBranch: true, pops: -(paramSize + 1), pushes: 0, emit: (pops, pushes, suffix, onSuccess, code, pc, onErrorPushes) => {
const onError = makeOnError(onErrorPushes);
const argInitialiser = paramSize > pops.length ? `f.opStack.sliceAndDropFromTop(${paramSize - pops.length});` : `[${pops.slice(0, paramSize).reduce((a,b) => b + ',' + a, '')}];`;
let argMaker = `var args${suffix}=` + argInitialiser;
if ((paramSize > pops.length) && (pops.length > 0)) {
argMaker += `args${suffix}.push(${pops.slice().reverse().join(',')});`;
}
return argMaker + `var obj${suffix}=${(paramSize+1)===pops.length?pops[paramSize]:"f.opStack.pop()"};f.pc=${pc};
if(!u.isNull(t,f,obj${suffix})){obj${suffix}['${methodReference.fullSignature}'](t, args${suffix});f.returnToThreadLoop=true;${onSuccess}}else{${onError}}`;
}};
}
private jitCompileFrom(startPC: number, thread: JVMThread) {
if (!RELEASE && thread.getJVM().shouldPrintJITCompilation()) {
console.log(`Planning to JIT: ${this.fullSignature} from ${startPC}`);
}
const code = this.getCodeAttribute().getCode();
let trace: Trace = null;
const self = this;
let done = false;
function closeCurrentTrace() {
if (trace !== null) {
// console.log("Tracing method: " + self.fullSignature);
const compiledFunction = trace.close(thread);
if (compiledFunction) {
self.compiledFunctions[trace.startPC] = compiledFunction;
if (!RELEASE && thread.getJVM().shouldDumpCompiledCode()) {
thread.getJVM().dumpCompiledMethod(self.fullSignature, trace.startPC, compiledFunction.toString());
}
}
trace = null;
}
done = true;
}
for (let i = startPC; i < code.length && !done;) {
const op = code[i];
// TODO: handle wide()
if (!RELEASE && thread.getJVM().shouldPrintJITCompilation()) {
console.log(`${i}: ${annotateOpcode(op, this, code, i)}`);
}
const jitInfo = opJitInfo[op];
if (jitInfo) {
if (trace === null) {
trace = new Trace(i, code, self);
}
trace.addOp(i, jitInfo);
if (jitInfo.hasBranch) {
this.failedCompile[i] = true;
closeCurrentTrace();
}
} else if (op === OpCode.INVOKESTATIC_FAST && trace !== null) {
const invokeJitInfo: JitInfo = this.makeInvokeStaticJitInfo(code, i);
trace.addOp(i, invokeJitInfo);
this.failedCompile[i] = true;
closeCurrentTrace();
} else if (((op === OpCode.INVOKEVIRTUAL_FAST) || (op === OpCode.INVOKEINTERFACE_FAST)) && trace !== null) {
const invokeJitInfo: JitInfo = this.makeInvokeVirtualJitInfo(code, i);
trace.addOp(i, invokeJitInfo);
this.failedCompile[i] = true;
closeCurrentTrace();
} else if ((op === OpCode.INVOKENONVIRTUAL_FAST) && trace !== null) {
const invokeJitInfo: JitInfo = this.makeInvokeNonVirtualJitInfo(code, i);
trace.addOp(i, invokeJitInfo);
this.failedCompile[i] = true;
closeCurrentTrace();
} else {
if (!RELEASE) {
if (trace !== null) {
statTraceCloser[op]++;
}
}
this.failedCompile[i] = true;
if (trace) {
trace.emitEndPC(i);
}
closeCurrentTrace();
}
i += opcodeSize[OpcodeLayouts[op]];
}
return self.compiledFunctions[startPC];
}
public getNativeFunction(): Function {
assert(this.accessFlags.isNative() && typeof (this.code) === 'function');
return this.code;
}
/**
* Resolves all of the classes referenced through this method. Required in
* order to create its reflection object.
*/
private _resolveReferencedClasses(thread: JVMThread, cb: (classes: {[ className: string ]: ClassData}) => void): void {
// Start with the return type + parameter types + reflection object types.
var toResolve: string[] = this.parameterTypes.concat(this.returnType),
code: Code = this.code,
exceptionAttribute = <Exceptions> this.getAttribute("Exceptions");
// Exception handler types.
if (!this.accessFlags.isNative() && !this.accessFlags.isAbstract() && code.exceptionHandlers.length > 0) {
toResolve.push('Ljava/lang/Throwable;'); // Mimic native Java (in case <any> is the only handler).
// Filter out the <any> handlers.
toResolve = toResolve.concat(code.exceptionHandlers.filter((handler) => handler.catchType !== '<any>').map((handler) => handler.catchType));
}
// Resolve checked exception types.
if (exceptionAttribute !== null) {
toResolve = toResolve.concat(exceptionAttribute.exceptions);
}
this.cls.getLoader().resolveClasses(thread, toResolve, (classes: {[className: string]: ClassData}) => {
// Use bootstrap classloader for reflection classes.
thread.getBsCl().resolveClasses(thread, ['Ljava/lang/reflect/Method;', 'Ljava/lang/reflect/Constructor;'], (classes2: {[className: string]: ClassData}) => {
if (classes === null || classes2 === null) {
cb(null);
} else {
classes['Ljava/lang/reflect/Method;'] = classes2['Ljava/lang/reflect/Method;'];
classes['Ljava/lang/reflect/Constructor;'] = classes2['Ljava/lang/reflect/Constructor;'];
cb(classes);
}
});
});
}
/**
* Get a reflection object representing this method.
*/
public reflector(thread: JVMThread, cb: (reflectedMethod: JVMTypes.java_lang_reflect_Executable) => void): void {
var bsCl = thread.getBsCl(),
// Grab the classes required to construct the needed arrays.
clazzArray = (<ArrayClassData<JVMTypes.java_lang_Class>> bsCl.getInitializedClass(thread, '[Ljava/lang/Class;')).getConstructor(thread),
jvm = thread.getJVM(),
// Grab the needed
signatureAttr = <Signature> this.getAttribute("Signature"),
exceptionAttr = <Exceptions> this.getAttribute("Exceptions");
// Retrieve all of the required class references.
this._resolveReferencedClasses(thread, (classes: { [className: string ]: ClassData }) => {
if (classes === null) {
return cb(null);
}
// Construct the needed objects for the reflection object.
var clazz = this.cls.getClassObject(thread),
name = jvm.internString(this.name),
parameterTypes = new clazzArray(thread, 0),
returnType = classes[this.returnType].getClassObject(thread),
exceptionTypes = new clazzArray(thread, 0),
modifiers = this.accessFlags.getRawByte(),
signature = signatureAttr !== null ? jvm.internString(signatureAttr.sig) : null;
// Prepare the class arrays.
parameterTypes.array = this.parameterTypes.map((ptype: string) => classes[ptype].getClassObject(thread));
if (exceptionAttr !== null) {
exceptionTypes.array = exceptionAttr.exceptions.map((eType: string) => classes[eType].getClassObject(thread));
}
if (this.name === '<init>') {
// Constructor object.
var consCons = (<ReferenceClassData<JVMTypes.java_lang_reflect_Constructor>> classes['Ljava/lang/reflect/Constructor;']).getConstructor(thread),
consObj = new consCons(thread);
consObj['java/lang/reflect/Constructor/clazz'] = clazz;
consObj['java/lang/reflect/Constructor/parameterTypes'] = parameterTypes;
consObj['java/lang/reflect/Constructor/exceptionTypes'] = exceptionTypes;
consObj['java/lang/reflect/Constructor/modifiers'] = modifiers;
consObj['java/lang/reflect/Constructor/slot'] = this.slot;
consObj['java/lang/reflect/Constructor/signature'] = signature;
consObj['java/lang/reflect/Constructor/annotations'] = this.getAnnotationType(thread, 'RuntimeVisibleAnnotations');
consObj['java/lang/reflect/Constructor/parameterAnnotations'] = this.getAnnotationType(thread, 'RuntimeVisibleParameterAnnotations');
cb(consObj);
} else {
// Method object.
var methodCons = (<ReferenceClassData<JVMTypes.java_lang_reflect_Method>> classes['Ljava/lang/reflect/Method;']).getConstructor(thread),
methodObj = new methodCons(thread);
methodObj['java/lang/reflect/Method/clazz'] = clazz;
methodObj['java/lang/reflect/Method/name'] = name;
methodObj['java/lang/reflect/Method/parameterTypes'] = parameterTypes;
methodObj['java/lang/reflect/Method/returnType'] = returnType;
methodObj['java/lang/reflect/Method/exceptionTypes'] = exceptionTypes;
methodObj['java/lang/reflect/Method/modifiers'] = modifiers;
methodObj['java/lang/reflect/Method/slot'] = this.slot;
methodObj['java/lang/reflect/Method/signature'] = signature;
methodObj['java/lang/reflect/Method/annotations'] = this.getAnnotationType(thread, 'RuntimeVisibleAnnotations');
methodObj['java/lang/reflect/Method/annotationDefault'] = this.getAnnotationType(thread, 'AnnotationDefault');
methodObj['java/lang/reflect/Method/parameterAnnotations'] = this.getAnnotationType(thread, 'RuntimeVisibleParameterAnnotations');
cb(methodObj);
}
});
}
/**
* Convert the arguments to this method into a form suitable for a native
* implementation.
*
* The JVM uses two parameter slots for double and long values, since they
* consist of two JVM machine words (32-bits). Doppio stores the entire value
* in one slot, and stores a NULL in the second.
*
* This function strips out these NULLs so the arguments are in a more
* consistent form. The return value is the arguments to this function without
* these NULL values. It also adds the 'thread' object to the start of the
* arguments array.
*/
public convertArgs(thread: JVMThread, params: any[]): any[] {
if (this.isSignaturePolymorphic()) {
// These don't need any conversion, and have arbitrary arguments.
// Just append the thread object.
params.unshift(thread);
return params;
}
var convertedArgs = [thread], argIdx = 0, i: number;
if (!this.accessFlags.isStatic()) {
convertedArgs.push(params[0]);
argIdx = 1;
}
for (i = 0; i < this.parameterTypes.length; i++) {
var p = this.parameterTypes[i];
convertedArgs.push(params[argIdx]);
argIdx += (p === 'J' || p === 'D') ? 2 : 1;
}
return convertedArgs;
}
/**
* Lock this particular method.
*/
public methodLock(thread: JVMThread, frame: BytecodeStackFrame): Monitor {
if (this.accessFlags.isStatic()) {
// Static methods lock the class.
return this.cls.getClassObject(thread).getMonitor();
} else {
// Non-static methods lock the instance.
return (<JVMTypes.java_lang_Object> frame.locals[0]).getMonitor();
}
}
/**
* Check if this is a signature polymorphic method.
* From S2.9:
* A method is signature polymorphic if and only if all of the following conditions hold :
* * It is declared in the java.lang.invoke.MethodHandle class.
* * It has a single formal parameter of type Object[].
* * It has a return type of Object.
* * It has the ACC_VARARGS and ACC_NATIVE flags set.
*/
public isSignaturePolymorphic(): boolean {
return this.cls.getInternalName() === 'Ljava/lang/invoke/MethodHandle;' &&
this.accessFlags.isNative() && this.accessFlags.isVarArgs() &&
this.rawDescriptor === '([Ljava/lang/Object;)Ljava/lang/Object;';
}
/**
* Retrieve the MemberName/invokedynamic JavaScript "bridge method" that
* encapsulates the logic required to call this particular method.
*/
public getVMTargetBridgeMethod(thread: JVMThread, refKind: number): (thread: JVMThread, descriptor: string, args: any[], cb?: (e?: JVMTypes.java_lang_Throwable, rv?: any) => void) => void {
// TODO: Could cache these in the Method object if desired.
var outStream = new StringOutputStream(),
virtualDispatch = !(refKind === MethodHandleReferenceKind.INVOKESTATIC || refKind === MethodHandleReferenceKind.INVOKESPECIAL);
// Args: thread, cls, util
if (this.accessFlags.isStatic()) {
assert(!virtualDispatch, "Can't have static virtual dispatch.");
outStream.write(`var jsCons = cls.getConstructor(thread);\n`);
}
outStream.write(`function bridgeMethod(thread, descriptor, args, cb) {\n`);
if (!this.accessFlags.isStatic()) {
outStream.write(` var obj = args.shift();\n`);
outStream.write(` if (obj === null) { return thread.throwNewException('Ljava/lang/NullPointerException;', ''); }\n`);
outStream.write(` obj["${reescapeJVMName(virtualDispatch ? this.signature : this.fullSignature)}"](thread, `);
} else {
outStream.write(` jsCons["${reescapeJVMName(this.fullSignature)}"](thread, `);
}
// TODO: Is it ever appropriate to box arguments for varargs functions? It appears not.
outStream.write(`args`);
outStream.write(`, cb);
}
return bridgeMethod;`);
var evalText = outStream.flush();
if (!RELEASE && thread !== null && thread.getJVM().shouldDumpCompiledCode()) {
thread.getJVM().dumpBridgeMethod(this.fullSignature, evalText);
}
return new Function("thread", "cls", "util", evalText)(thread, this.cls, util);
}
/**
* Generates JavaScript code for this particular method.
* TODO: Move lock logic and such into this function! And other specialization.
* TODO: Signature polymorphic functions...?
*/
public outputJavaScriptFunction(jsConsName: string, outStream: StringOutputStream, nonVirtualOnly: boolean = false): void {
var i: number;
if (this.accessFlags.isStatic()) {
outStream.write(`${jsConsName}["${reescapeJVMName(this.fullSignature)}"] = ${jsConsName}["${reescapeJVMName(this.signature)}"] = `);
} else {
if (!nonVirtualOnly) {
outStream.write(`${jsConsName}.prototype["${reescapeJVMName(this.signature)}"] = `);
}
outStream.write(`${jsConsName}.prototype["${reescapeJVMName(this.fullSignature)}"] = `);
}
// cb check is boilerplate, required for natives calling into JVM land.
outStream.write(`(function(method) {
return function(thread, args, cb) {
if (typeof cb === 'function') {
thread.stack.push(new InternalStackFrame(cb));
}
thread.stack.push(new ${this.accessFlags.isNative() ? "NativeStackFrame" : "BytecodeStackFrame"}(method, `);
if (!this.accessFlags.isStatic()) {
// Non-static functions need to add the implicit 'this' variable to the
// local variables.
outStream.write(`[this`);
// Give the JS engine hints about the size, type, and contents of the array
// by making it a literal.
for (i = 0; i < this.parameterWords; i++) {
outStream.write(`, args[${i}]`);
}
outStream.write(`]`);
} else {
// Static function doesn't need to mutate the arguments.
if (this.parameterWords > 0) {
outStream.write(`args`);
} else {
outStream.write(`[]`);
}
}
outStream.write(`));
thread.setStatus(${ThreadStatus.RUNNABLE});
};
})(cls.getSpecificMethod("${reescapeJVMName(this.cls.getInternalName())}", "${reescapeJVMName(this.signature)}"));\n`);
}
}
function makeOnError(onErrorPushes: string[]) {
return onErrorPushes.length > 0 ? `f.opStack.pushAll(${onErrorPushes.join(',')});` : '';
}
const statTraceCloser: number[] = new Array(256);
if (!RELEASE) {
for (let i = 0; i < 256; i++) {
statTraceCloser[i] = 0;
}
}
export function dumpStats() {
const range = new Array(256);
for (let i = 0; i < 256; i++) {
range[i] = i;
}
range.sort((x, y) => statTraceCloser[y] - statTraceCloser[x]);
const top = range.slice(0, 24);
console.log("Opcodes that closed a trace (number of times encountered):");
for (let i = 0; i < top.length; i++) {
const op = top[i];
if (statTraceCloser[op] > 0) {
console.log(OpCode[op], statTraceCloser[op]);
}
}
} | the_stack |
"use strict";
// uuid: 19d4bf0d-48f2-4d72-bcfa-32a636038b50
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
/** @module end-user | The lines bellow convey information for the end-user */
/**
* ## Description
*
* <i class="fa fa-exclamation-triangle fa-lg"></i>
* **Warning** This is still an experimental technology,
* to push forward the development in this field,
* please, consider leaving your donation or become a sponsor.
*
* **Teleporting** is the process of splitting the story created in one machine
* into its constituting pieces and then from this pieces,
* recreate the story in a remote machine, in order to generate
* the physical story frames images in this remote machine.
*
* Teleporting allows a user to create animations just by using **a web browser
* from a computer or tablet** without the need of installed software
* nor direct access to the computer files.
*
* It was created with the main goal of allowing video hosting services,
* ad network, and e-commerce companies to allow their users
* or employees to build their animation in their machines,
* and then generate the video on the company's machines.
*
* It can also be used, in case where the user is on a controlled
* computer environment defined by the company's policy
* or in case there is a faster machine available for rendering,
* specially when the story contains heavy computational WebGL elements.
*
* The [ABeamer Animation Editor](animation-editor.md) will allow
* to bring the remote rending to new heights.
*
* Without the ABeamer Animation Editor, it's required that the user has
* basic skills of CSS and HTML. JavaScript programming skills aren't required.
*
* Due restrictions imposed by [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)
* It's required that:
*
* - The client either runs on a remote link or runs under a live server.
* ABeamer includes a live server. Just execute `abeamer serve`
* - The render server agent must execute the url from a live server.
*
* With the current technology still has following limitations,
* some of them imposed due security reasons:
*
* - [Code Handlers](Code Handler) aren't allowed.
* - Only default scenes are allowed.
* - Scenes can't be removed during the execution.
* - Only fixed remote assets are allowed.
* - Use only functionality that isn't marked as: doesn't supports teleporting.
* - Assets inside CSS files must have the `url("....") format`
* and be part of the project structure.
* - No `<style>` tag inside html file is allowed.
* - No `<script>` files are allowed.
*
*
* ## Usage
*
* The whole process is fairly simple, just follow these steps:
*
* - create a project using abeamer command line called `my-project`.
*
* ```shell
* abeamer create my-project
* ```
*
* - download [animate-transitions](/gallery/latest/animate-transitions/code.zip),
* and unzip to the newly created folder `my-project`. When asked to overwrite the files, select 'Yes'.
* This is just a complete example of story ready to teleport.
* The following steps are for testing purposes, for production mode will be
* described after.
*
* - Run the live server:
*
* ```shell
* abeamer serve
* ```
*
* Due CORS and since this is a local file it requires a live server.
*
* - Execute:
*
* ```shell
* abeamer render my-project --url http://localhost:9000/my-project/ --teleport
* ```
*
* This will create a file called `story.json` on `my-project` folder.
*
* - create a project using abeamer command line called `server`.
*
* ```shell
* abeamer create server
* ```
*
* Download [remote-server](/gallery/latest/remote-server/code.zip),
* and unzip to the newly created folder `server`. When asked to overwrite the files, select 'Yes'.
*
* - Copy the `story.json` from the `my-project` folder to the `server` folder.
*
* - Copy all the assets sub-folder from the `my-project` folder to the `server` folder.
*
* - Execute:
*
* ```shell
* abeamer render \
* --url http://localhost:9000/server/ \
* --allowed-plugins server/.allowed-plugins.json \
* --inject-page server/index.html \
* --config server/story.json
* ```
*
* This will generate the frames on `server/story-frames`.
*
*
* The previous steps where built for testing purposes,
* since the teleporter was built to be used without the need of using anything
* but the web browser.
*
* For production mode:
*
* 1. Open on chrome the following url: `http://localhost:9000/gallery/animate-transitions/`.
*
* 2. Uncomment both code lines on the 'animate-transitions/js/main.ts'.
* And either compile using TypeScript or port those lines into main.js.
* This will create the story with `{ toTeleport: true }`.
* Which will record every part of the animation and instruct the library and plugins
* to behave differently.
*
* 3. On chrome developer tools, you will see on the console the complete story as string.
* This data was generated via `story.getStoryToTeleport()`
* This is the data you have to send via Ajax to the remote server.
*
* In this case, it's no longer needed: `abeamer render --teleport`, nor access to the computer disk.
*
* ## How it works?
*
* When a story is created with `toTeleport = true`, ABeamer will:
*
* 1. Store a copy of the initial html and CSS (due CORS, it requires a live server).
* 2. When transitions, stills or pEls are used, it will behave differently in order to be recorded into a file.
* 3. On each addAnimations, a deep copy will be stored before tasks modify its content.
* 4. Plugins will check if it's on teleporting mode, and act according to it.
*
* Instead of calling render, the `getStoryToTeleport` will generate data ready to be teleported.
* This data must be **beamed** to the remote machine, usually via Ajax.
*
* `getStoryToTeleport` will return a string, if you want to add more parameters,
* use `getStoryToTeleportAsConfig`, and it will return an Object.
* ABeamer uses only `config.abeamer` record inside the generated object,
* any other field can be used to store extra data.
*
* The remote machine has an empty story body,
* see [remote-server](/gallery/latest/#remote-server), where it fills
* with the data has been teleported and injects the plugins.
*
*
* ## Security tips
*
* ABeamer is an open-source library, which runs inside a contained environment such as a web browser,
* and doesn't allows the execution of any javascript code except from plugins.
* However, in order to prevent malicious users or plugins, ensure that:
*
* 1. **Only allow 3rd party plugins from trusted sources**.
* 2. Execute the live server in a contained environment.
* 3. Don't place any password files accessible to the live server.
* 4. The provided live server, is just a simple live server, consider using a more restrict live server.
* 5. Blacklist from the browser the access to the local network resources.
* 6. Use only the latest versions of the ABeamer, browser, and render server.
* 7. Set the maxWidth, maxHeight, maxFps and maxFrameCount parameters for `abeamer render`
* 8. Move the files .allowed-plugins.json and story.json from the user access.
*/
namespace ABeamer {
interface CSSRule {
/**
* Path is the local path to CSS file used to remap url references.
*/
path: string;
text: string;
}
export class _InnerConfig {
version?: string;
width?: uint;
height?: uint;
fps?: uint;
file?: string;
userAgent?: string;
locale?: string;
renderPos?: uint;
renderCount?: int;
metadata?: StoryMetadata;
plugins?: PluginInfo[];
html?: string[];
css?: CSSRule[];
animations?: Animations[][];
}
export class _Teleporter {
protected _active: boolean = false;
protected _cfg: _InnerConfig;
protected _story: _StoryImpl;
hasStory: boolean = false;
constructor(story: _StoryImpl, cfg: _InnerConfig, isTeleport: boolean) {
this._story = story;
this._cfg = cfg;
if (isTeleport) {
pluginManager._plugins.forEach(plugin => {
if (!plugin.teleportable) {
throwErr(`Plugin ${plugin.id} doesn't supports teleporting`);
}
});
this._active = true;
// these parameters should come first
cfg.version = VERSION;
cfg.locale = pluginManager._locale;
cfg.file = cfg.file || "__PROJDIR__/index.html";
cfg.renderPos = 0;
cfg.renderCount = 0;
cfg.userAgent = window.navigator.userAgent;
cfg.metadata = {};
// this parameters because tend to be longer should come at the end.
cfg.plugins = pluginManager._plugins;
cfg.animations = [];
} else {
this.hasStory = cfg.html !== undefined;
}
}
createSnapshot(): void {
this._cfg.html = (this._story.storyAdapter.getProp('html', this._story._args) as string).split(/\n/);
this._cfg.css = _getStoryCSS();
}
get active() {
return this._active;
}
_getStoryToTeleportAsConfig(): StoryConfig {
this._cfg.renderPos = this._story.renderFramePos;
this._cfg.renderCount = this._story.renderFrameCount;
this._cfg.metadata = this._story.metadata;
return { config: { abeamer: this._cfg } };
}
_rebuildStory(): void {
const story = this._story;
// css must be rebuilt before html.
if (this._cfg.css) {
_buildCssRulesFromConfig(this._cfg.css);
}
if (this._cfg.html) {
story.storyAdapter.setProp('html',
_sanitizeHtml(this._cfg.html.join('\n')), story._args);
story.addDefaultScenes();
}
if (this._cfg.animations) {
story.addStoryAnimations(this._cfg.animations);
}
if (this._cfg.metadata) {
_filteredDeepCopy(this._cfg.metadata, story.metadata);
}
}
_addScene(): void {
this._cfg.animations.push([]);
}
_addAnimations(anime: Animations, sceneIndex: uint): void {
this._cfg.animations[sceneIndex].push(_filteredDeepCopy(anime, []));
}
_fillFrameOpts(frameOpts: RenderFrameOptions): RenderFrameOptions {
frameOpts = frameOpts || {};
// during teleporting don't use stored frameOptions.
if (this._active) { return frameOpts; }
// disabled for now, until is found a fix.
// frameOpts.renderPos = frameOpts.renderPos || this._cfg.renderPos;
// frameOpts.renderCount = frameOpts.renderCount || this._cfg.renderCount;
return frameOpts;
}
}
function _getStoryCSS(): CSSRule[] {
const pageRoot = _getPageRoot();
const styleSheets = window.document.styleSheets;
const rules: CSSRule[] = [];
for (let sheetI = 0; sheetI < styleSheets.length; sheetI++) {
const style = styleSheets[sheetI] as CSSStyleSheet;
const styleHref = style.href;
if (styleHref.endsWith('normalize.css')
|| styleHref.endsWith('abeamer.min.css')) {
continue;
}
const path = styleHref.startsWith(pageRoot) ?
styleHref.substr(pageRoot.length).replace(/\/[^/]*$/, '/') : '';
const cssRules = style.cssRules;
for (let ruleI = 0; ruleI < cssRules.length; ruleI++) {
const cssRule = cssRules[ruleI];
rules.push({ path, text: cssRule.cssText });
}
}
return rules;
}
/**
* Recursively copies one object into another, and sanitizes the input
* to ensure there are no javascript functions.
* keys starting with `_` aren't copied.
*/
function _filteredDeepCopy(src: any, dst: any): any {
if (Array.isArray(src)) {
src.forEach(item => {
switch (typeof item) {
case 'function':
throwI8n(Msgs.NoCode);
break;
case 'object':
dst.push(_filteredDeepCopy(item, Array.isArray(item) ? [] : {}));
break;
default:
dst.push(item);
}
});
} else {
Object.keys(src).forEach(key => {
if (key[0] !== '_') {
const item = src[key];
switch (typeof item) {
case 'function':
throwI8n(Msgs.NoCode);
break;
case 'object':
dst[key] = Array.isArray(item) ? [] : {};
_filteredDeepCopy(item, dst[key]);
break;
default:
dst[key] = item;
}
}
});
}
return dst;
}
function _buildCssRulesFromConfig(cssRules: CSSRule[]): void {
const pageRoot = _getPageRoot();
const styleSheets = window.document.styleSheets;
const lastSheet = styleSheets[styleSheets.length - 1] as CSSStyleSheet;
let cssRulesLen = lastSheet.cssRules.length;
for (let i = 0; i < cssRules.length; i++) {
const cssRule = cssRules[i];
const prefixedCssRule = _handleVendorPrefixes(cssRule.text);
const remappedRule = _remapCSSRuleLocalLink(pageRoot, cssRule.path,
prefixedCssRule);
lastSheet.insertRule(remappedRule, cssRulesLen++);
}
}
/** Prevents scripts to be injected to the teleported story. */
function _sanitizeHtml(html: string): string {
return html.replace(/\<\s*script/gi, '');
}
/** Returns the url location of the current web page without the html file name. */
function _getPageRoot(): string {
const location = window.location;
return location.origin + (location.pathname || '').replace(/\/[^/]*$/, '/');
}
/**
* Adds or removes vendor prefixes from the teleported story.
*/
function _handleVendorPrefixes(text: string): string {
return text.replace(/([\w\-]+)\s*:([^;]*;)/g, (_all, propName, propValue) => {
const propNames = _propNameToVendorProps(propName);
return propNames.map(name => `${name}: ${propValue}`).join(' ');
});
}
/**
* When CSS rules are injected, the web browser has a different behavior
* regarding local url links inside CSS files.
* This function from the original path and current host generates a new link.
*/
function _remapCSSRuleLocalLink(pageRoot: string, path: string,
cssText: string): string {
return !path ? path : cssText.replace(/url\("([^"]+)"\)/g, (all, link) => {
if (link.startsWith('http')) { return all; }
const newLink = pageRoot + path + link;
return `url("${newLink}")`;
});
}
} | the_stack |
class BKTokenizer {
constructor(public keywords: any, public builtinFunctions: any) {
this.keywords = keywords
this.builtinFunctions = builtinFunctions
}
getTokenizer() {
const defaultKeywords = [
"ACCESSIBLE", "ACCOUNT", "ACTION", "ADD", "AFTER", "AGAINST", "AGGREGATE", "ALGORITHM", "ALL", "ALTER", "ALWAYS", "ANALYSE", "ANALYZE",
"AND", "ANY", "AS", "ASC", "ASCII", "ASENSITIVE", "AT", "AUTOEXTEND_SIZE", "AUTO_INCREMENT", "AVG", "AVG_ROW_LENGTH", "BACKUP", "BEFORE",
"BEGIN", "BETWEEN", "BIGINT", "BINARY", "BINLOG", "BIT", "BLOB", "BLOCK", "BOOL", "BOOLEAN", "BOTH", "BTREE", "BY", "BYTE", "CACHE", "CALL",
"CASCADE", "CASCADED", "CASE", "CATALOG_NAME", "CHAIN", "CHANGE", "CHANGED", "CHANNEL", "CHAR", "CHARACTER", "CHARSET", "CHECK", "CHECKSUM",
"CIPHER", "CLASS_ORIGIN", "CLIENT", "CLOSE", "COALESCE", "CODE", "COLLATE", "COLLATION", "COLUMN", "COLUMNS", "COLUMN_FORMAT", "COLUMN_NAME",
"COMMENT", "COMMIT", "COMMITTED", "COMPACT", "COMPLETION", "COMPRESSED", "COMPRESSION", "CONCURRENT", "CONDITION", "CONNECTION", "CONSISTENT",
"CONSTRAINT", "CONSTRAINT_CATALOG", "CONSTRAINT_NAME", "CONSTRAINT_SCHEMA", "CONTAINS", "CONTEXT", "CONTINUE", "CONVERT", "CPU", "CREATE",
"CROSS", "CUBE", "CURRENT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "CURSOR_NAME", "DATA", "DATABASE",
"DATABASES", "DATAFILE", "DATE", "DATETIME", "DAY", "DAY_HOUR", "DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND", "DEALLOCATE", "DEC", "DECIMAL",
"DECLARE", "DEFAULT", "DEFAULT_AUTH", "DEFINER", "DELAYED", "DELAY_KEY_WRITE", "DELETE", "DESC", "DESCRIBE", "DES_KEY_FILE", "DETERMINISTIC",
"DIAGNOSTICS", "DIRECTORY", "DISABLE", "DISCARD", "DISK", "DISTINCT", "DISTINCTROW", "DIV", "DO", "DOUBLE", "DROP", "DUAL", "DUMPFILE",
"DUPLICATE", "DYNAMIC", "EACH", "ELSE", "ELSEIF", "ENABLE", "ENCLOSED", "ENCRYPTION", "END", "ENDS", "ENGINE", "ENGINES", "ENUM", "ERROR",
"ERRORS", "ESCAPE", "ESCAPED", "EVENT", "EVENTS", "EVERY", "EXCHANGE", "EXECUTE", "EXISTS", "EXIT", "EXPANSION", "EXPIRE", "EXPLAIN", "EXPORT",
"EXTENDED", "EXTENT_SIZE", "FALSE", "FAST", "FAULTS", "FETCH", "FIELDS", "FILE", "FILE_BLOCK_SIZE", "FILTER", "FIRST", "FIXED", "FLOAT", "FLOAT4",
"FLOAT8", "FLUSH", "FOLLOWS", "FOR", "FORCE", "FOREIGN", "FORMAT", "FOUND", "FROM", "FULL", "FULLTEXT", "FUNCTION", "GENERAL", "GENERATED",
"GEOMETRY", "GEOMETRYCOLLECTION", "GET", "GET_FORMAT", "GLOBAL", "GRANT", "GRANTS", "GROUP", "GROUP_REPLICATION", "HANDLER", "HASH", "HAVING",
"HELP", "HIGH_PRIORITY", "HOST", "HOSTS", "HOUR", "HOUR_MICROSECOND", "HOUR_MINUTE", "HOUR_SECOND", "IDENTIFIED", "IF", "IGNORE", "IGNORE_SERVER_IDS",
"IMPORT", "INDEX", "INDEXES", "INFILE", "INITIAL_SIZE", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INSERT_METHOD", "INSTALL", "INSTANCE",
"INT", "INT1", "INT2", "INT3", "INT4", "INT8", "INTEGER", "INTERVAL", "INTO", "INVOKER", "IO", "IO_AFTER_GTIDS", "IO_BEFORE_GTIDS", "IO_THREAD",
"IPC", "ISOLATION", "ISSUER", "ITERATE", "JOIN", "JSON", "KEY", "KEYS", "KEY_BLOCK_SIZE", "KILL", "LANGUAGE", "LAST", "LEADING", "LEAVE",
"LEAVES", "LEFT", "LESS", "LEVEL", "LIKE", "LIMIT", "LINEAR", "LINES", "LINESTRING", "LIST", "LOAD", "LOCAL", "LOCALTIME", "LOCALTIMESTAMP", "LOCK",
"LOCKS", "LOGFILE", "LOGS", "LONG", "LONGBLOB", "LONGTEXT", "LOOP", "LOW_PRIORITY", "MASTER", "MASTER_AUTO_POSITION", "MASTER_BIND", "MASTER_CONNECT_RETRY",
"MASTER_DELAY", "MASTER_HEARTBEAT_PERIOD", "MASTER_HOST", "MASTER_LOG_FILE", "MASTER_LOG_POS", "MASTER_PASSWORD", "MASTER_PORT", "MASTER_RETRY_COUNT",
"MASTER_SERVER_ID", "MASTER_SSL", "MASTER_SSL_CA", "MASTER_SSL_CAPATH", "MASTER_SSL_CERT", "MASTER_SSL_CIPHER", "MASTER_SSL_CRL", "MASTER_SSL_CRLPATH",
"MASTER_SSL_KEY", "MASTER_SSL_VERIFY_SERVER_CERT", "MASTER_TLS_VERSION", "MASTER_USER", "MATCH", "MAXVALUE", "MAX_CONNECTIONS_PER_HOUR", "MAX_QUERIES_PER_HOUR",
"MAX_ROWS", "MAX_SIZE", "MAX_STATEMENT_TIME", "MAX_UPDATES_PER_HOUR", "MAX_USER_CONNECTIONS", "MEDIUM", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MEMORY",
"MERGE", "MESSAGE_TEXT", "MICROSECOND", "MIDDLEINT", "MIGRATE", "MINUTE", "MINUTE_MICROSECOND", "MINUTE_SECOND", "MIN_ROWS", "MOD", "MODE", "MODIFIES",
"MODIFY", "MONTH", "MULTILINESTRING", "MULTIPOINT", "MULTIPOLYGON", "MUTEX", "MYSQL_ERRNO", "NAME", "NAMES", "NATIONAL", "NATURAL", "NCHAR", "NDB",
"NDBCLUSTER", "NEVER", "NEW", "NEXT", "NO", "NODEGROUP", "NONBLOCKING", "NONE", "NO_WAIT", "NO_WRITE_TO_BINLOG", "NUMBER", "NUMERIC",
"NVARCHAR", "OFFSET", "OLD_PASSWORD", "ON", "ONE", "ONLY", "OPEN", "OPTIMIZE", "OPTIMIZER_COSTS", "OPTION", "OPTIONALLY", "OPTIONS", "OR", "ORDER",
"OUT", "OUTER", "OUTFILE", "OWNER", "PACK_KEYS", "PAGE", "PARSER", "PARSE_GCOL_EXPR", "PARTIAL", "PARTITION", "PARTITIONING", "PARTITIONS", "PASSWORD",
"PHASE", "PLUGIN", "PLUGINS", "PLUGIN_DIR", "POINT", "POLYGON", "PORT", "PRECEDES", "PRECISION", "PREPARE", "PRESERVE", "PREV", "PRIMARY", "PRIVILEGES",
"PROCEDURE", "PROCESSLIST", "PROFILE", "PROFILES", "PROXY", "PURGE", "QUARTER", "QUERY", "QUICK", "RANGE", "READ", "READS", "READ_ONLY", "READ_WRITE",
"REAL", "REBUILD", "RECOVER", "REDOFILE", "REDO_BUFFER_SIZE", "REDUNDANT", "REFERENCES", "REGEXP", "RELAY", "RELAYLOG", "RELAY_LOG_FILE", "RELAY_LOG_POS",
"RELAY_THREAD", "RELEASE", "RELOAD", "REMOVE", "RENAME", "REORGANIZE", "REPAIR", "REPEAT", "REPEATABLE", "REPLACE", "REPLICATE_DO_DB", "REPLICATE_DO_TABLE",
"REPLICATE_IGNORE_DB", "REPLICATE_IGNORE_TABLE", "REPLICATE_REWRITE_DB", "REPLICATE_WILD_DO_TABLE", "REPLICATE_WILD_IGNORE_TABLE", "REPLICATION", "REQUIRE",
"RESET", "RESIGNAL", "RESTORE", "RESTRICT", "RESUME", "RETURN", "RETURNED_SQLSTATE", "RETURNS", "REVERSE", "REVOKE", "RIGHT", "RLIKE", "ROLLBACK", "ROLLUP",
"ROTATE", "ROUTINE", "ROW", "ROWS", "ROW_COUNT", "ROW_FORMAT", "RTREE", "SAVEPOINT", "SCHEDULE", "SCHEMA", "SCHEMAS", "SCHEMA_NAME", "SECOND", "SECOND_MICROSECOND",
"SECURITY", "SELECT", "SENSITIVE", "SEPARATOR", "SERIAL", "SERIALIZABLE", "SERVER", "SESSION", "SET", "SHARE", "SHOW", "SHUTDOWN", "SIGNAL", "SIGNED", "SIMPLE",
"SLAVE", "SLOW", "SMALLINT", "SNAPSHOT", "SOCKET", "SOME", "SONAME", "SOUNDS", "SOURCE", "SPATIAL", "SPECIFIC", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING",
"SQL_AFTER_GTIDS", "SQL_AFTER_MTS_GAPS", "SQL_BEFORE_GTIDS", "SQL_BIG_RESULT", "SQL_BUFFER_RESULT", "SQL_CACHE", "SQL_CALC_FOUND_ROWS", "SQL_NO_CACHE",
"SQL_SMALL_RESULT", "SQL_THREAD", "SQL_TSI_DAY", "SQL_TSI_HOUR", "SQL_TSI_MINUTE", "SQL_TSI_MONTH", "SQL_TSI_QUARTER", "SQL_TSI_SECOND", "SQL_TSI_WEEK",
"SQL_TSI_YEAR", "SSL", "STACKED", "START", "STARTING", "STARTS", "STATS_AUTO_RECALC", "STATS_PERSISTENT", "STATS_SAMPLE_PAGES", "STATUS", "STOP", "STORAGE",
"STORED", "STRAIGHT_JOIN", "STRING", "SUBCLASS_ORIGIN", "SUBJECT", "SUBPARTITION", "SUBPARTITIONS", "SUPER", "SUSPEND", "SWAPS", "SWITCHES", "TABLE", "TABLES",
"TABLESPACE", "TABLE_CHECKSUM", "TABLE_NAME", "TEMPORARY", "TEMPTABLE", "TERMINATED", "TEXT", "THAN", "THEN", "TIME", "TIMESTAMP", "TIMESTAMPADD", "TIMESTAMPDIFF",
"TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING", "TRANSACTION", "TRIGGER", "TRIGGERS", "TRUE", "TRUNCATE", "TYPE", "TYPES", "UNCOMMITTED", "UNDEFINED", "UNDO",
"UNDOFILE", "UNDO_BUFFER_SIZE", "UNICODE", "UNINSTALL", "UNION", "UNIQUE", "UNKNOWN", "UNLOCK", "UNSIGNED", "UNTIL", "UPDATE", "UPGRADE", "USAGE", "USE", "USER",
"USER_RESOURCES", "USE_FRM", "USING", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "VALIDATION", "VALUE", "VALUES", "VARBINARY", "VARCHAR", "VARCHARACTER", "VARIABLES",
"VARYING", "VIEW", "VIRTUAL", "WAIT", "WARNINGS", "WEEK", "WEIGHT_STRING", "WHEN", "WHERE", "WHILE", "WITH", "WITHOUT", "WORK", "WRAPPER", "WRITE", "X509", "XA",
"XID", "XML", "XOR", "YEAR", "YEAR_MONTH", "ZEROFILL"
]
const defaultFunction = [
"ABS", "ACOS", "ADDDATE", "ADDTIME", "AES_DECRYPT", "AES_ENCRYPT", "ANY_VALUE", "Area", "AsBinary", "AsWKB", "ASCII", "ASIN",
"AsText", "AsWKT", "ASYMMETRIC_DECRYPT", "ASYMMETRIC_DERIVE", "ASYMMETRIC_ENCRYPT", "ASYMMETRIC_SIGN", "ASYMMETRIC_VERIFY",
"ATAN", "ATAN2", "ATAN", "AVG", "BENCHMARK", "BIN", "BIT_AND", "BIT_COUNT", "BIT_LENGTH", "BIT_OR", "BIT_XOR", "Buffer", "CAST",
"CEIL", "CEILING", "Centroid", "CHAR", "CHAR_LENGTH", "CHARACTER_LENGTH", "CHARSET", "COALESCE", "COERCIBILITY", "COLLATION",
"COMPRESS", "CONCAT", "CONCAT_WS", "CONNECTION_ID", "Contains", "CONV", "CONVERT", "CONVERT_TZ", "ConvexHull", "COS", "COT",
"COUNT", "CRC32", "CREATE_ASYMMETRIC_PRIV_KEY", "CREATE_ASYMMETRIC_PUB_KEY", "CREATE_DH_PARAMETERS", "CREATE_DIGEST", "Crosses",
"CURDATE", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURTIME", "DATABASE", "DATE", "DATE_ADD",
"DATE_FORMAT", "DATE_SUB", "DATEDIFF", "DAY", "DAYNAME", "DAYOFMONTH", "DAYOFWEEK", "DAYOFYEAR", "DECODE", "DEFAULT", "DEGREES",
"DES_DECRYPT", "DES_ENCRYPT", "Dimension", "Disjoint", "Distance", "ELT", "ENCODE", "ENCRYPT", "EndPoint", "Envelope", "Equals",
"EXP", "EXPORT_SET", "ExteriorRing", "EXTRACT", "ExtractValue", "FIELD", "FIND_IN_SET", "FLOOR", "FORMAT", "FOUND_ROWS", "FROM_BASE64",
"FROM_DAYS", "FROM_UNIXTIME", "GeomCollFromText", "GeometryCollectionFromText", "GeomCollFromWKB", "GeometryCollectionFromWKB",
"GeometryCollection", "GeometryN", "GeometryType", "GeomFromText", "GeometryFromText", "GeomFromWKB", "GeometryFromWKB", "GET_FORMAT",
"GET_LOCK", "GLength", "GREATEST", "GROUP_CONCAT", "GTID_SUBSET", "GTID_SUBTRACT", "HEX", "HOUR", "IF", "IFNULL", "INET_ATON",
"INET_NTOA", "INET6_ATON", "INET6_NTOA", "INSERT", "INSTR", "InteriorRingN", "Intersects", "INTERVAL", "IS_FREE_LOCK", "IS_IPV4",
"IS_IPV4_COMPAT", "IS_IPV4_MAPPED", "IS_IPV6", "IS_USED_LOCK", "IsClosed", "IsEmpty", "ISNULL", "IsSimple", "JSON_APPEND", "JSON_ARRAY",
"JSON_ARRAY_APPEND", "JSON_ARRAY_INSERT", "JSON_CONTAINS", "JSON_CONTAINS_PATH", "JSON_DEPTH", "JSON_EXTRACT", "JSON_INSERT", "JSON_KEYS",
"JSON_LENGTH", "JSON_MERGE", "JSON_MERGE_PRESERVE", "JSON_OBJECT", "JSON_QUOTE", "JSON_REMOVE", "JSON_REPLACE", "JSON_SEARCH", "JSON_SET",
"JSON_TYPE", "JSON_UNQUOTE", "JSON_VALID", "LAST_INSERT_ID", "LCASE", "LEAST", "LEFT", "LENGTH", "LineFromText", "LineStringFromText",
"LineFromWKB", "LineStringFromWKB", "LineString", "LN", "LOAD_FILE", "LOCALTIME", "LOCALTIMESTAMP", "LOCATE", "LOG", "LOG10", "LOG2",
"LOWER", "LPAD", "LTRIM", "MAKE_SET", "MAKEDATE", "MAKETIME", "MASTER_POS_WAIT", "MAX", "MBRContains", "MBRCoveredBy", "MBRCovers",
"MBRDisjoint", "MBREqual", "MBREquals", "MBRIntersects", "MBROverlaps", "MBRTouches", "MBRWithin", "MD5", "MICROSECOND", "MID",
"MIN", "MINUTE", "MLineFromText", "MultiLineStringFromText", "MLineFromWKB", "MultiLineStringFromWKB", "MOD", "MONTH", "MONTHNAME",
"MPointFromText", "MultiPointFromText", "MPointFromWKB", "MultiPointFromWKB", "MPolyFromText", "MultiPolygonFromText", "MPolyFromWKB",
"MultiPolygonFromWKB", "MultiLineString", "MultiPoint", "MultiPolygon", "NAME_CONST", "NOT IN", "NOW", "NULLIF", "NumGeometries",
"NumInteriorRings", "NumPoints", "OCT", "OCTET_LENGTH", "OLD_PASSWORD", "ORD", "Overlaps", "PASSWORD", "PERIOD_ADD", "PERIOD_DIFF",
"PI", "Point", "PointFromText", "PointFromWKB", "PointN", "PolyFromText", "PolygonFromText", "PolyFromWKB", "PolygonFromWKB", "Polygon",
"POSITION", "POW", "POWER", "PROCEDURE ANALYSE", "QUARTER", "QUOTE", "RADIANS", "RAND", "RANDOM_BYTES", "RELEASE_ALL_LOCKS", "RELEASE_LOCK",
"REPEAT", "REPLACE", "REVERSE", "RIGHT", "ROUND", "ROW_COUNT", "RPAD", "RTRIM", "SCHEMA", "SEC_TO_TIME", "SECOND", "SESSION_USER", "SHA1",
"SHA", "SHA2", "SIGN", "SIN", "SLEEP", "SOUNDEX", "SPACE", "SQRT", "SRID", "ST_Area", "ST_AsBinary", "ST_AsWKB", "ST_AsGeoJSON", "ST_AsText",
"ST_AsWKT", "ST_Buffer", "ST_Buffer_Strategy", "ST_Centroid", "ST_Contains", "ST_ConvexHull", "ST_Crosses", "ST_Difference", "ST_Dimension",
"ST_Disjoint", "ST_Distance", "ST_Distance_Sphere", "ST_EndPoint", "ST_Envelope", "ST_Equals", "ST_ExteriorRing", "ST_GeoHash",
"ST_GeomCollFromText", "ST_GeometryCollectionFromText", "ST_GeomCollFromTxt", "ST_GeomCollFromWKB", "ST_GeometryCollectionFromWKB",
"ST_GeometryN", "ST_GeometryType", "ST_GeomFromGeoJSON", "ST_GeomFromText", "ST_GeometryFromText", "ST_GeomFromWKB", "ST_GeometryFromWKB",
"ST_InteriorRingN", "ST_Intersection", "ST_Intersects", "ST_IsClosed", "ST_IsEmpty", "ST_IsSimple", "ST_IsValid", "ST_LatFromGeoHash",
"ST_Length", "ST_LineFromText", "ST_LineStringFromText", "ST_LineFromWKB", "ST_LineStringFromWKB", "ST_LongFromGeoHash", "ST_MakeEnvelope",
"ST_MLineFromText", "ST_MultiLineStringFromText", "ST_MLineFromWKB", "ST_MultiLineStringFromWKB", "ST_MPointFromText", "ST_MultiPointFromText",
"ST_MPointFromWKB", "ST_MultiPointFromWKB", "ST_MPolyFromText", "ST_MultiPolygonFromText", "ST_MPolyFromWKB", "ST_MultiPolygonFromWKB",
"ST_NumGeometries", "ST_NumInteriorRing", "ST_NumInteriorRings", "ST_NumPoints", "ST_Overlaps", "ST_PointFromGeoHash", "ST_PointFromText",
"ST_PointFromWKB", "ST_PointN", "ST_PolyFromText", "ST_PolygonFromText", "ST_PolyFromWKB", "ST_PolygonFromWKB", "ST_Simplify", "ST_SRID",
"ST_StartPoint", "ST_SymDifference", "ST_Touches", "ST_Union", "ST_Validate", "ST_Within", "ST_X", "ST_Y", "StartPoint", "STD", "STDDEV",
"STDDEV_POP", "STDDEV_SAMP", "STR_TO_DATE", "STRCMP", "SUBDATE", "SUBSTR", "SUBSTRING", "SUBSTRING_INDEX", "SUBTIME", "SUM", "SYSDATE",
"SYSTEM_USER", "TAN", "TIME", "TIME_FORMAT", "TIME_TO_SEC", "TIMEDIFF", "TIMESTAMP", "TIMESTAMPADD", "TIMESTAMPDIFF", "TO_BASE64", "TO_DAYS",
"TO_SECONDS", "Touches", "TRIM", "TRUNCATE", "UCASE", "UNCOMPRESS", "UNCOMPRESSED_LENGTH", "UNHEX", "UNIX_TIMESTAMP", "UpdateXML", "UPPER",
"USER", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "UUID", "UUID_SHORT", "VALIDATE_PASSWORD_STRENGTH", "VALUES", "VAR_POP", "VAR_SAMP", "VARIANCE",
"VERSION", "WAIT_FOR_EXECUTED_GTID_SET", "WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS", "WEEK", "WEEKDAY", "WEEKOFYEAR", "WEIGHT_STRING", "Within",
"X", "Y", "YEAR", "YEARWEEK"
]
return {
defaultToken: '',
tokenPostfix: '.sql',
ignoreCase: true,
brackets: [
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' }
],
keywords: this.keywords || defaultKeywords,
operators: [
"AND", "BETWEEN", "IN", "LIKE", "NOT", "OR", "IS", "NULL", "INTERSECT", "UNION", "INNER", "JOIN", "LEFT", "OUTER", "RIGHT"
],
builtinFunctions: this.builtinFunctions || defaultFunction,
builtinVariables: [
// NOT SUPPORTED
],
tokenizer: {
root: [
{ include: '@comments' },
{ include: '@whitespace' },
{ include: '@numbers' },
{ include: '@strings' },
{ include: '@complexIdentifiers' },
{ include: '@scopes' },
[/[;,.]/, 'delimiter'],
[/[()]/, '@brackets'],
[/[\w@]+/, {
cases: {
'@keywords': 'keyword',
'@operators': 'operator',
'@builtinVariables': 'predefined',
'@builtinFunctions': 'predefined',
'@default': 'identifier'
}
}],
[/[<>=!%&+\-*/|~^]/, 'operator'],
],
whitespace: [
[/\s+/, 'white']
],
comments: [
[/--+.*/, 'comment'],
[/#+.*/, 'comment'],
[/\/\*/, { token: 'comment.quote', next: '@comment' }]
],
comment: [
[/[^*/]+/, 'comment'],
// Not supporting nested comments, as nested comments seem to not be standard?
// i.e. http://stackoverflow.com/questions/728172/are-there-multiline-comment-delimiters-in-sql-that-are-vendor-agnostic
// [/\/\*/, { token: 'comment.quote', next: '@push' }], // nested comment not allowed :-(
[/\*\//, { token: 'comment.quote', next: '@pop' }],
[/./, 'comment']
],
numbers: [
[/0[xX][0-9a-fA-F]*/, 'number'],
[/[$][+-]*\d*(\.\d*)?/, 'number'],
[/((\d+(\.\d*)?)|(\.\d+))([eE][\-+]?\d+)?/, 'number']
],
strings: [
[/'/, { token: 'string', next: '@string' }],
[/"/, { token: 'string.double', next: '@stringDouble' }]
],
string: [
[/[^']+/, 'string'],
[/''/, 'string'],
[/'/, { token: 'string', next: '@pop' }],
],
stringDouble: [
[/[^"]+/, 'string.double'],
[/""/, 'string.double'],
[/"/, { token: 'string.double', next: '@pop' }]
],
complexIdentifiers: [
[/`/, { token: 'identifier.quote', next: '@quotedIdentifier' }]
],
quotedIdentifier: [
[/[^`]+/, 'identifier'],
[/``/, 'identifier'],
[/`/, { token: 'identifier.quote', next: '@pop' }]
],
scopes: [
// NOT SUPPORTED
]
}
}
}
}
export default {
getTokenizer: (keywords: any, builtinFunctions: any) => new BKTokenizer(keywords, builtinFunctions).getTokenizer()
} | the_stack |
import * as std from "tstl";
import { ParallelSystemArray } from "../parallel/ParallelSystemArray";
import { DistributedSystem } from "./DistributedSystem";
import { DistributedProcess } from "./DistributedProcess";
import { InvokeHistory } from "../slave/InvokeHistory";
import { DSInvokeHistory } from "./DSInvokeHistory";
import { XML, XMLList } from "sxml";
/**
* Master of Distributed Processing System.
*
* The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system
* drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents
* your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave**
* systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being
* requested the *distributed processes*.
*
* You can specify this {@link DistributedSystemArray} class to be *a server accepting distributed clients* or
* *a client connecting to distributed servers*. Even both of them is possible. Extends one of them below and overrides
* abstract factory method(s) creating the child {@link DistributedSystem} object.
*
* - {@link DistributedClientArray}: A server accepting {@link DistributedSystem distributed clients}.
* - {@link DistributedServerArray}: A client connecting to {@link DistributedServer distributed servers}.
* - {@link DistributedServerClientArray}: Both of them. Accepts {@link DistributedSystem distributed clients} and
* connects to {@link DistributedServer distributed servers} at the same time.
*
* The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a
* **distributed process** through the {@link DistributedProcess} object. You can access the
* {@link DistributedProcess} object(s) with those methods:
*
* - {@link hasProcess}
* - {@link getProcess}
* - {@link insertProcess}
* - {@link eraseProcess}
* - {@link getProcessMap}
*
* When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the
* {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed
* **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When
* the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and
* {@link DistributedProcess.getResource resource index} of related objects will be revaluated.
*
* <a href="http://samchon.github.io/framework/images/design/ts_class_diagram/templates_distributed_system.png"
* target="_blank">
* <img src="http://samchon.github.io/framework/images/design/ts_class_diagram/templates_distributed_system.png"
* style="max-width: 100%" />
* </a>
*
* #### Parallel Process
* This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request
* a **parallel process**, too.
*
* When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}.
* When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s
* {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will
* be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}.
*
* #### Proxy Pattern
* This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take
* advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the
* *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it
* may better to utilizing the *Proxy Pattern*:
*
* The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which
* {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not
* important. Only interested in user's perspective is *which can be done*.
*
* By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged
* to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}.
* Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}.
*
* <ul>
* <li>
* {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring
* from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}.
* </li>
* <li>
* When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call
* {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the
* external system.
* </li>
* <li> Those strategy is called *Proxy Pattern*. </li>
* </ul>
*
* @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System)
* @author Jeongho Nam <http://samchon.org>
*/
export abstract class DistributedSystemArray<System extends DistributedSystem>
extends ParallelSystemArray<System>
{
/**
* @hidden
*/
private process_map_: std.HashMap<string, DistributedProcess>;
/* ---------------------------------------------------------
CONSTRUCTORS
--------------------------------------------------------- */
/**
* Default Constructor.
*/
public constructor()
{
super();
// CREATE ROLE MAP AND ENROLL COLLECTION EVENT LISTENRES
this.process_map_ = new std.HashMap<string, DistributedProcess>();
}
/**
* @inheritdoc
*/
public construct(xml: XML): void
{
//--------
// CONSTRUCT ROLES
//--------
// CLEAR ORDINARY ROLES
this.process_map_.clear();
// CREATE ROLES
if (xml.has("processes") == true && xml.get("processes").front().has("process") == true)
{
let role_xml_list: XMLList = xml.get("processes").front().get("process");
for (let i: number = 0; i < role_xml_list.size(); i++)
{
let role_xml: XML = role_xml_list.at(i);
// CONSTRUCT ROLE FROM XML
let process: DistributedProcess = this.createProcess(role_xml);
process.construct(role_xml);
// AND INSERT TO ROLE_MAP
this.process_map_.emplace(process.getName(), process);
}
}
//--------
// CONSTRUCT SYSTEMS
//--------
super.construct(xml);
}
/**
* Factory method creating a child {@link DistributedProcess process} object.
*
* @param xml {@link XML} represents the {@link DistributedProcess child} object.
* @return A new {@link DistributedProcess} object.
*/
protected abstract createProcess(xml: XML): DistributedProcess;
/* ---------------------------------------------------------
ACCESSORS
--------------------------------------------------------- */
/**
* Get process map.
*
* Gets an {@link HashMap} containing {@link DistributedProcess} objects with their *key*.
*
* @return An {@link HasmMap> containing pairs of string and {@link DistributedProcess} object.
*/
public getProcessMap(): std.HashMap<string, DistributedProcess>
{
return this.process_map_;
}
/**
* Test whether the process exists.
*
* @param name Name, identifier of target {@link DistributedProcess process}.
*
* @return Whether the process has or not.
*/
public hasProcess(name: string): boolean
{
return this.process_map_.has(name);
}
/**
* Get a process.
*
* @param name Name, identifier of target {@link DistributedProcess process}.
*
* @return The specified process.
*/
public getProcess(name: string): DistributedProcess
{
return this.process_map_.get(name);
}
/**
* Insert a process.
*
* @param process A process to be inserted.
* @return Success flag.
*/
public insertProcess(process: DistributedProcess): boolean
{
return this.process_map_.emplace(process.getName(), process).second;
}
/**
* Erase a process.
*
* @param name Name, identifier of target {@link DistributedProcess process}.
*/
public eraseProcess(name: string): boolean
{
let prev_size: number = this.process_map_.size();
return (this.process_map_.erase(name) != prev_size);
}
/* ---------------------------------------------------------
HISTORY HANDLER - PERFORMANCE ESTIMATION
--------------------------------------------------------- */
/**
* @hidden
*/
protected _Complete_history(history: InvokeHistory): boolean
{
if (history instanceof DSInvokeHistory)
{
//--------
// DistributedProcess's history -> DSInvokeHistory
//--------
// NO ROLE, THEN FAILED TO COMPLETE
if (history.getProcess() == null)
return false;
// ESTIMATE PERFORMANCE INDEXES
this.estimate_system_performance(history); // ESTIMATE SYSTEMS' INDEX
this.estimate_process_resource(history); // ESTIMATE PROCESS' RESOURCE
// AT LAST, NORMALIZE PERFORMANCE INDEXES OF ALL SYSTEMS AND ROLES
this._Normalize_performance();
return true;
}
else
{
// ParallelSystem's history -> PRInvokeHistory
return super._Complete_history(history);
}
}
/**
* @hidden
*/
private estimate_process_resource(history: DSInvokeHistory): void
{
let process: DistributedProcess = history.getProcess();
if (process["enforced_"] == true)
return; // THE RESOURCE INDEX IS ENFORCED. DO NOT PERMIT REVALUATION
let average_elapsed_time_of_others: number = 0;
let denominator: number = 0;
// COMPUTE AVERAGE ELAPSED TIME
for (let it = this.process_map_.begin(); !it.equals(this.process_map_.end()); it = it.next())
{
let my_process: DistributedProcess = it.second;
if (my_process == history.getProcess() || my_process["history_list_"].empty() == true)
continue;
average_elapsed_time_of_others += my_process["_Compute_average_elapsed_time"]() * my_process.getResource();
denominator++;
}
// COMPARE WITH THIS HISTORY'S ELAPSED TIME
if (denominator != 0)
{
// DIVE WITH DENOMINATOR
average_elapsed_time_of_others /= denominator;
// DEDUCT NEW PERFORMANCE INDEX BASED ON THE EXECUTION TIME
// - ROLE'S PERFORMANCE MEANS; HOW MUCH TIME THE ROLE NEEDS
// - ELAPSED TIME IS LONGER, THEN PERFORMANCE IS HIGHER
let elapsed_time: number = history.computeElapsedTime() / history.getWeight(); // CONSIDER WEIGHT
let new_resource: number = elapsed_time / average_elapsed_time_of_others; // NEW PERFORMANCE
// DEDUCT RATIO TO REFLECT THE NEW PERFORMANCE INDEX -> MAXIMUM: 15%
let ordinary_ratio: number;
if (process["history_list_"].size() < 2)
ordinary_ratio = .15;
else
ordinary_ratio = Math.min(.85, 1.0 / (process["history_list_"].size() - 1.0));
// DEFINE NEW PERFORMANCE
process.setResource
(
(process.getResource() * ordinary_ratio)
+ (new_resource * (1 - ordinary_ratio))
);
}
}
/**
* @hidden
*/
private estimate_system_performance(history: DSInvokeHistory): void
{
let system: DistributedSystem = history.getSystem();
if (system["enforced_"] == true)
return; // THE PERFORMANCE INDEX IS ENFORCED. IT DOESN'T PERMIT REVALUATION
let average_elapsed_time_of_others: number = 0;
let denominator: number = 0;
// COMPUTE AVERAGE ELAPSED TIME
for (let i: number = 0; i < this.size(); i++)
{
let system: DistributedSystem = this.at(i);
let avg: number = system["_Compute_average_elapsed_time"]();
if (avg == -1)
continue;
average_elapsed_time_of_others += avg;
denominator++;
}
// COMPARE WITH THIS HISTORY'S ELAPSED TIME
if (denominator != 0)
{
// DIVE WITH DENOMINATOR
average_elapsed_time_of_others /= denominator;
// DEDUCT NEW PERFORMANCE INDEX BASED ON THE EXECUTION TIME
// - SYSTEM'S PERFORMANCE MEANS; HOW FAST THE SYSTEM IS
// - ELAPSED TIME IS LOWER, THEN PERFORMANCE IS HIGHER
let elapsed_time: number = history.computeElapsedTime() / history.getWeight(); // CONSIDER WEIGHT
let new_performance: number = average_elapsed_time_of_others / elapsed_time; // NEW PERFORMANCE
// DEDUCT RATIO TO REFLECT THE NEW PERFORMANCE INDEX -> MAXIMUM: 30%
let ordinary_ratio: number;
if (system["history_list_"].size() < 2)
ordinary_ratio = .3;
else
ordinary_ratio = Math.min(0.7, 1.0 / (system["history_list_"].size() - 1.0));
// DEFINE NEW PERFORMANCE
system.setPerformance
(
(system.getPerformance() * ordinary_ratio)
+ (new_performance * (1 - ordinary_ratio))
);
}
}
/**
* @hidden
*/
protected _Normalize_performance(): void
{
// NORMALIZE SYSTEMS' PERFORMANCE INDEXES
super._Normalize_performance();
// COMPUTE AVERAGE
let average: number = 0.0;
let denominator: number = 0;
for (let it = this.process_map_.begin(); !it.equals(this.process_map_.end()); it = it.next())
{
let process: DistributedProcess = it.second;
if (process["enforced_"] == true)
continue; // THE RESOURCE INDEX IS ENFORCED. DO NOT PERMIT REVALUATION
average += process.getResource();
denominator++;
}
average /= denominator;
// DIVIDE FROM THE AVERAGE
for (let it = this.process_map_.begin(); !it.equals(this.process_map_.end()); it = it.next())
{
let process: DistributedProcess = it.second;
if (process["enforced_"] == true)
continue; // THE RESOURCE INDEX IS ENFORCED. DO NOT PERMIT REVALUATION
process.setResource(process.getResource() / average);
}
}
/* ---------------------------------------------------------
EXPORTERS
--------------------------------------------------------- */
/**
* @inheritdoc
*/
public toXML(): XML
{
let xml: XML = super.toXML();
if (this.process_map_.empty() == true)
return xml;
let processes_xml: XML = new XML();
{
processes_xml.setTag("processes");
for (let it = this.process_map_.begin(); !it.equals(this.process_map_.end()); it = it.next())
processes_xml.push(it.second.toXML());
}
xml.push(processes_xml);
return xml;
}
} | the_stack |
/// <reference path="../../metricsPlugin.ts"/>
/// <reference path="../../../includes.ts"/>
module HawkularMetrics {
export class DatasourceDetailController {
private static MILIS_IN_SECONDS = 1000;
private autoRefreshPromise: ng.IPromise<number>;
public datasource: any;
public datasourceId: any;
public skipChartData = {};
public startTimeStamp: TimestampInMillis;
public endTimeStamp: TimestampInMillis;
private feedId: FeedId;
public chartAvailData: any;
public resolvedAvailData: any;
public chartRespData: any;
public resolvedRespData: any;
public alertList: any;
constructor(private $q: ng.IQService,
private $rootScope: IHawkularRootScope,
private MetricsService: IMetricsService,
private HawkularNav: any,
private $routeParams: any,
private HawkularAlertRouterManager: IHawkularAlertRouterManager,
private HawkularInventory: any,
private $interval: ng.IIntervalService) {
this.feedId = this.$routeParams.feedId;
this.datasourceId = this.$routeParams.datasourceId;
this.$rootScope.$on('ChartTimeRangeChanged', (event, data: Date[]) => {
this.startTimeStamp = data[0].getTime();
this.endTimeStamp = data[1].getTime();
this.HawkularNav.setTimestampStartEnd(this.startTimeStamp, this.endTimeStamp);
this.refresh();
});
this.$rootScope.$on('$destroy', () => {
this.destroy();
});
if ($rootScope.currentPersona) {
this.getDatasource().then((data) => {
this.datasource = data;
this.registerAlerts();
this.refresh();
});
} else {
/// currentPersona hasn't been injected to the rootScope yet, wait for it..
$rootScope.$watch('currentPersona', (currentPersona) => currentPersona &&
this.getDatasource().then((data) => {
this.datasource = data;
this.registerAlerts();
this.refresh();
}));
}
this.autoRefresh(20);
}
private getDatasource(): ng.IPromise<any> {
const resourceId = this.$routeParams.resourceId + '~~';
return this.HawkularInventory.ResourceUnderFeed.get({
feedId: this.$routeParams.feedId,
resourcePath: resourceId + '/' + this.datasourceId.replace(/\$/g, '%2F'),
}).$promise;
}
public getDatasourceChartData(): void {
if (this.datasource) {
this.$q.all(this.getAvailableChartPromises()).then((response) => {
this.chartAvailData = response || [];
this.resolvedAvailData = true;
});
this.$q.all(this.getResponseChartPromises()).then((response) => {
this.chartRespData = response || [];
this.resolvedRespData = true;
});
}
}
/**
* Method for creating chart data from raw IChartDataPoint data.
* @returns {ng.IPromise<IMultipleChartData>[]} formatted Data for multi-line available chart.
*/
public getAvailableChartPromises(): ng.IPromise<IMultipleChartData>[] {
let availPromises: ng.IPromise<IMultipleChartData>[] = [];
if (!this.skipChartData[this.datasource.id + '_Available Count']) {
availPromises.push(this.getAvailablePromise()
.then((data) => {
return {
key: 'Available Count',
color: AppServerDatasourcesDetailsController.AVAILABLE_COLOR,
values: MetricsService.formatBucketedChartOutput(data)
};
})
);
}
if (!this.skipChartData[this.datasource.id + '_In Use Count']) {
availPromises.push(this.getInUsePromise()
.then((data) => {
return {
key: 'In Use',
color: AppServerDatasourcesDetailsController.IN_USE_COLOR,
values: MetricsService.formatBucketedChartOutput(data)
};
})
);
}
if (!this.skipChartData[this.datasource.id + '_Timed Out']) {
availPromises.push(this.getTimedOutPromise()
.then((data) => {
return {
key: 'Timed Out',
color: AppServerDatasourcesDetailsController.TIMED_OUT_COLOR,
values: MetricsService.formatBucketedChartOutput(data)
};
})
);
}
return availPromises;
}
/**
* Method for creating chart data from raw IChartDataPoint data.
* @returns {ng.IPromise<IMultipleChartData>[]} formatted Data for multi-line response chart.
*/
public getResponseChartPromises(): ng.IPromise<IMultipleChartData>[] {
let responsePromises: ng.IPromise<IMultipleChartData>[] = [];
if (!this.skipChartData[this.datasource.id + '_Average Get Time']) {
responsePromises.push(this.getAvgGetTimePromise()
.then((data) => {
return {
key: 'Wait Time (Avg.)',
color: AppServerDatasourcesDetailsController.WAIT_COLOR,
values: MetricsService.formatBucketedChartOutput(data)
};
})
);
}
if (!this.skipChartData[this.datasource.id + '_Average Creation Time']) {
responsePromises.push(this.getAvgCreateTimePromise()
.then((data) => {
return {
key: 'Creation Time (Avg.)',
color: AppServerDatasourcesDetailsController.CREATION_COLOR,
values: MetricsService.formatBucketedChartOutput(data)
};
})
);
}
return responsePromises;
}
/**
* Method for constructing promise with data for chart of Available count in Datasource pool.
* @returns {ng.IPromise<IChartDataPoint[]>} constructed promise with data point for available chart.
*/
public getAvailablePromise(): ng.IPromise<IChartDataPoint[]> {
return this.MetricsService.retrieveGaugeMetrics(
this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.datasource.id, 'Datasource Pool Metrics~Available Count'),
this.startTimeStamp,
this.endTimeStamp,
60);
}
/**
* Method for constructing promise with data for chart of Use Count in Datasource pool.
* @returns {ng.IPromise<IChartDataPoint[]>} constructed promise with data point for available chart.
*/
public getInUsePromise(): ng.IPromise<IChartDataPoint[]> {
return this.MetricsService.retrieveGaugeMetrics(
this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.datasource.id, 'Datasource Pool Metrics~In Use Count'),
this.startTimeStamp,
this.endTimeStamp,
60);
}
/**
* Method for constructing promise with data for chart of Timed Out in Datasource pool.
* @returns {ng.IPromise<IChartDataPoint[]>} constructed promise with data point for available chart
*/
public getTimedOutPromise(): ng.IPromise<IChartDataPoint[]> {
return this.MetricsService.retrieveGaugeMetrics(
this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M', this.feedId, this.datasource.id, 'Datasource Pool Metrics~Timed Out'),
this.startTimeStamp,
this.endTimeStamp,
60);
}
/**
* Method for constructing promise with data for chart of Average Get Time in Datasource pool.
* @returns {ng.IPromise<IChartDataPoint[]>} constructed promise with data point for response chart.
*/
public getAvgGetTimePromise(): ng.IPromise<IChartDataPoint[]> {
return this.MetricsService.retrieveGaugeMetrics(
this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M',
this.feedId,
this.datasource.id,
'Datasource Pool Metrics~Average Get Time'),
this.startTimeStamp,
this.endTimeStamp,
60);
}
/**
* Method for constructing promise with data for chart of Average Creation Time in Datasource pool.
* @returns {ng.IPromise<IChartDataPoint[]>} constructed promise with data point for response chart.
*/
public getAvgCreateTimePromise(): ng.IPromise<IChartDataPoint[]> {
return this.MetricsService.retrieveGaugeMetrics(this.$rootScope.currentPersona.id,
MetricsService.getMetricId('M',
this.feedId,
this.datasource.id,
'Datasource Pool Metrics~Average Creation Time'),
this.startTimeStamp,
this.endTimeStamp,
60);
}
public encodeResourceId(resourceId: ResourceId): string {
return Utility.encodeResourceId(resourceId);
}
public toggleChartData(name): void {
this.skipChartData[name] = !this.skipChartData[name];
this.getDatasourceChartData();
}
private autoRefresh(intervalInSeconds: number): void {
this.autoRefreshPromise = this.$interval(() => {
this.refresh();
}, intervalInSeconds * DatasourceDetailController.MILIS_IN_SECONDS);
}
public refresh() {
this.endTimeStamp = this.$routeParams.endTime || +moment();
this.startTimeStamp = this.endTimeStamp - (this.$routeParams.timeOffset || 3600000);
this.getDatasourceChartData();
this.getAlerts();
this.$rootScope.lastUpdateTimestamp = new Date();
}
public getAlerts() {
this.HawkularAlertRouterManager.getAlertsForResourceId(
this.feedId + '/' + this.datasource.id,
this.startTimeStamp,
this.endTimeStamp
).then((data) => {
this.alertList = data;
});
}
public registerAlerts() {
this.HawkularAlertRouterManager.registerForAlerts(
this.feedId + '/' + this.datasource.id,
'datasource',
_.bind(AppServerDatasourcesDetailsController.filterAlerts, this, _, this.datasource)
);
}
public changeTimeRange(data: Date[]): void {
this.startTimeStamp = data[0].getTime();
this.endTimeStamp = data[1].getTime();
this.HawkularNav.setTimestampStartEnd(this.startTimeStamp, this.endTimeStamp);
this.refresh();
}
public destroy() {
this.$interval.cancel(this.autoRefreshPromise);
}
}
_module.controller('DatasourceDetailController', DatasourceDetailController);
} | the_stack |
import * as util from './core/util';
import * as vec2 from './core/vector';
import Draggable from './mixin/Draggable';
import Eventful from './core/Eventful';
import * as eventTool from './core/event';
import {GestureMgr} from './core/GestureMgr';
import Displayable from './graphic/Displayable';
import {PainterBase} from './PainterBase';
import HandlerDomProxy, { HandlerProxyInterface } from './dom/HandlerProxy';
import { ZRRawEvent, ZRPinchEvent, ElementEventName, ElementEventNameWithOn, ZRRawTouchEvent } from './core/types';
import Storage from './Storage';
import Element, {ElementEvent} from './Element';
import CanvasPainter from './canvas/Painter';
/**
* [The interface between `Handler` and `HandlerProxy`]:
*
* The default `HandlerProxy` only support the common standard web environment
* (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
* But `HandlerProxy` can be replaced to support more non-standard environment
* (e.g., mini app), or to support more feature that the default `HandlerProxy`
* not provided (like echarts-gl did).
* So the interface between `Handler` and `HandlerProxy` should be stable. Do not
* make break changes util inevitable. The interface include the public methods
* of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
* drives `Handler`.
*/
/**
* [DRAG_OUTSIDE]:
*
* That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
* zrender area when dragging. That is important for the improvement of the user experience
* when dragging something near the boundary without being terminated unexpectedly.
*
* We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
* to resolve this issue. But some drawbacks of it is described in
* https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
*
* Instead, we referenced the specifications:
* https://www.w3.org/TR/touch-events/#the-touchmove-event
* https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
* where the the mousemove/touchmove can be continue to fire if the user began a drag
* operation and the pointer has left the boundary. (for the mouse event, browsers
* only do it on `document` and when the pointer has left the boundary of the browser.)
*
* So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
* state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
* to fire until release the pointer. That is implemented by listen to those event on
* `document`.
* If we implement some other `HandlerProxy` only for touch device, that would be easier.
* The touch event support this feature by default.
* The term "pointer capture" is from the spec:
* https://www.w3.org/TR/pointerevents2/#idl-def-element-setpointercapture-pointerid
*
* Note:
* There might be some cases that the mouse event can not be received on `document`.
* For example,
* (A) When `useCapture` is not supported and some user defined event listeners on the ancestor
* of zr dom throw Error.
* (B) When `useCapture` is not supported and some user defined event listeners on the ancestor of
* zr dom call `stopPropagation`.
* In these cases, the `mousemove` event might be keep triggering event when the mouse is released.
* We try to reduce the side-effect in those cases, that is, use `isOutsideBoundary` to prevent
* it from do anything (especially, `findHover`).
* (`useCapture` mean, `addEvnetListener(listener, {capture: true})`, althought it may not be
* suppported in some environments.)
*
* Note:
* If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
* prevent user-registered-handler from calling `stopPropagation` and `preventDefault`
* when the `event.target` is not a zrender dom element. Otherwise the user-registered-handler
* may be able to prevent other elements (that not relevant to zrender) in the web page from receiving
* dom events.
*/
const SILENT = 'silent';
function makeEventPacket(eveType: ElementEventName, targetInfo: {
target?: Element
topTarget?: Element
}, event: ZRRawEvent): ElementEvent {
return {
type: eveType,
event: event,
// target can only be an element that is not silent.
target: targetInfo.target,
// topTarget can be a silent element.
topTarget: targetInfo.topTarget,
cancelBubble: false,
offsetX: event.zrX,
offsetY: event.zrY,
gestureEvent: (event as ZRPinchEvent).gestureEvent,
pinchX: (event as ZRPinchEvent).pinchX,
pinchY: (event as ZRPinchEvent).pinchY,
pinchScale: (event as ZRPinchEvent).pinchScale,
wheelDelta: event.zrDelta,
zrByTouch: event.zrByTouch,
which: event.which,
stop: stopEvent
};
}
function stopEvent(this: ElementEvent) {
eventTool.stop(this.event);
}
class EmptyProxy extends Eventful {
handler: Handler = null
dispose() {}
setCursor() {}
}
class HoveredResult {
x: number
y: number
target: Displayable
topTarget: Displayable
constructor(x?: number, y?: number) {
this.x = x;
this.y = y;
}
}
const handlerNames = [
'click', 'dblclick', 'mousewheel', 'mouseout',
'mouseup', 'mousedown', 'mousemove', 'contextmenu'
];
type HandlerName = 'click' |'dblclick' |'mousewheel' |'mouseout' |
'mouseup' |'mousedown' |'mousemove' |'contextmenu';
// TODO draggable
class Handler extends Eventful {
storage: Storage
painter: PainterBase
painterRoot: HTMLElement
proxy: HandlerProxyInterface
private _hovered = new HoveredResult(0, 0)
private _gestureMgr: GestureMgr
private _draggingMgr: Draggable
_downEl: Element
_upEl: Element
_downPoint: [number, number]
constructor(
storage: Storage,
painter: PainterBase,
proxy: HandlerProxyInterface,
painterRoot: HTMLElement
) {
super();
this.storage = storage;
this.painter = painter;
this.painterRoot = painterRoot;
proxy = proxy || new EmptyProxy();
/**
* Proxy of event. can be Dom, WebGLSurface, etc.
*/
this.proxy = null;
this.setHandlerProxy(proxy);
this._draggingMgr = new Draggable(this);
}
setHandlerProxy(proxy: HandlerProxyInterface) {
if (this.proxy) {
this.proxy.dispose();
}
if (proxy) {
util.each(handlerNames, function (name) {
proxy.on && proxy.on(name, this[name as HandlerName], this);
}, this);
// Attach handler
proxy.handler = this;
}
this.proxy = proxy;
}
mousemove(event: ZRRawEvent) {
const x = event.zrX;
const y = event.zrY;
const isOutside = isOutsideBoundary(this, x, y);
let lastHovered = this._hovered;
let lastHoveredTarget = lastHovered.target;
// If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
// (like 'setOption' or 'dispatchAction') in event handlers, we should find
// lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
// See #6198.
if (lastHoveredTarget && !lastHoveredTarget.__zr) {
lastHovered = this.findHover(lastHovered.x, lastHovered.y);
lastHoveredTarget = lastHovered.target;
}
const hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
const hoveredTarget = hovered.target;
const proxy = this.proxy;
proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
// Mouse out on previous hovered element
if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
this.dispatchToElement(lastHovered, 'mouseout', event);
}
// Mouse moving on one element
this.dispatchToElement(hovered, 'mousemove', event);
// Mouse over on a new element
if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
this.dispatchToElement(hovered, 'mouseover', event);
}
}
mouseout(event: ZRRawEvent) {
const eventControl = event.zrEventControl;
if (eventControl !== 'only_globalout') {
this.dispatchToElement(this._hovered, 'mouseout', event);
}
if (eventControl !== 'no_globalout') {
// FIXME: if the pointer moving from the extra doms to realy "outside",
// the `globalout` should have been triggered. But currently not.
this.trigger('globalout', {type: 'globalout', event: event});
}
}
/**
* Resize
*/
resize() {
this._hovered = new HoveredResult(0, 0);
}
/**
* Dispatch event
*/
dispatch(eventName: HandlerName, eventArgs?: any) {
const handler = this[eventName];
handler && handler.call(this, eventArgs);
}
/**
* Dispose
*/
dispose() {
this.proxy.dispose();
this.storage = null;
this.proxy = null;
this.painter = null;
}
/**
* 设置默认的cursor style
* @param cursorStyle 例如 crosshair,默认为 'default'
*/
setCursorStyle(cursorStyle: string) {
const proxy = this.proxy;
proxy.setCursor && proxy.setCursor(cursorStyle);
}
/**
* 事件分发代理
*
* @private
* @param {Object} targetInfo {target, topTarget} 目标图形元素
* @param {string} eventName 事件名称
* @param {Object} event 事件对象
*/
dispatchToElement(targetInfo: {
target?: Element
topTarget?: Element
}, eventName: ElementEventName, event: ZRRawEvent) {
targetInfo = targetInfo || {};
let el = targetInfo.target as Element;
if (el && el.silent) {
return;
}
const eventKey = ('on' + eventName) as ElementEventNameWithOn;
const eventPacket = makeEventPacket(eventName, targetInfo, event);
while (el) {
el[eventKey]
&& (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
el.trigger(eventName, eventPacket);
// Bubble to the host if on the textContent.
// PENDING
el = el.__hostTarget ? el.__hostTarget : el.parent;
if (eventPacket.cancelBubble) {
break;
}
}
if (!eventPacket.cancelBubble) {
// 冒泡到顶级 zrender 对象
this.trigger(eventName, eventPacket);
// 分发事件到用户自定义层
// 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
if (this.painter && (this.painter as CanvasPainter).eachOtherLayer) {
(this.painter as CanvasPainter).eachOtherLayer(function (layer) {
if (typeof (layer[eventKey]) === 'function') {
layer[eventKey].call(layer, eventPacket);
}
if (layer.trigger) {
layer.trigger(eventName, eventPacket);
}
});
}
}
}
findHover(x: number, y: number, exclude?: Displayable): HoveredResult {
const list = this.storage.getDisplayList();
const out = new HoveredResult(x, y);
for (let i = list.length - 1; i >= 0; i--) {
let hoverCheckResult;
if (list[i] !== exclude
// getDisplayList may include ignored item in VML mode
&& !list[i].ignore
&& (hoverCheckResult = isHover(list[i], x, y))
) {
!out.topTarget && (out.topTarget = list[i]);
if (hoverCheckResult !== SILENT) {
out.target = list[i];
break;
}
}
}
return out;
}
processGesture(event: ZRRawEvent, stage?: 'start' | 'end' | 'change') {
if (!this._gestureMgr) {
this._gestureMgr = new GestureMgr();
}
const gestureMgr = this._gestureMgr;
stage === 'start' && gestureMgr.clear();
const gestureInfo = gestureMgr.recognize(
event as ZRRawTouchEvent,
this.findHover(event.zrX, event.zrY, null).target,
(this.proxy as HandlerDomProxy).dom
);
stage === 'end' && gestureMgr.clear();
// Do not do any preventDefault here. Upper application do that if necessary.
if (gestureInfo) {
const type = gestureInfo.type;
(event as ZRPinchEvent).gestureEvent = type;
let res = new HoveredResult();
res.target = gestureInfo.target;
this.dispatchToElement(res, type as ElementEventName, gestureInfo.event as ZRRawEvent);
}
}
click: (event: ZRRawEvent) => void
mousedown: (event: ZRRawEvent) => void
mouseup: (event: ZRRawEvent) => void
mousewheel: (event: ZRRawEvent) => void
dblclick: (event: ZRRawEvent) => void
contextmenu: (event: ZRRawEvent) => void
}
// Common handlers
util.each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name: HandlerName) {
Handler.prototype[name] = function (event) {
const x = event.zrX;
const y = event.zrY;
const isOutside = isOutsideBoundary(this, x, y);
let hovered;
let hoveredTarget;
if (name !== 'mouseup' || !isOutside) {
// Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
hovered = this.findHover(x, y);
hoveredTarget = hovered.target;
}
if (name === 'mousedown') {
this._downEl = hoveredTarget;
this._downPoint = [event.zrX, event.zrY];
// In case click triggered before mouseup
this._upEl = hoveredTarget;
}
else if (name === 'mouseup') {
this._upEl = hoveredTarget;
}
else if (name === 'click') {
if (this._downEl !== this._upEl
// Original click event is triggered on the whole canvas element,
// including the case that `mousedown` - `mousemove` - `mouseup`,
// which should be filtered, otherwise it will bring trouble to
// pan and zoom.
|| !this._downPoint
// Arbitrary value
|| vec2.dist(this._downPoint, [event.zrX, event.zrY]) > 4
) {
return;
}
this._downPoint = null;
}
this.dispatchToElement(hovered, name, event);
};
});
function isHover(displayable: Displayable, x: number, y: number) {
if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
let el: Element = displayable;
let isSilent;
let ignoreClip = false;
while (el) {
// Ignore clip on any ancestors.
if (el.ignoreClip) {
ignoreClip = true;
}
if (!ignoreClip) {
let clipPath = el.getClipPath();
// If clipped by ancestor.
// FIXME: If clipPath has neither stroke nor fill,
// el.clipPath.contain(x, y) will always return false.
if (clipPath && !clipPath.contain(x, y)) {
return false;
}
if (el.silent) {
isSilent = true;
}
}
// Consider when el is textContent, also need to be silent
// if any of its host el and its ancestors is silent.
const hostEl = el.__hostTarget;
el = hostEl ? hostEl : el.parent;
}
return isSilent ? SILENT : true;
}
return false;
}
/**
* See [DRAG_OUTSIDE].
*/
function isOutsideBoundary(handlerInstance: Handler, x: number, y: number) {
const painter = handlerInstance.painter;
return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
}
export default Handler; | the_stack |
import { ipcRenderer } from "electron";
import { join, extname } from "path";
import { pathExists, mkdir, writeJSON, readFile, writeFile, remove } from "fs-extra";
import { IPCResponses } from "../../../shared/ipc";
import * as React from "react";
import { ButtonGroup, Button, Classes, Menu, MenuItem, Popover, Divider, Position, ContextMenu, Tag, Intent } from "@blueprintjs/core";
import { Scene, Node } from "babylonjs";
import { IFile } from "../project/files";
import { Project } from "../project/project";
import { ProjectExporter } from "../project/project-exporter";
import { WorkSpace } from "../project/workspace";
import { Icon } from "../gui/icon";
import { Dialog } from "../gui/dialog";
import { Tools } from "../tools/tools";
import { undoRedo } from "../tools/undo-redo";
import { IPCTools } from "../tools/ipc";
import { Assets } from "../components/assets";
import { AbstractAssets, IAssetComponentItem } from "./abstract-assets";
export class GraphAssets extends AbstractAssets {
/**
* Defines the list of all avaiable meshes in the assets component.
*/
public static Graphs: IFile[] = [];
private static _GraphEditors: { id: number; path: string }[] = [];
/**
* Defines the size of assets to be drawn in the panel. Default is 100x100 pixels.
* @override
*/
protected size: number = 100;
/**
* Defines the type of the data transfer data when drag'n'dropping asset.
* @override
*/
public readonly dragAndDropType: string = "application/script-asset";
/**
* Registers the component.
*/
public static Register(): void {
Assets.addAssetComponent({
title: "Visual Scripts (Beta)",
identifier: "graphs",
ctor: GraphAssets,
});
}
/**
* Renders the component.
*/
public render(): React.ReactNode {
const node = super.render();
const add =
<Menu>
<MenuItem key="add-new-graph" text="New Graph..." onClick={() => this._addGraph()} />
</Menu>;
return (
<>
<div className={Classes.FILL} key="materials-toolbar" style={{ width: "100%", height: "25px", backgroundColor: "#333333", borderRadius: "10px", marginTop: "5px" }}>
<ButtonGroup>
<Button key="refresh-folder" icon="refresh" small={true} onClick={() => this.refresh()} />
<Divider />
<Popover content={add} position={Position.BOTTOM_LEFT}>
<Button icon={<Icon src="plus.svg" />} rightIcon="caret-down" small={true} text="Add"/>
</Popover>
</ButtonGroup>
</div>
{node}
</>
);
}
/**
* Refreshes the component.
* @override
*/
public async refresh(): Promise<void> {
for (const m of GraphAssets.Graphs) {
const existingItem = this.items.find((i) => i.key === m.path);
const item = {
...existingItem ?? {
id: m.name,
key: m.path,
base64: "../css/svg/grip-lines.svg",
},
extraData: {
scriptPath: join("src", "scenes", WorkSpace.GetProjectName(), "graphs", m.name.replace(".json", ".ts")),
},
style: {
backgroundColor: "#222222",
borderColor: "#2FA1D6",
borderStyle: "solid",
borderWidth: this._isGraphAttached(m.name.replace(".json", ".ts")) ? "2px" : "0px",
}
}
if (!existingItem) {
this.items.push(item);
} else {
const index = this.items.indexOf(existingItem);
this.items[index] = item;
}
this.updateAssetObservable.notifyObservers();
}
return super.refresh();
}
/**
* Called on the user double clicks an item.
* @param item the item being double clicked.
* @param img the double-clicked image element.
*/
public async onDoubleClick(item: IAssetComponentItem, img: HTMLImageElement): Promise<void> {
super.onDoubleClick(item, img);
const index = GraphAssets._GraphEditors.findIndex((m) => m.path === item.key);
const existingId = index !== -1 ? GraphAssets._GraphEditors[index].id : undefined;
const path = join("src", "scenes", WorkSpace.GetProjectName(), "graphs", item.id).replace(".json", ".ts");
const popupId = await this.editor.addWindowedPlugin("graph-editor", existingId, item.key, path);
if (!popupId) { return; }
if (index === -1) {
GraphAssets._GraphEditors.push({ id: popupId, path: item.key });
} else {
GraphAssets._GraphEditors[index].id = popupId;
}
let callback: (...args: any[]) => void;
ipcRenderer.on(IPCResponses.SendWindowMessage, callback = async (_, message) => {
if (message.id !== "graph-json") { return; }
if (message.data.path !== item.key) { return; }
if (message.data.closed) {
ipcRenderer.removeListener(IPCResponses.SendWindowMessage, callback);
}
if (message.data.json) {
try {
await writeJSON(item.key, message.data.json, {
encoding: "utf-8",
spaces: "\t",
});
IPCTools.SendWindowMessage(popupId, "graph-json");
} catch (e) {
IPCTools.SendWindowMessage(popupId, "graph-json", { error: true });
}
// Update preview
item.base64 = message.data.preview;
this.setState({ items: this.items });
await ProjectExporter.ExportGraphs(this.editor);
}
});
}
/**
* Called on the user right-clicks on an item.
* @param item the item being right-clicked.
* @param event the original mouse event.
*/
public onContextMenu(item: IAssetComponentItem, e: React.MouseEvent<HTMLImageElement, MouseEvent>): void {
super.onContextMenu(item, e);
ContextMenu.show(
<Menu className={Classes.DARK}>
<MenuItem text="Remove" icon={<Icon src="times.svg" />} onClick={() => this._handleRemoveGraph(item)} />
</Menu>,
{ left: e.clientX, top: e.clientY },
);
}
/**
* Called on the user pressed the delete key on the asset.
* @param item defines the item being deleted.
*/
public onDeleteAsset(item: IAssetComponentItem): void {
super.onDeleteAsset(item);
this._handleRemoveGraph(item);
}
/**
* Returns the content of the item's tooltip on the pointer is over the given item.
* @param item defines the reference to the item having the pointer over.
*/
protected getItemTooltipContent(item: IAssetComponentItem): JSX.Element {
return (
<>
<Tag fill={true} intent={Intent.PRIMARY}>{item.id}</Tag>
<Divider />
<Tag fill={true} intent={Intent.PRIMARY}>{item.key}</Tag>
<Divider />
<img
src={item.base64}
style={{
width: "512px",
height: "256px",
objectFit: "contain",
backgroundColor: "#222222",
left: "50%",
}}
></img>
</>
);
}
/**
* Called on an asset item has been drag'n'dropped on graph component.
* @param data defines the data of the asset component item being drag'n'dropped.
* @param nodes defines the array of nodes having the given item being drag'n'dropped.
*/
public onGraphDropAsset(data: IAssetComponentItem, nodes: (Scene | Node)[]): boolean {
super.onGraphDropAsset(data, nodes);
if (!data.extraData?.scriptPath) { return false; }
nodes.forEach((n) => {
n.metadata ??= { };
n.metadata.script ??= { };
n.metadata.script.name = data.extraData!.scriptPath as string;
});
return true;
}
/**
* Adds a new graph to the project.
*/
private async _addGraph(): Promise<void> {
const name = await Dialog.Show("New Graph Name..", "Please provide a name for the new graph to create");
const destFolder = join(Project.DirPath!, "graphs");
if (!(await pathExists(destFolder))) {
await mkdir(destFolder);
}
const fileame = `${name}.json`;
const dest = join(destFolder, fileame);
const skeleton = await readFile(join(Tools.GetAppPath(), `assets/graphs/default.json`), { encoding: "utf-8" });
await writeFile(dest, skeleton);
GraphAssets.Graphs.push({ name: fileame, path: dest });
this.refresh();
}
/**
* Called on the user wants to remove a mesh from the library.
*/
private async _handleRemoveGraph(item: IAssetComponentItem): Promise<void> {
const extension = extname(item.id);
const sourcePath = join(WorkSpace.DirPath!, "src/scenes/", WorkSpace.GetProjectName(), "graphs", item.id.replace(extension, ".ts"));
const scriptExists = await pathExists(sourcePath);
undoRedo.push({
common: () => this.refresh(),
redo: async () => {
const graphIndex = GraphAssets.Graphs.findIndex((m) => m.path === item.key);
if (graphIndex !== -1) { GraphAssets.Graphs.splice(graphIndex, 1); }
const itemIndex = this.items.indexOf(item);
if (itemIndex !== -1) { this.items.splice(itemIndex, 1); }
if (scriptExists) {
remove(sourcePath);
}
},
undo: async () => {
GraphAssets.Graphs.push({ name: item.id, path: item.key });
this.items.push(item);
if (scriptExists) {
await ProjectExporter.ExportGraphs(this.editor);
}
},
});
}
/**
* Returns wether or not the given graph asset item is attached to a node or not.
*/
private _isGraphAttached(name: string): boolean {
const nodes: (Node | Scene)[] = [
this.editor.scene!,
...this.editor.scene!.meshes,
...this.editor.scene!.cameras,
...this.editor.scene!.lights,
...this.editor.scene!.transformNodes,
];
const path = join("src", "scenes", WorkSpace.GetProjectName(), "graphs", name);
for (const n of nodes) {
if (n.metadata?.script?.name === path) {
return true;
}
}
return false;
}
} | the_stack |
import PouchDB from "pouchdb";
import PouchDBFind from "pouchdb-find";
PouchDB.plugin(PouchDBFind);
import AxiomObject from "./AxiomObject";
import Channel from "./Channel";
import KeyPair from "./KeyPair";
import Message from "./Message";
import Node from "./Node";
import Peer from "./Peer";
import SignedMessage from "./SignedMessage";
let CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
let NAME_REGEX = RegExp("^[a-zA-Z0-9]+$");
function randomName(): string {
let name = "";
for (let i = 0; i < 10; i++) {
name += CHARS[Math.floor(Math.random() * CHARS.length)];
}
return name;
}
interface Query {
selector: object;
}
type DatabaseCallback = (sm: SignedMessage) => void;
declare var process: any;
// A Database represents a set of data that is being synced by a node in the Axiom
// peer-to-peer network.
export default class Database {
// If this is set, new PouchDB databases will use this adapter.
static adapter: any = null;
channel: Channel;
name: string;
node: Node;
keyPair: KeyPair;
db: any;
filterer: (obj: AxiomObject) => boolean;
verbose: boolean;
callbacks: DatabaseCallback[];
// A cached outgoing Dataset message.
dataset: Message | null;
// A list of callbacks for when we are done with the initial load.
// Null if we already loaded.
onLoad: ((sms: SignedMessage[]) => void)[] | null;
constructor(name: string, channel: Channel, node?: Node, prefix?: string) {
this.name = name;
this.channel = channel;
prefix = prefix || "";
this.db = new PouchDB(prefix + name, {
auto_compaction: true,
adapter: Database.adapter
});
if (node) {
this.node = node;
this.keyPair = node.keyPair;
this.verbose = this.node.verbose;
} else {
this.keyPair = KeyPair.fromRandom();
this.verbose = false;
}
this.callbacks = [];
this.filterer = null;
this.onLoad = [];
this.dataset = null;
}
// Wraps database access, and exits on any error
// TODO: pipe through pouch types
async wrap<T>(p: Promise<T>): Promise<any> {
try {
return await p;
} catch (e) {
console.error("fatal database error:", e);
}
process && process.exit && process.exit(1);
throw new Error("cannot exit in the browser environment");
}
log(...args: any[]) {
this.node && this.node.log(...args);
}
// Sets a filter to be applied to new objects.
// A filter returns true for objects that are to be kept.
setFilter(filterer: (obj: AxiomObject) => boolean): void {
this.filterer = filterer;
}
// Applies a filter to objects already in the database.
// Returns when we are done filtering.
async applyFilter(filterer: (obj: AxiomObject) => boolean): Promise<void> {
let objects = await this.find({ selector: {} });
let forgettable = objects.filter(x => !filterer(x));
await Promise.all(forgettable.map(obj => obj.forget()));
}
// Applies a filter to both objects already in the database, and new objects.
async useFilter(filterer: (obj: AxiomObject) => boolean): Promise<void> {
this.setFilter(filterer);
await this.applyFilter(filterer);
}
async statusLine(): Promise<string> {
let info = await this.wrap(this.db.info());
return (
`${this.name} db has ${info.doc_count} docs. ` +
`seq = ${info.update_seq}`
);
}
async allSignedMessages(): Promise<SignedMessage[]> {
let docs = await this.wrap(this.findDocs({ selector: {} }, true));
let answer = [];
for (let doc of docs) {
try {
let sm = this.documentToSignedMessage(doc);
answer.push(sm);
} catch (e) {
// There's something invalid in the database.
console.error("invalid database document:", doc);
console.error(e);
}
}
return answer;
}
// You don't have to await this.
async onMessage(callback: DatabaseCallback) {
let sms = await this.allSignedMessages();
for (let sm of sms) {
callback(sm);
}
this.callbacks.push(callback);
}
// Create/Update/Delete ops
// If this message updates our database, it is forwarded on.
async handleDatabaseWrite(sm: SignedMessage, batch: boolean): Promise<void> {
if (!sm.message.timestamp) {
return;
}
if (this.filterer) {
try {
let obj = this.signedMessageToObject(sm);
if (!this.filterer(obj)) {
return;
}
} catch (e) {
// A malformed db write message
return;
}
}
let newDocument = this.signedMessageToDocument(sm);
let oldDocument = await this.getDocument(sm.signer, sm.message.name);
if (oldDocument) {
let oldMessage = this.documentToSignedMessage(oldDocument);
if (oldMessage && sm.message.timestamp <= oldMessage.message.timestamp) {
return;
}
newDocument._rev = oldDocument._rev;
}
try {
await this.db.put(newDocument);
} catch (e) {
if (e.status === 409) {
// Another write to this same object beat us to it.
// Just try again.
return await this.handleDatabaseWrite(sm, batch);
}
throw e;
}
this.dataset = null;
for (let callback of this.callbacks) {
callback(sm);
}
if (this.verbose && !batch) {
let info = await this.wrap(this.db.info());
let count = info.doc_count;
this.log(
`${this.name} write: ${sm.message.type}`,
`id=${newDocument._id} doc_count=${count}`
);
}
if (this.node) {
this.node.forwardToChannel(sm.message.channel, sm);
}
}
async handleDataset(peer: Peer, sm: SignedMessage): Promise<void> {
let messages = [];
for (let serialized of sm.message.messages) {
let nested;
try {
nested = SignedMessage.fromSerialized(serialized, true);
} catch (e) {
console.log("bad dataset:", e);
return;
}
if (
nested.message.channel != this.channel.name ||
nested.message.database != this.name
) {
console.log("inconsistent dataset");
return;
}
switch (nested.message.type) {
case "Create":
case "Update":
case "Delete":
messages.push(nested);
break;
default:
console.log("weird dataset message type:", nested.message.type);
return;
}
}
if (this.onLoad) {
this.log(`${this.name} db loaded from ${peer.peerPublicKey.slice(0, 6)}`);
let copy = this.onLoad;
this.onLoad = null;
for (let callback of copy) {
callback(messages);
}
}
for (let sm of messages) {
await this.handleDatabaseWrite(sm, true);
}
}
// TODO: handle malicious messages differently
async handleSignedMessage(peer: Peer, sm: SignedMessage): Promise<void> {
switch (sm.message.type) {
case "Create":
case "Update":
case "Delete":
return await this.handleDatabaseWrite(sm, false);
case "Query":
return await this.handleQuery(peer, sm.message);
case "Dataset":
let response = await this.handleDataset(peer, sm);
return response;
default:
throw new Error(
`Database cannot handleSignedMessage of type ${sm.message.type}`
);
}
}
// Convert a SignedMessage to a form storable in PouchDB.
// Of the top-level fields, most of them are the user-generated data.
// There is also _id, which is the object id, aka
// "owner:objectName".
// There is also metadata, which we reserve the right to add junk to in the future.
// TODO: Throw an error if the message is invalid
signedMessageToDocument(sm: SignedMessage): any {
if (sm.message.type !== "Delete" && !sm.message.data) {
throw new Error(
`cannot store ${sm.message.type} with missing data field`
);
}
if (!NAME_REGEX.test(sm.message.name)) {
throw new Error(`bad name: ${sm.message.name}`);
}
let doc = {
...sm.message.data,
_id: `${sm.signer}:${sm.message.name}`,
metadata: {
timestamp: sm.message.timestamp,
type: sm.message.type,
signature: sm.signature
}
};
// Check the signature verifies, so we don't get bad data stuck in our database
try {
this.documentToSignedMessage(doc);
} catch (e) {
throw new Error(`failure formatting SignedMessage for storage: ${e}`);
}
return doc;
}
// Convert a SignedMessage to an AxiomObject
signedMessageToObject(sm: SignedMessage): AxiomObject {
if (!sm.message.data) {
throw new Error("cannot create AxiomObject with missing data field");
}
if (this.name !== sm.message.database) {
throw new Error("database mismatch");
}
if (this.channel.name !== sm.message.channel) {
throw new Error("channel mismatch");
}
let metadata = {
database: this,
timestamp: new Date(sm.message.timestamp),
name: sm.message.name,
owner: sm.signer
};
return new AxiomObject(metadata, sm.message.data);
}
// Convert a PouchDB document to a SignedMessage
// Throws an error if the signature does not match
documentToSignedMessage(doc: any): SignedMessage {
let parts = doc._id.split(":");
if (parts.length != 2) {
throw new Error(`bad pouch _id: ${doc._id}`);
}
let [signer, name] = parts;
let messageContent: any = {
channel: this.channel.name,
database: this.name,
timestamp: doc.metadata.timestamp,
name
};
if (doc.metadata.type !== "Delete") {
messageContent.data = {};
for (let key in doc) {
if (!key.startsWith("_") && key !== "metadata") {
messageContent.data[key] = doc[key];
}
}
}
let message = new Message(doc.metadata.type, messageContent);
let sm = new SignedMessage({
message,
messageString: message.serialize(),
signer,
signature: doc.metadata.signature,
verified: false
});
sm.verify();
return sm;
}
// Convert a PouchDB document to an AxiomObject
documentToObject(doc: any): AxiomObject {
let parts = doc._id.split(":");
if (parts.length != 2) {
throw new Error(`bad pouch _id: ${doc._id}`);
}
let [owner, name] = parts;
let metadata = {
database: this,
timestamp: new Date(doc.metadata.timestamp),
name,
owner
};
if (doc.metadata.type == "Delete") {
throw new Error("cannot convert a Delete to an AxiomObject");
}
let data: any = {};
for (let key in doc) {
if (!key.startsWith("_") && key !== "metadata") {
data[key] = doc[key];
}
}
return new AxiomObject(metadata, data);
}
async handleNewPeer(peer: Peer): Promise<void> {
if (this.onLoad) {
// We ourselves are just loading. We should focus on loading data now, and only
// start sharing data later.
return;
}
let start = new Date();
let cached = true;
if (!this.dataset) {
cached = false;
let fakeQuery = new Message("Query", {
selector: {}
});
this.dataset = await this.responseForQuery(fakeQuery);
}
if (!this.dataset) {
return;
}
peer.sendMessage(this.dataset);
let elapsed = (new Date().getTime() - start.getTime()) / 1000;
this.log(
`sent${cached ? " cached" : ""}`,
this.name,
"dataset with",
this.dataset.messages.length,
"messages to",
peer.peerPublicKey.slice(0, 6),
`in ${elapsed.toFixed(3)}s`
);
}
async responseForQuery(m: Message): Promise<Message | null> {
let selector = m.selector || {};
let messages = [];
let docs = await this.findDocs({ selector }, false);
for (let doc of docs) {
try {
let sm = this.documentToSignedMessage(doc);
messages.push(sm.serialize());
} catch (e) {
// There's an invalid database message
}
}
if (messages.length === 0) {
return null;
}
return new Message("Dataset", {
channel: this.channel.name,
database: this.name,
messages
});
}
// If we have data, send back a Dataset containing a lot of other messages
async handleQuery(peer: Peer, m: Message): Promise<void> {
let response = await this.responseForQuery(m);
if (response) {
peer.sendMessage(response);
}
}
// Assigns a random name to the object if none is provided.
// Returns the newly-created AxiomObject.
async create(data: any, name?: string): Promise<AxiomObject> {
if (data.metadata) {
throw new Error("You can't have a field in data named metadata.");
}
let kp = await this.channel.getKeyPair();
if (!kp) {
throw new Error("You must register a keypair to create an object.");
}
name = name || randomName();
let message = new Message("Create", {
channel: this.channel.name,
database: this.name,
timestamp: new Date().toISOString(),
name,
data
});
let sm = SignedMessage.fromSigning(message, kp);
await this.handleDatabaseWrite(sm, false);
return this.signedMessageToObject(sm);
}
async update(name: string, data: any) {
if (data.metadata) {
throw new Error("You can't have a field in data named metadata.");
}
let kp = await this.channel.getKeyPair();
if (!kp) {
throw new Error("You must register a keypair to update an object.");
}
let message = new Message("Update", {
channel: this.channel.name,
database: this.name,
timestamp: new Date().toISOString(),
name: name,
data
});
let sm = SignedMessage.fromSigning(message, kp);
await this.handleDatabaseWrite(sm, false);
return this.signedMessageToObject(sm);
}
// Returns a pouch document, or null if there is none.
// Throws on unrecoverable errors.
async getDocument(owner: string, name: string): Promise<any> {
let objectKey = `${owner}:${name}`;
let oldDocument;
try {
oldDocument = await this.db.get(objectKey);
} catch (e) {
if (e.name !== "not_found") {
throw e;
}
}
return oldDocument || null;
}
// Removes an object from the local database, but doesn't try to delete it across the
// network.
// Future updates to this object will arrive in our database again, so this method alone
// won't prevent an object from arriving in our database.
async forget(owner: string, name: string) {
let doc = await this.getDocument(owner, name);
if (!doc) {
return;
}
let objectKey = `${owner}:${name}`;
await this.wrap(this.db.remove(objectKey, doc._rev));
}
// Forgets the entire contents of this database.
async clear(): Promise<void> {
let objects = await this.find({ selector: {} });
for (let obj of objects) {
await obj.forget();
}
}
async delete(name: string) {
let kp = await this.channel.getKeyPair();
if (!kp) {
throw new Error("You must register a keypair to delete an object.");
}
let message = new Message("Delete", {
channel: this.channel.name,
database: this.name,
timestamp: new Date().toISOString(),
name: name
});
let sm = SignedMessage.fromSigning(message, kp);
await this.handleDatabaseWrite(sm, false);
}
async createIndex(blob: any) {
await this.wrap(this.db.createIndex(blob));
}
// Returns a list of pouch documents
async findDocs(query: Query, includeDeleted: boolean): Promise<any[]> {
let start = new Date();
let response = await this.wrap(this.db.find(query));
let answer = [];
for (let doc of response.docs) {
if (!includeDeleted && doc.metadata.type === "Delete") {
continue;
}
answer.push(doc);
}
let ms = new Date().getTime() - start.getTime();
let s = ms / 1000;
if (s > 1) {
let q = JSON.stringify(query.selector);
this.log(`${this.name} handled query ${q} in ${s.toFixed(3)}s`);
}
return answer;
}
// Returns a list of AxiomObject
async find(query: Query): Promise<AxiomObject[]> {
let docs = await this.findDocs(query, false);
let answer = [];
for (let doc of docs) {
try {
let obj = this.documentToObject(doc);
answer.push(obj);
} catch (e) {
// There's an invalid database message
}
}
return answer;
}
// TODO: use this logic.
// This is currently unused.
// We used to call this in the constructor. However, at that point we haven't connected to
// the channel yet, so the query can't be sent.
load() {
this.log(`loading ${this.name} db`);
let message = new Message("Query", {
channel: this.channel.name,
database: this.name
});
if (this.node) {
this.node.sendToChannel(this.channel.name, message);
}
}
// TODO: ensure this doesn't return objects that don't match the query
async waitForLoad(query: Query): Promise<AxiomObject[]> {
if (!this.onLoad) {
return await this.find(query);
}
// Merge local objects with the first remote dataset
let p = this.find(query);
let sms: SignedMessage[] = await new Promise((resolve, reject) => {
this.onLoad.push(resolve);
});
let localObjects = await p;
let objects: { [id: string]: AxiomObject } = {};
for (let obj of localObjects) {
objects[obj.id] = obj;
}
for (let sm of sms) {
if (sm.message.type === "Delete") {
continue;
}
let obj = this.signedMessageToObject(sm);
if (this.filterer && !this.filterer(obj)) {
continue;
}
let existing = objects[obj.id];
if (existing && existing.timestamp.getTime() > obj.timestamp.getTime()) {
continue;
}
objects[obj.id] = obj;
}
return Object.values(objects);
}
} | the_stack |
import open from 'open';
import boxen from 'boxen';
import execa from 'execa';
import plural from 'pluralize';
import inquirer from 'inquirer';
import { resolve } from 'path';
import chalk, { Chalk } from 'chalk';
import { URLSearchParams, parse } from 'url';
import sleep from '../../util/sleep';
import formatDate from '../../util/format-date';
import link from '../../util/output/link';
import logo from '../../util/output/logo';
import getArgs from '../../util/get-args';
import Client from '../../util/client';
import { getPkgName } from '../../util/pkg-name';
import { Output } from '../../util/output';
import { Deployment, PaginationOptions } from '../../types';
interface DeploymentV6
extends Pick<
Deployment,
'url' | 'target' | 'projectId' | 'ownerId' | 'meta' | 'inspectorUrl'
> {
createdAt: number;
}
interface Deployments {
deployments: DeploymentV6[];
pagination: PaginationOptions;
}
const pkgName = getPkgName();
const help = () => {
console.log(`
${chalk.bold(`${logo} ${pkgName} bisect`)} [options]
${chalk.dim('Options:')}
-h, --help Output usage information
-d, --debug Debug mode [off]
-b, --bad Known bad URL
-g, --good Known good URL
-o, --open Automatically open each URL in the browser
-p, --path Subpath of the deployment URL to test
-r, --run Test script to run for each deployment
${chalk.dim('Examples:')}
${chalk.gray('–')} Bisect the current project interactively
${chalk.cyan(`$ ${pkgName} bisect`)}
${chalk.gray('–')} Bisect with a known bad deployment
${chalk.cyan(`$ ${pkgName} bisect --bad example-310pce9i0.vercel.app`)}
${chalk.gray('–')} Automated bisect with a run script
${chalk.cyan(`$ ${pkgName} bisect --run ./test.sh`)}
`);
};
export default async function main(client: Client): Promise<number> {
const { output } = client;
const argv = getArgs(client.argv.slice(2), {
'--bad': String,
'-b': '--bad',
'--good': String,
'-g': '--good',
'--open': Boolean,
'-o': '--open',
'--path': String,
'-p': '--path',
'--run': String,
'-r': '--run',
});
if (argv['--help']) {
help();
return 2;
}
let bad =
argv['--bad'] ||
(await prompt(output, `Specify a URL where the bug occurs:`));
let good =
argv['--good'] ||
(await prompt(output, `Specify a URL where the bug does not occur:`));
let subpath = argv['--path'] || '';
let run = argv['--run'] || '';
const openEnabled = argv['--open'] || false;
if (run) {
run = resolve(run);
}
if (!bad.startsWith('https://')) {
bad = `https://${bad}`;
}
let parsed = parse(bad);
if (!parsed.hostname) {
output.error('Invalid input: no hostname provided');
return 1;
}
bad = parsed.hostname;
if (typeof parsed.path === 'string' && parsed.path !== '/') {
if (subpath && subpath !== parsed.path) {
output.note(
`Ignoring subpath ${chalk.bold(
parsed.path
)} in favor of \`--path\` argument ${chalk.bold(subpath)}`
);
} else {
subpath = parsed.path;
}
}
const badDeploymentPromise = getDeployment(client, bad).catch(err => err);
if (!good.startsWith('https://')) {
good = `https://${good}`;
}
parsed = parse(good);
if (!parsed.hostname) {
output.error('Invalid input: no hostname provided');
return 1;
}
good = parsed.hostname;
if (
typeof parsed.path === 'string' &&
parsed.path !== '/' &&
subpath &&
subpath !== parsed.path
) {
output.note(
`Ignoring subpath ${chalk.bold(
parsed.path
)} which does not match ${chalk.bold(subpath)}`
);
}
const goodDeploymentPromise = getDeployment(client, good).catch(err => err);
if (!subpath) {
subpath = await prompt(
output,
`Specify the URL subpath where the bug occurs:`
);
}
output.spinner('Retrieving deployments…');
const [badDeployment, goodDeployment] = await Promise.all([
badDeploymentPromise,
goodDeploymentPromise,
]);
if (badDeployment) {
if (badDeployment instanceof Error) {
badDeployment.message += ` "${bad}"`;
output.prettyError(badDeployment);
return 1;
}
bad = badDeployment.url;
} else {
output.error(`Failed to retrieve ${chalk.bold('bad')} Deployment: ${bad}`);
return 1;
}
const { projectId } = badDeployment;
if (goodDeployment) {
if (goodDeployment instanceof Error) {
goodDeployment.message += ` "${good}"`;
output.prettyError(goodDeployment);
return 1;
}
good = goodDeployment.url;
} else {
output.error(
`Failed to retrieve ${chalk.bold('good')} Deployment: ${good}`
);
return 1;
}
if (projectId !== goodDeployment.projectId) {
output.error(`Good and Bad deployments must be from the same Project`);
return 1;
}
if (badDeployment.createdAt < goodDeployment.createdAt) {
output.error(`Good deployment must be older than the Bad deployment`);
return 1;
}
if (badDeployment.target !== goodDeployment.target) {
output.error(
`Bad deployment target "${
badDeployment.target || 'preview'
}" does not match good deployment target "${
goodDeployment.target || 'preview'
}"`
);
return 1;
}
// Fetch all the project's "READY" deployments with the pagination API
let deployments: DeploymentV6[] = [];
let next: number | undefined = badDeployment.createdAt + 1;
do {
const query = new URLSearchParams();
query.set('projectId', projectId);
if (badDeployment.target) {
query.set('target', badDeployment.target);
}
query.set('limit', '100');
query.set('state', 'READY');
if (next) {
query.set('until', String(next));
}
const res = await client.fetch<Deployments>(`/v6/deployments?${query}`, {
accountId: badDeployment.ownerId,
});
next = res.pagination.next;
let newDeployments = res.deployments;
// If we have the "good" deployment in this chunk, then we're done
for (let i = 0; i < newDeployments.length; i++) {
if (newDeployments[i].url === good) {
newDeployments = newDeployments.slice(0, i + 1);
next = undefined;
break;
}
}
deployments = deployments.concat(newDeployments);
if (next) {
// Small sleep to avoid rate limiting
await sleep(100);
}
} while (next);
if (!deployments.length) {
output.error(
'Cannot bisect because this project does not have any deployments'
);
return 1;
}
// The first deployment is the one that was marked
// as "bad", so that one does not need to be tested
let lastBad = deployments.shift()!;
while (deployments.length > 0) {
// Add a blank space before the next step
output.print('\n');
const middleIndex = Math.floor(deployments.length / 2);
const deployment = deployments[middleIndex];
const rem = plural('deployment', deployments.length, true);
const steps = Math.floor(Math.log2(deployments.length));
const pSteps = plural('step', steps, true);
output.log(
chalk.magenta(
`${chalk.bold(
'Bisecting:'
)} ${rem} left to test after this (roughly ${pSteps})`
),
chalk.magenta
);
const testUrl = `https://${deployment.url}${subpath}`;
output.log(`${chalk.bold('Deployment URL:')} ${link(testUrl)}`);
output.log(`${chalk.bold('Date:')} ${formatDate(deployment.createdAt)}`);
const commit = getCommit(deployment);
if (commit) {
const shortSha = commit.sha.substring(0, 7);
const firstLine = commit.message.split('\n')[0];
output.log(`${chalk.bold('Commit:')} [${shortSha}] ${firstLine}`);
}
let action: string;
if (run) {
const proc = await execa(run, [testUrl], {
stdio: 'inherit',
reject: false,
env: {
...process.env,
HOST: deployment.url,
URL: testUrl,
},
});
if (proc instanceof Error && typeof proc.exitCode !== 'number') {
// Script does not exist or is not executable, so exit
output.prettyError(proc);
return 1;
}
const { exitCode } = proc;
let color: Chalk;
if (exitCode === 0) {
color = chalk.green;
action = 'good';
} else if (exitCode === 125) {
action = 'skip';
color = chalk.grey;
} else {
action = 'bad';
color = chalk.red;
}
output.log(
`Run script returned exit code ${chalk.bold(String(exitCode))}: ${color(
action
)}`
);
} else {
if (openEnabled) {
await open(testUrl);
}
const answer = await inquirer.prompt({
type: 'expand',
name: 'action',
message: 'Select an action:',
choices: [
{ key: 'g', name: 'Good', value: 'good' },
{ key: 'b', name: 'Bad', value: 'bad' },
{ key: 's', name: 'Skip', value: 'skip' },
],
});
action = answer.action;
}
if (action === 'good') {
deployments = deployments.slice(0, middleIndex);
} else if (action === 'bad') {
lastBad = deployment;
deployments = deployments.slice(middleIndex + 1);
} else if (action === 'skip') {
deployments.splice(middleIndex, 1);
}
}
output.print('\n');
let result = [
chalk.bold(
`The first bad deployment is: ${link(`https://${lastBad.url}`)}`
),
'',
` ${chalk.bold('Date:')} ${formatDate(lastBad.createdAt)}`,
];
const commit = getCommit(lastBad);
if (commit) {
const shortSha = commit.sha.substring(0, 7);
const firstLine = commit.message.split('\n')[0];
result.push(` ${chalk.bold('Commit:')} [${shortSha}] ${firstLine}`);
}
result.push(`${chalk.bold('Inspect:')} ${link(lastBad.inspectorUrl)}`);
output.print(boxen(result.join('\n'), { padding: 1 }));
output.print('\n');
return 0;
}
function getDeployment(
client: Client,
hostname: string
): Promise<DeploymentV6> {
const query = new URLSearchParams();
query.set('url', hostname);
query.set('resolve', '1');
query.set('noState', '1');
return client.fetch<DeploymentV6>(`/v10/deployments/get?${query}`);
}
function getCommit(deployment: DeploymentV6) {
const sha =
deployment.meta?.githubCommitSha ||
deployment.meta?.gitlabCommitSha ||
deployment.meta?.bitbucketCommitSha;
if (!sha) return null;
const message =
deployment.meta?.githubCommitMessage ||
deployment.meta?.gitlabCommitMessage ||
deployment.meta?.bitbucketCommitMessage;
return { sha, message };
}
async function prompt(output: Output, message: string): Promise<string> {
// eslint-disable-next-line no-constant-condition
while (true) {
const { val } = await inquirer.prompt({
type: 'input',
name: 'val',
message,
});
if (val) {
return val;
} else {
output.error('A value must be specified');
}
}
} | the_stack |
const models = require('../../../../../db/mysqldb/index')
import moment from 'moment'
const { render, resClientJson } = require('../../../utils/resData')
const Op = require('sequelize').Op
const clientWhere = require('../../../utils/clientWhere')
import {
statusList,
modelAction,
modelName
} from '../../../utils/constant'
const { reviewSuccess, freeReview, pendingReview, reviewFail } = statusList
const { TimeNow, TimeDistance } = require('../../../utils/time')
class PersonalCenter {
/**
* 用户个人中心个人文章列表render
* @param {object} ctx 上下文对象
*/
static async userMyArticle(req: any, res: any, next: any) {
let uid = req.query.uid
let blog_id = req.query.blog_id || 'all'
let type = req.query.type || ''
let page = req.query.page || 1
let pageSize = Number(req.query.pageSize) || 10
let whereParams: any = {
uid,
status: {
[Op.or]: [reviewSuccess, freeReview, pendingReview, reviewFail] // 审核成功、免审核
}
}
try {
type && (whereParams.type = type)
blog_id !== 'all' && (whereParams.blog_ids = blog_id)
let { count, rows } = await models.article.findAndCountAll({
where: whereParams, // 为空,获取全部,也可以自己添加条件
offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目
limit: pageSize, // 每页限制返回的数据条数
order: [['create_timestamp', 'desc']]
})
/* for (let item in rows) { // 循环取用户 render 渲染必须用这种方法 与 ajax 有区别
rows[item].create_dt = await moment(rows[item].create_date)
.format('YYYY-MM-DD H:m:s')
rows[item].user = await models.user.findOne({
where: { uid: rows[item].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
} */
for (let i in rows) {
rows[i].setDataValue(
'create_dt',
await TimeDistance(rows[i].create_date)
)
let oneArticleBlog = await models.article_blog.findOne({
where: { blog_id: rows[i].blog_ids }
})
if (oneArticleBlog && ~[2, 4].indexOf(oneArticleBlog.status)) {
rows[i].setDataValue('article_blog', oneArticleBlog)
}
if (rows[i].tag_ids) {
rows[i].setDataValue(
'tag',
await models.article_tag.findAll({
where: {
tag_id: { [Op.or]: rows[i].tag_ids.split(',') }
}
})
)
}
rows[i].setDataValue(
'user',
await models.user.findOne({
where: { uid: rows[i].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
}
await resClientJson(res, {
state: 'success',
message: 'home',
data: {
count: count,
blog_id,
page,
pageSize,
list: rows
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 用户个人中心用户关注用户render
* @param {object} ctx 上下文对象
*/
static async getUserAttentionList(req: any, res: any, next: any) {
let uid = req.query.uid
let page = req.query.page || 1
let pageSize = Number(req.query.pageSize) || 10
let any = req.query.any || 'me'
let whereParmas = {}
try {
if (any === 'me') {
whereParmas = {
uid: uid,
type: modelName.user,
is_associate: true
}
} else {
whereParmas = {
associate_id: uid,
type: modelName.user,
is_associate: true
}
}
let { count, rows } = await models.attention.findAndCountAll({
where: whereParmas, // 为空,获取全部,也可以自己添加条件
offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目
limit: pageSize, // 每页限制返回的数据条数
order: [['create_timestamp', 'desc']]
})
for (let i in rows) {
rows[i].setDataValue(
'user',
await models.user.findOne({
where: { uid: any === 'me' ? rows[i].associate_id : rows[i].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
rows[i].setDataValue(
'userAttentionIds',
await models.attention.findAll({
where: {
associate_id: any === 'me' ? rows[i].associate_id : rows[i].uid,
type: modelName.user,
is_associate: true
}
})
)
}
await resClientJson(res, {
state: 'success',
message: '获取列表成功',
data: {
count,
page,
pageSize,
list: rows,
any
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
static async getDynamicListMe(req: any, res: any, next: any) {
const { uid } = req.query
let page = req.query.page || 1
let pageSize = Number(req.query.pageSize) || 10
let whereParams = {} // 查询参数
let orderParams = [['create_date', 'DESC']] // 排序参数
try {
// sort
// hottest 全部热门:
whereParams = {
uid,
status: {
[Op.or]: [reviewSuccess, freeReview, pendingReview, reviewFail] // 审核成功、免审核
}
}
let { count, rows } = await models.dynamic.findAndCountAll({
where: whereParams, // 为空,获取全部,也可以自己添加条件
offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目
limit: pageSize, // 每页限制返回的数据条数
order: orderParams
})
for (let i in rows) {
rows[i].setDataValue(
'create_dt',
await TimeDistance(rows[i].create_date)
)
rows[i].setDataValue(
'topic',
rows[i].topic_ids
? await models.dynamic_topic.findOne({
where: { topic_id: rows[i].topic_ids }
})
: ''
)
rows[i].setDataValue(
'thumbCount',
await models.thumb.count({
where: {
associate_id: rows[i].id,
is_associate: true,
type: modelName.dynamic
}
})
)
rows[i].setDataValue(
'user',
await models.user.findOne({
where: { uid: rows[i].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
rows[i].setDataValue(
'userAttentionIds',
await models.attention.findAll({
where: {
uid: rows[i].uid || '',
type: modelName.user,
is_associate: true
}
})
)
}
if (rows) {
resClientJson(res, {
state: 'success',
message: '数据返回成功',
data: {
count,
page,
pageSize,
list: rows
}
})
} else {
resClientJson(res, {
state: 'error',
message: '数据返回错误,请再次刷新尝试'
})
}
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 用户个人中心个人专栏列表
* @param {object} ctx 上下文对象
*/
static async userArticleBlogList(req: any, res: any, next: any) {
let uid = req.query.uid
let page = req.query.page || 1
let pageSize = Number(req.query.pageSize) || 10
let whereParams = {
uid
}
try {
let { count, rows } = await models.article_blog.findAndCountAll({
where: whereParams, // 为空,获取全部,也可以自己添加条件
offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目
limit: pageSize, // 每页限制返回的数据条数
order: [['update_date', 'desc']]
})
/* for (let item in rows) { // 循环取用户 render 渲染必须用这种方法 与 ajax 有区别
rows[item].create_dt = await moment(rows[item].create_date)
.format('YYYY-MM-DD H:m:s')
rows[item].user = await models.user.findOne({
where: { uid: rows[item].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
} */
for (let i in rows) {
rows[i].setDataValue(
'create_dt',
await TimeDistance(rows[i].create_date)
)
rows[i].setDataValue('update_dt', await TimeDistance(rows[i].update_dt))
rows[i].setDataValue(
'articleCount',
await models.article.count({
where: { blog_ids: rows[i].blog_id }
})
)
rows[i].setDataValue(
'likeCount',
await models.collect.count({
where: {
associate_id: rows[i].blog_id,
is_associate: true,
type: modelName.article_blog
}
})
)
if (rows[i].tag_ids) {
rows[i].setDataValue(
'tag',
await models.article_tag.findAll({
where: { tag_id: { [Op.or]: rows[i].tag_ids.split(',') } }
})
)
}
rows[i].setDataValue(
'user',
await models.user.findOne({
where: { uid: rows[i].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
rows[i].setDataValue(
'likeUserIds',
await models.collect.findAll({
where: {
associate_id: rows[i].blog_id,
is_associate: true,
type: modelName.article_blog
}
})
)
}
await resClientJson(res, {
state: 'success',
message: '获取用户个人专栏成功列表',
data: {
count: count,
page,
pageSize,
list: rows
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
/**
* 用户个人中心个人小书列表
* @param {object} ctx 上下文对象
*/
static async userBooksList(req: any, res: any, next: any) {
let uid = req.query.uid
let page = req.query.page || 1
let pageSize = Number(req.query.pageSize) || 10
let whereParams = {
uid,
status: {
[Op.or]: [reviewSuccess, freeReview, pendingReview, reviewFail] // 审核成功、免审核
}
}
try {
let { count, rows } = await models.books.findAndCountAll({
where: whereParams, // 为空,获取全部,也可以自己添加条件
offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目
limit: pageSize, // 每页限制返回的数据条数
order: [['update_date', 'desc']]
})
/* for (let item in rows) { // 循环取用户 render 渲染必须用这种方法 与 ajax 有区别
rows[item].create_dt = await moment(rows[item].create_date)
.format('YYYY-MM-DD H:m:s')
rows[item].user = await models.user.findOne({
where: { uid: rows[item].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
} */
for (let i in rows) {
rows[i].setDataValue(
'create_dt',
await TimeDistance(rows[i].create_date)
)
rows[i].setDataValue('update_dt', await TimeDistance(rows[i].update_dt))
rows[i].setDataValue(
'bookCount',
await models.book.count({
where: { books_id: rows[i].books_id }
})
)
if (rows[i].tag_ids) {
rows[i].setDataValue(
'tag',
await models.article_tag.findAll({
where: { tag_id: { [Op.or]: rows[i].tag_ids.split(',') } }
})
)
}
rows[i].setDataValue(
'user',
await models.user.findOne({
where: { uid: rows[i].uid },
attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction']
})
)
}
await resClientJson(res, {
state: 'success',
message: '获取用户个人小书列表',
data: {
count,
page,
pageSize,
list: rows
}
})
} catch (err) {
resClientJson(res, {
state: 'error',
message: '错误信息:' + err.message
})
return false
}
}
}
export default PersonalCenter | the_stack |
import {
DataRecord,
Data,
DataRecordScale,
DataField,
DataFieldScale,
} from './Data';
import { Plugin } from './Plugin';
import { CoordinateParams, CoordinateKind } from './Coordinate';
import { AxisParams } from './Axis';
import { LegendParams, LegendItem } from './Legend';
import { TooltipParams } from './Tooltip';
import { Guide } from './Guide';
import { AnimateChartParams } from './Animate';
import { Geometry, GeometryParams } from './Geometry';
import { Point } from './Point';
import { InteractionKind, InteractionParams } from './Interaction';
import { PieLabelParams } from './PieLabel';
import { ScrollBarParams } from './ScrollBar';
import { GestureParams } from './Gesture';
import { IntervalLabelParams } from './IntervalLabel';
import { LegendController } from './LegendController';
/**
* 图表参数。
*
* `id`、`el`、`context` 这三个属性必须设置一个。
*/
export interface ChartParams {
/**
* 指定对应 canvas 的 id。
*/
id?: string;
/**
* 如果未指定 id 时可以直接传入 canvas 对象。
*/
el?: HTMLElement;
/**
* 若 id、el 都未指定可以直接传入 canvas 的上下文。
*/
context?: CanvasRenderingContext2D;
/**
* 渲染引擎,默认: canvas
*/
renderer?: string,
/**
* 图表的宽度,如果 `<canvas>` 元素上设置了宽度,可以不传入。
*/
width?: number;
/**
* 图表的高度,如果 <canvas> 元素上设置了高度,可以不传入。
*/
height?: number;
/**
* 图表绘图区域和画布边框的间距,用于显示坐标轴文本、图例,默认为 auto,即自动计算。
*/
padding?: number | 'auto' | Array<number | 'auto'>;
/**
* 图表画布区域四边的预留边距,即我们会在 padding 的基础上,为四边再加上 appendPadding 的数值,默认为 15。
*/
appendPadding?: number | number[];
/**
* 屏幕画布的像素比,默认为 1。
*/
pixelRatio?: number;
/**
* 为 chart 实例注册插件。
*/
plugins?: Plugin | Plugin[];
/**
* 是否关闭 chart 的动画。
*/
animate?: boolean;
/**
* 用于多 Y 轴的情况下,统一 Y 轴的数值范围,默认为 false。
*/
syncY?: boolean;
}
export interface ChartInnerProps<TRecord extends DataRecord> {
/**
* 对应 canvas 的 id。
*/
id: string;
/**
* 当前的图表绘图区域和画布边框的间距。
*/
padding: Exclude<ChartParams['padding'], undefined>;
/**
* 原始数据。
*/
data: Data<TRecord>;
/**
* 图表宽度。
*/
width: Exclude<ChartParams['width'], undefined>;
/**
* 图表高度。
*/
height: Exclude<ChartParams['height'], undefined>;
/**
* 图表的屏幕像素比。
*/
pixelRatio: Exclude<ChartParams['pixelRatio'], undefined>;
/**
* 对应 canvas 的 dom 对象。
*/
el: Exclude<ChartParams['el'], undefined>;
/**
* 对应的 canvas 对象(G.Canvas)。
*
* @todo 细化类型
*/
canvas: any;
/**
* chart render 之后可获取,返回所有的 geoms 对象。
*
* @todo 细化类型
*/
geoms: any;
/**
* 坐标系对象。
*/
coord:
| {
/**
* 是否是直角坐标系,直角坐标系下为 true。
*/
isRect: true;
/**
* 判断是否是极坐标,极坐标下为 true。
*/
isPolar: false;
/**
* 坐标系的起始点,F2 图表的坐标系原点位于左下角。
*/
start: Point;
/**
* 坐标系右上角的画布坐标。
*/
end: Point;
/**
* 是否发生转置,true 表示发生了转置。
*/
transposed: boolean;
}
| {
/**
* 是否是直角坐标系,直角坐标系下为 true。
*/
isRect: false;
/**
* 判断是否是极坐标,极坐标下为 true。
*/
isPolar: true;
/**
* 极坐标的起始角度,弧度制。
*/
startAngle: number;
/**
* 极坐标的结束角度,弧度制。
*/
endAngle: number;
/**
* 绘制环图时,设置内部空心半径,相对值,0 至 1 范围。
*/
innerRadius: number;
/**
* 设置圆的半径,相对值,0 至 1 范围。
*/
radius: number;
/**
* 是否发生转置,true 表示发生了转置。
*/
transposed: boolean;
/**
* 极坐标的圆心所在的画布坐标。
*/
center: Point;
/**
* 极坐标的半径值。
*/
circleRadius: number;
};
/**
* 图示控制器。
*/
legendController: LegendController;
/**
* @todo 补全所有的内部属性后去除该项
*/
[key: string]: any;
}
/**
* 图表插件。
*/
export interface ChartPlugins {
/**
* 注册插件。
*/
register(plugin: Plugin | Plugin[]): void;
/**
* 注销插件。
*/
unregister(plugin: Plugin | Plugin[]): void;
/**
* 清除插件。
*/
clear(): void;
/**
* 获取注册的所有插件。
*/
getAll(): Plugin[];
}
/**
* 创建图表实例。
*/
export class Chart<TRecord extends DataRecord = DataRecord> {
/**
* 插件管理。
*/
static plugins: ChartPlugins;
constructor(params: ChartParams);
/**
* 获取 chart 内部的属性。
*
* @param prop 属性名
*/
get<TProp extends keyof ChartInnerProps<TRecord>>(
prop: TProp,
): ChartInnerProps<TRecord>[TProp];
/**
* 装载数据。
*
* @param data 数据
* @param recordScale 各个字段的度量配置
*/
source(data: Data<TRecord>, recordScale?: DataRecordScale<TRecord>): void;
/**
* 设置或更新多个字段的度量配置。
*
* @param recordScale 各个字段的度量配置
*/
scale(recordScale?: DataRecordScale<TRecord>): void;
/**
* 设置或更新单个字段的度量配置。
*
* @param field 要操作的字段名
* @param fieldScale 要应用的度量配置
*/
scale<TField extends DataField<TRecord>>(
field: TField,
fieldScale?: DataFieldScale<TRecord, TField>,
): void;
/**
* 选择并配置笛卡尔坐标系。
*
* @param params 笛卡尔坐标系的配置参数
*/
coord(params: CoordinateParams<'rect'>): this;
/**
* 选择并配置坐标系。
*
* @param kind 选定的坐标系
* @param params 选定坐标系的配置参数
*/
coord<TKind extends CoordinateKind>(
kind: TKind,
params?: CoordinateParams<TKind>,
): this;
/**
* 关闭或启用坐标轴。
*
* @param enable 是否启用
*/
axis(enable: boolean): this;
/**
* 关闭或启用特定字段的坐标轴。
*
* @param field 要操作的字段名
* @param enable 是否启用
*/
axis(field: DataField<TRecord>, enable: boolean): this;
/**
* 配置特定字段的坐标轴。
*
* @param field 要操作的字段名
* @param params 配置参数
*/
axis<TField extends DataField<TRecord>>(
field: TField,
params: AxisParams<TRecord, TField>,
): this;
/**
* 关闭或启用图例。
*
* @param enable 是否启用
*/
legend(enable: boolean): this;
/**
* 关闭或启用特定字段的图例。
*
* @param field 要操作的字段名
* @param enable 是否启用
*/
legend(field: DataField<TRecord>, enable: boolean): this;
/**
* 配置图例。
*
* @param params 配置参数
*/
legend(params: LegendParams): this;
/**
* 配置特定字段的图例。
*
* @param field 要操作的字段名
* @param params 配置参数
*/
legend(field: DataField<TRecord>, params: LegendParams): this;
/**
* 过滤数据,如果存在对应的图例,则过滤掉的字段置灰。
*
* @param field 要过滤的数据字段
* @param callback 回调函数,用于过滤满足条件的数据
*/
filter<TField extends DataField<TRecord>>(
field: TField,
callback: (value: TRecord[TField]) => boolean,
): void;
/**
* 关闭或启用 Tooltip。
*
* @param enable 是否启用
*/
tooltip(enable: boolean): this;
/**
* 配置 Tooltip。
*
* @param params 配置参数
*/
tooltip(params: TooltipParams<TRecord>): this;
/**
* 配置辅助元素。
*/
guide(): Guide;
/**
* 关闭或启用图表动画。
*
* @param enable 是否启用
*/
animate(enable: boolean): this;
/**
* 配置图表动画。
*
* @param params 配置参数
*/
animate(params: AnimateChartParams): this;
/**
* 创建 point(点)的几何标记对象并返回该对象。
*
* @param params 配置参数
*/
point(params?: GeometryParams): Geometry<'point', TRecord>;
/**
* 创建 line(线)的几何标记对象并返回该对象。
*
* @param params 配置参数
*/
line(params?: GeometryParams): Geometry<'line', TRecord>;
/**
* 创建 area(区域)的几何标记对象并返回该对象。
*
* @param params 配置参数
*/
area(params?: GeometryParams): Geometry<'area', TRecord>;
/**
* 创建 path(路径)的几何标记对象并返回该对象。
*
* @param params 配置参数
*/
path(params?: GeometryParams): Geometry<'path', TRecord>;
/**
* 创建 interval(柱)的几何标记对象并返回该对象。
*
* @param params 配置参数
*/
interval(params?: GeometryParams): Geometry<'interval', TRecord>;
/**
* 创建 polygon(多边形)的几何标记对象并返回该对象并返回该对象。
*
* @param params 配置参数
*/
polygon(params?: GeometryParams): Geometry<'polygon', TRecord>;
/**
* 创建 schema 的几何标记对象并返回该对象。
*
* @param params 配置参数
*/
schema(params?: GeometryParams): Geometry<'schema', TRecord>;
/**
* 渲染图表,在最后调用。
*/
render(): this;
/**
* 清除图表内容。
*/
clear(): this;
/**
* 重新绘制图表。当修改了 guide、geometry 的配置项时可以重新绘制图表。
*/
repaint(): this;
/**
* 改变数据,同时刷新图表。
*
* @param data 新数据
*/
changeData(data: Data<TRecord>): this;
/**
* 改变图表宽高。示例:
*
* ```javascript
* chart.changeSize(300) // 只改变宽度
* chart.changeSize(300, 500) // 宽度高度同时改变
* chart.changeSize(, 300) // 只改变高度
* ```
*
* @param width 宽度
* @param height 高度
*/
changeSize(width?: number, height?: number): this;
/**
* 销毁图表,`<canvas>` dom 元素不会销毁。
*/
destroy(): void;
/**
* 获取原始数据记录对应在画布上的坐标。
*
* @param record 原始数据记录
*/
getPosition(record: TRecord): Point;
/**
* 根据画布上的坐标获取对应的原始数据。
*
* @param point 坐标位置
*/
getRecord(point: Point): TRecord;
/**
* 根据画布上的坐标获取附近的数据集。
*
* @param point 坐标位置
*/
getSnapRecords(
point: Point,
): Array<{
/**
* 该 shape 对应的原始数据。
*/
_origin: TRecord;
/**
* 组成该 shape 的关键顶点,归一化数据。
*/
points: Point[];
/**
* Y 轴对应的原始数据。
*/
_originY: number;
/**
* 该 shape 的 x 轴画布坐标。
*/
x: number;
/**
* 该 shape 的 y 轴画布坐标。
*/
y: number;
/**
* shape 的索引。
*/
index: number;
}>;
/**
* 获取图例的 items,用于图例相关的操作。
*/
getLegendItems(): Partial<Record<DataField<TRecord>, LegendItem[]>>;
/**
* 获取图表 X 轴对应的度量。
*
* @todo 细化返回类型
*/
getXScale(): any;
/**
* 获取图表 Y 轴对应的度量,有可能会有多个 Y 轴。
*
* @todo 细化返回类型
*/
getYScales(): any[];
/**
* 在指定坐标显示 Tooltip。
*
* @param point 坐标位置
*/
showTooltip(point: Point): this;
/**
* 隐藏当前 Tooltip。
*/
hideTooltip(): this;
/**
* 配置内置的交互行为。
*
* @param kind 交互行为类型
* @param params 配置参数
*/
interaction<TKind extends InteractionKind>(
kind: TKind,
params?: InteractionParams<TKind, TRecord>,
): void;
/**
* 配置自定义的交互行为。
*
* @param kind 交互行为类型
* @param params 配置参数
*/
interaction<TParams>(kind: string, params?: TParams): void;
/**
* 配置饼图文本。
*
* @param params 配置参数
*/
pieLabel(params: PieLabelParams<TRecord>): void;
/**
* 配置进度条。
*
* @param params 配置参数
*/
scrollBar(params: ScrollBarParams): void;
/**
* 配置手势。
*
* @param params 配置参数
*/
pluginGesture(params: GestureParams): void;
/**
* @todo 文档未说明参数,漏斗图示例中有出现
*/
intervalLabel(params: IntervalLabelParams<TRecord>): void;
/**
* 是否为横屏展示
*
* @param {Boolean} landscape 是否为横屏
*/
landscape(landscape: boolean): void;
} | the_stack |
import * as React from 'react';
import { Checkbox, Popover } from 'antd';
import cx from 'classnames';
import { TLayoutVertex } from '@jaegertracing/plexus/lib/types';
import IoAndroidLocate from 'react-icons/lib/io/android-locate';
import MdVisibilityOff from 'react-icons/lib/md/visibility-off';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import calcPositioning from './calc-positioning';
import {
MAX_LENGTH,
MAX_LINKED_TRACES,
MIN_LENGTH,
OP_PADDING_TOP,
PARAM_NAME_LENGTH,
PROGRESS_BAR_STROKE_WIDTH,
RADIUS,
WORD_RX,
} from './constants';
import { setFocusIcon } from './node-icons';
import { trackSetFocus, trackViewTraces, trackVertexSetOperation } from '../../index.track';
import { getUrl } from '../../url';
import BreakableText from '../../../common/BreakableText';
import FilteredList from '../../../common/FilteredList';
import NewWindowIcon from '../../../common/NewWindowIcon';
import { getUrl as getSearchUrl } from '../../../SearchTracePage/url';
import padActions from '../../../../actions/path-agnostic-decorations';
import {
ECheckedStatus,
EDdgDensity,
EDirection,
EViewModifier,
TDdgVertex,
PathElem,
} from '../../../../model/ddg/types';
import extractDecorationFromState, {
TDecorationFromState,
} from '../../../../model/path-agnostic-decorations';
import { ReduxState } from '../../../../types/index';
import './index.css';
type TDispatchProps = {
getDecoration: (id: string, svc: string, op?: string) => void;
};
type TProps = TDispatchProps &
TDecorationFromState & {
focalNodeUrl: string | null;
focusPathsThroughVertex: (vertexKey: string) => void;
getGenerationVisibility: (vertexKey: string, direction: EDirection) => ECheckedStatus | null;
getVisiblePathElems: (vertexKey: string) => PathElem[] | undefined;
hideVertex: (vertexKey: string) => void;
isFocalNode: boolean;
isPositioned: boolean;
operation: string | string[] | null;
selectVertex: (selectedVertex: TDdgVertex) => void;
service: string;
setOperation: (operation: string) => void;
setViewModifier: (visIndices: number[], viewModifier: EViewModifier, isEnabled: boolean) => void;
updateGenerationVisibility: (vertexKey: string, direction: EDirection) => void;
vertex: TDdgVertex;
vertexKey: string;
};
type TState = {
childrenVisibility?: ECheckedStatus | null;
parentVisibility?: ECheckedStatus | null;
};
export function getNodeRenderer({
baseUrl,
density,
extraUrlArgs,
focusPathsThroughVertex,
getGenerationVisibility,
getVisiblePathElems,
hideVertex,
selectVertex,
setOperation,
setViewModifier,
updateGenerationVisibility,
}: {
baseUrl: string;
density: EDdgDensity;
extraUrlArgs?: { [key: string]: unknown };
focusPathsThroughVertex: (vertexKey: string) => void;
getGenerationVisibility: (vertexKey: string, direction: EDirection) => ECheckedStatus | null;
getVisiblePathElems: (vertexKey: string) => PathElem[] | undefined;
hideVertex: (vertexKey: string) => void;
selectVertex: (selectedVertex: TDdgVertex) => void;
setOperation: (operation: string) => void;
setViewModifier: (visIndices: number[], viewModifier: EViewModifier, isEnabled: boolean) => void;
updateGenerationVisibility: (vertexKey: string, direction: EDirection) => void;
}) {
return function renderNode(vertex: TDdgVertex, _: unknown, lv: TLayoutVertex<any> | null) {
const { isFocalNode, key, operation, service } = vertex;
return (
<DdgNodeContent
focalNodeUrl={isFocalNode ? null : getUrl({ density, operation, service, ...extraUrlArgs }, baseUrl)}
focusPathsThroughVertex={focusPathsThroughVertex}
getGenerationVisibility={getGenerationVisibility}
getVisiblePathElems={getVisiblePathElems}
hideVertex={hideVertex}
isFocalNode={isFocalNode}
isPositioned={Boolean(lv)}
operation={operation}
selectVertex={selectVertex}
setOperation={setOperation}
setViewModifier={setViewModifier}
service={service}
updateGenerationVisibility={updateGenerationVisibility}
vertex={vertex}
vertexKey={key}
/>
);
};
}
export function measureNode() {
const diameter = 2 * (RADIUS + 1);
return {
height: diameter,
width: diameter,
};
}
export class UnconnectedDdgNodeContent extends React.PureComponent<TProps, TState> {
state: TState = {};
hoveredIndices: Set<number> = new Set();
constructor(props: TProps) {
super(props);
this.getDecoration();
}
componentDidUpdate(prevProps: TProps) {
if (prevProps.decorationID !== this.props.decorationID) this.getDecoration();
}
componentWillUnmount() {
if (this.hoveredIndices.size) {
this.props.setViewModifier(Array.from(this.hoveredIndices), EViewModifier.Hovered, false);
this.hoveredIndices.clear();
}
}
private getDecoration() {
const { decorationID, getDecoration, operation, service } = this.props;
if (decorationID) {
getDecoration(decorationID, service, typeof operation === 'string' ? operation : undefined);
}
}
private focusPaths = () => {
const { focusPathsThroughVertex, vertexKey } = this.props;
focusPathsThroughVertex(vertexKey);
};
private handleClick = () => {
const { decorationValue, selectVertex, vertex } = this.props;
if (decorationValue) selectVertex(vertex);
};
private hideVertex = () => {
const { hideVertex, vertexKey } = this.props;
hideVertex(vertexKey);
};
private setOperation = (operation: string) => {
trackVertexSetOperation();
this.props.setOperation(operation);
};
private updateChildren = () => {
const { updateGenerationVisibility, vertexKey } = this.props;
updateGenerationVisibility(vertexKey, EDirection.Downstream);
};
private updateParents = () => {
const { updateGenerationVisibility, vertexKey } = this.props;
updateGenerationVisibility(vertexKey, EDirection.Upstream);
};
private viewTraces = () => {
trackViewTraces();
const { vertexKey, getVisiblePathElems } = this.props;
const elems = getVisiblePathElems(vertexKey);
if (elems) {
const urlIds: Set<string> = new Set();
let currLength = MIN_LENGTH;
// Because there is a limit on traceIDs, attempt to get some from each elem rather than all from one.
const allIDs = elems.map(({ memberOf }) => memberOf.traceIDs.slice());
while (allIDs.length) {
const ids = allIDs.shift();
if (ids && ids.length) {
const id = ids.pop();
if (id && !urlIds.has(id)) {
// Keep track of the length, then break if it is too long, to avoid opening a tab with a URL that
// the backend cannot process, even if there are more traceIDs
currLength += PARAM_NAME_LENGTH + id.length;
if (currLength > MAX_LENGTH) {
break;
}
urlIds.add(id);
if (urlIds.size >= MAX_LINKED_TRACES) {
break;
}
}
allIDs.push(ids);
}
}
window.open(getSearchUrl({ traceID: Array.from(urlIds) }), '_blank');
}
};
private onMouseUx = (event: React.MouseEvent<HTMLElement>) => {
const { getGenerationVisibility, getVisiblePathElems, setViewModifier, vertexKey } = this.props;
const hovered = event.type === 'mouseover';
const visIndices = hovered
? (getVisiblePathElems(vertexKey) || []).map(({ visibilityIdx }) => {
this.hoveredIndices.add(visibilityIdx);
return visibilityIdx;
})
: Array.from(this.hoveredIndices);
setViewModifier(visIndices, EViewModifier.Hovered, hovered);
if (hovered) {
this.setState({
childrenVisibility: getGenerationVisibility(vertexKey, EDirection.Downstream),
parentVisibility: getGenerationVisibility(vertexKey, EDirection.Upstream),
});
} else this.hoveredIndices.clear();
};
render() {
const { childrenVisibility, parentVisibility } = this.state;
const {
decorationProgressbar,
decorationValue,
focalNodeUrl,
isFocalNode,
isPositioned,
operation,
service,
} = this.props;
const { radius, svcWidth, opWidth, svcMarginTop } = calcPositioning(service, operation);
const trueRadius = decorationProgressbar ? RADIUS - PROGRESS_BAR_STROKE_WIDTH : RADIUS;
const scaleFactor = trueRadius / radius;
const transform = `translate(${RADIUS - radius}px, ${RADIUS - radius}px) scale(${scaleFactor})`;
return (
<div className="DdgNodeContent" onMouseOver={this.onMouseUx} onMouseOut={this.onMouseUx}>
{decorationProgressbar}
<div
className={cx('DdgNodeContent--core', {
'is-decorated': decorationValue,
'is-focalNode': isFocalNode,
'is-missingDecoration': typeof decorationValue === 'string',
'is-positioned': isPositioned,
})}
onClick={this.handleClick}
role="button"
style={{ width: `${radius * 2}px`, height: `${radius * 2}px`, transform }}
>
<div className="DdgNodeContent--labelWrapper">
<h4
className="DdgNodeContent--label"
style={{ marginTop: `${svcMarginTop}px`, width: `${svcWidth}px` }}
>
<BreakableText text={service} wordRegexp={WORD_RX} />
</h4>
{operation && (
<div
className="DdgNodeContent--label"
style={{ paddingTop: `${OP_PADDING_TOP}px`, width: `${opWidth}px` }}
>
{Array.isArray(operation) ? (
<Popover
content={<FilteredList options={operation} value={null} setValue={this.setOperation} />}
placement="bottom"
title="Select Operation to Filter Graph"
>
<span>{`${operation.length} Operations`}</span>
</Popover>
) : (
<BreakableText text={operation} wordRegexp={WORD_RX} />
)}
</div>
)}
</div>
</div>
<div className="DdgNodeContent--actionsWrapper">
{focalNodeUrl && (
<a href={focalNodeUrl} className="DdgNodeContent--actionsItem" onClick={trackSetFocus}>
<span className="DdgNodeContent--actionsItemIconWrapper">{setFocusIcon}</span>
<span className="DdgNodeContent--actionsItemText">Set focus</span>
</a>
)}
<a className="DdgNodeContent--actionsItem" onClick={this.viewTraces} role="button">
<span className="DdgNodeContent--actionsItemIconWrapper">
<NewWindowIcon />
</span>
<span className="DdgNodeContent--actionsItemText">View traces</span>
</a>
{!isFocalNode && (
<a className="DdgNodeContent--actionsItem" onClick={this.focusPaths} role="button">
<span className="DdgNodeContent--actionsItemIconWrapper">
<IoAndroidLocate />
</span>
<span className="DdgNodeContent--actionsItemText">Focus paths through this node</span>
</a>
)}
{!isFocalNode && (
<a className="DdgNodeContent--actionsItem" onClick={this.hideVertex} role="button">
<span className="DdgNodeContent--actionsItemIconWrapper">
<MdVisibilityOff />
</span>
<span className="DdgNodeContent--actionsItemText">Hide node</span>
</a>
)}
{parentVisibility && (
<a className="DdgNodeContent--actionsItem" onClick={this.updateParents} role="button">
<span className="DdgNodeContent--actionsItemIconWrapper">
<Checkbox
checked={parentVisibility === ECheckedStatus.Full}
indeterminate={parentVisibility === ECheckedStatus.Partial}
/>
</span>
<span className="DdgNodeContent--actionsItemText">View Parents</span>
</a>
)}
{childrenVisibility && (
<a className="DdgNodeContent--actionsItem" onClick={this.updateChildren} role="button">
<span className="DdgNodeContent--actionsItemIconWrapper">
<Checkbox
checked={childrenVisibility === ECheckedStatus.Full}
indeterminate={childrenVisibility === ECheckedStatus.Partial}
/>
</span>
<span className="DdgNodeContent--actionsItemText">View Children</span>
</a>
)}
</div>
</div>
);
}
}
export function mapDispatchToProps(dispatch: Dispatch<ReduxState>): TDispatchProps {
const { getDecoration } = bindActionCreators(padActions, dispatch);
return {
getDecoration,
};
}
const DdgNodeContent = connect(
extractDecorationFromState,
mapDispatchToProps
)(UnconnectedDdgNodeContent);
export default DdgNodeContent; | the_stack |
import { expect } from "chai";
import { SaxesOptions, SaxesParser } from "../build/dist/saxes";
import { test } from "./testutil";
const XML_1_0_DECLARATION = "<?xml version=\"1.0\"?>";
const XML_1_1_DECLARATION = "<?xml version=\"1.1\"?>";
const WELL_FORMED_1_0_NOT_1_1 = "<root>\u007F</root>";
const WELL_FORMED_1_1_NOT_1_0 = "<root></root>";
type UnforcedExpectation = { version?: "1.0" | "1.1"; expectError: boolean };
type ForcedExpectation = { version: "1.0" | "1.1"; expectError: boolean };
describe("xml declaration", () => {
test({
name: "empty declaration",
xml: "<?xml?><root/>",
expect: [
["error", "1:7: XML declaration must contain a version."],
[
"xmldecl",
{
encoding: undefined,
version: undefined,
standalone: undefined,
},
],
["opentagstart", { name: "root", attributes: {}, ns: {} }],
[
"opentag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
[
"closetag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
],
opt: {
xmlns: true,
},
});
test({
name: "version without equal",
xml: "<?xml version?><root/>",
expect: [
["error", "1:14: XML declaration is incomplete."],
[
"xmldecl",
{
encoding: undefined,
version: undefined,
standalone: undefined,
},
],
["opentagstart", { name: "root", attributes: {}, ns: {} }],
[
"opentag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
[
"closetag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
],
opt: {
xmlns: true,
},
});
test({
name: "version without value",
xml: "<?xml version=?><root/>",
expect: [
["error", "1:15: XML declaration is incomplete."],
[
"xmldecl",
{
encoding: undefined,
version: undefined,
standalone: undefined,
},
],
["opentagstart", { name: "root", attributes: {}, ns: {} }],
[
"opentag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
[
"closetag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
],
opt: {
xmlns: true,
},
});
test({
name: "unquoted value",
xml: "<?xml version=a?><root/>",
expect: [
["error", "1:15: value must be quoted."],
["error", "1:16: XML declaration is incomplete."],
[
"xmldecl",
{
encoding: undefined,
version: undefined,
standalone: undefined,
},
],
["opentagstart", { name: "root", attributes: {}, ns: {} }],
[
"opentag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
[
"closetag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
],
opt: {
xmlns: true,
},
});
test({
name: "unterminated value",
xml: "<?xml version=\"a?><root/>",
expect: [
["error", "1:17: XML declaration is incomplete."],
[
"xmldecl",
{
encoding: undefined,
version: undefined,
standalone: undefined,
},
],
["opentagstart", { name: "root", attributes: {}, ns: {} }],
[
"opentag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
[
"closetag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
],
opt: {
xmlns: true,
},
});
test({
name: "bad version",
xml: "<?xml version=\"a\"?><root/>",
expect: [
["error", "1:17: version number must match /^1\\.[0-9]+$/."],
[
"xmldecl",
{
encoding: undefined,
version: "a",
standalone: undefined,
},
],
["opentagstart", { name: "root", attributes: {}, ns: {} }],
[
"opentag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
[
"closetag",
{
name: "root",
prefix: "",
local: "root",
uri: "",
attributes: {},
ns: {},
isSelfClosing: true,
},
],
],
opt: {
xmlns: true,
},
});
it("well-formed", () => {
const parser = new SaxesParser();
let seen = false;
parser.on("opentagstart", () => {
expect(parser.xmlDecl).to.deep.equal({
version: "1.1",
encoding: "utf-8",
standalone: "yes",
});
seen = true;
});
parser.write(
"<?xml version=\"1.1\" encoding=\"utf-8\" standalone=\"yes\"?><root/>");
parser.close();
expect(seen).to.be.true;
});
function parse(source: string, options?: SaxesOptions): boolean {
const parser = new SaxesParser(options);
let error = false;
parser.on("error", () => {
error = true;
});
parser.write(source);
parser.close();
return error;
}
function makeDefaultXMLVersionTests(
groupName: string,
xmlDeclaration: string,
document: string,
expecteUnforcedResults: UnforcedExpectation[],
expectedForcedResults: ForcedExpectation[] = []): void {
describe(groupName, () => {
for (const { version, expectError } of expecteUnforcedResults) {
const errorLabel = expectError ? "errors" : "no errors";
const title = version === undefined ?
`and without defaultXMLVersion: ${errorLabel}` :
`and with defaultXMLVersion === ${version}: ${errorLabel}`;
it(title, () => {
expect(parse(
xmlDeclaration + document,
version === undefined ? undefined : { defaultXMLVersion: version }))
.to.equal(expectError);
});
}
if (xmlDeclaration !== "") {
for (const { version, expectError } of expectedForcedResults) {
const errorLabel = expectError ? "errors" : "no errors";
it(`and with forced xml version ${version}: ${errorLabel}`, () => {
expect(parse(xmlDeclaration + document, {
defaultXMLVersion: version,
forceXMLVersion: true,
})).to.equal(expectError);
});
}
}
});
}
describe("document well-formed for 1.0, not 1.1", () => {
makeDefaultXMLVersionTests("without XML declaration", "",
WELL_FORMED_1_0_NOT_1_1, [{
version: undefined,
expectError: false,
}, {
version: "1.0",
expectError: false,
}, {
version: "1.1",
expectError: true,
}]);
makeDefaultXMLVersionTests("with XML 1.0 declaration", XML_1_0_DECLARATION,
WELL_FORMED_1_0_NOT_1_1, [{
version: undefined,
expectError: false,
}, {
version: "1.0",
expectError: false,
}, {
version: "1.1",
// The XML declaration overrides
// defaultXMLVersion.
expectError: false,
}], [{
version: "1.0",
expectError: false,
}, {
version: "1.1",
expectError: true,
}]);
makeDefaultXMLVersionTests("with XML 1.1 declaration", XML_1_1_DECLARATION,
WELL_FORMED_1_0_NOT_1_1, [{
version: undefined,
// The XML declaration overrides
// defaultXMLVersion.
expectError: true,
}, {
version: "1.0",
// The XML declaration overrides
// defaultXMLVersion.
expectError: true,
}, {
version: "1.1",
expectError: true,
}], [{
version: "1.0",
expectError: false,
}, {
version: "1.1",
expectError: true,
}]);
});
describe("document well-formed for 1.1, not 1.0", () => {
makeDefaultXMLVersionTests("without XML declaration", "",
WELL_FORMED_1_1_NOT_1_0, [{
version: undefined,
expectError: true,
}, {
version: "1.0",
expectError: true,
}, {
version: "1.1",
expectError: false,
}]);
makeDefaultXMLVersionTests("with XML 1.0 declaration",
XML_1_0_DECLARATION,
WELL_FORMED_1_1_NOT_1_0, [{
version: undefined,
expectError: true,
}, {
version: "1.0",
expectError: true,
}, {
version: "1.1",
// The XML declaration overrides
// defaultXMLVersion.
expectError: true,
}], [{
version: "1.0",
expectError: true,
}, {
version: "1.1",
expectError: false,
}]);
makeDefaultXMLVersionTests("with XML 1.1 declaration",
XML_1_1_DECLARATION,
WELL_FORMED_1_1_NOT_1_0, [{
version: undefined,
// The XML declaration overrides
// defaultXMLVersion.
expectError: false,
}, {
version: "1.0",
// The XML declaration overrides
// defaultXMLVersion.
expectError: false,
}, {
version: "1.1",
expectError: false,
}], [{
version: "1.0",
expectError: true,
}, {
version: "1.1",
expectError: false,
}]);
});
}); | the_stack |
import React, {useCallback, useEffect, useState} from 'react';
import {Card, CardActions, CardContent, CardTitle, RadioGroup, ScrollingHOC, Spinner,} from '@eccenca/gui-elements';
import {Button, FieldItem, Notification, Spacing, TextField} from '@gui-elements/index';
import {
AffirmativeButton,
DismissiveButton,
Radio,
TextField as LegacyTextField,
} from '@gui-elements/legacy-replacements';
import _ from 'lodash';
import ExampleView from '../ExampleView';
import {ParentElement} from '../../../components/ParentElement';
import {
checkUriPatternValidity,
checkValuePathValidity,
createMappingAsync,
fetchUriPatternAutoCompletions,
fetchValuePathSuggestions, updateVocabularyCacheEntry,
useApiDetails
} from '../../../store';
import {convertToUri} from '../../../utils/convertToUri';
import ErrorView from '../../../components/ErrorView';
import AutoComplete from '../../../components/AutoComplete';
import {MAPPING_RULE_TYPE_ROOT, MAPPING_RULE_TYPE_URI, MESSAGES,} from '../../../utils/constants';
import EventEmitter from '../../../utils/EventEmitter';
import {trimValue} from '../../../utils/trimValue';
import {wasTouched} from '../../../utils/wasTouched';
import {newValueIsIRI} from '../../../utils/newValueIsIRI';
import TargetCardinality from "../../../components/TargetCardinality";
import MultiAutoComplete from "../../../components/MultiAutoComplete";
import AutoSuggestion from "../../../components/AutoSuggestion/AutoSuggestion";
import silkApi from "../../../../api/silkRestApi";
import {IUriPattern} from "../../../../api/types";
import {UriPatternSelectionModal} from "./UriPatternSelectionModal";
interface IProps {
id?: string
parentId?: string
scrollIntoView: ({topOffset: number}) => any
onAddNewRule: (callback: () => any) => any
scrollElementIntoView: () => any
ruleData: object
parent: any
}
// Extracts the pure URI string if it has the form "<...>"
const pureUri = (uri: string) => uri ? uri.replace(/^<|>$/g, "") : uri
/**
* Provides the editable form for object mappings.
*/
export const ObjectRuleForm = (props: IProps) => {
const [loading, setLoading] = useState(false)
const [changed, setChanged] = useState(false)
const create = !props.id
// get a deep copy of origin data for modification
const [modifiedValues, setModifiedValues] = useState<any>(_.cloneDeep(props.ruleData))
const [saveObjectError, setSaveObjectError] = useState<any>(undefined)
const [uriPatternIsValid, setUriPatternIsValid] = useState<boolean>(true)
const [objectPathValid, setObjectPathValid] = useState<boolean>(true)
// When creating a new rule only when this is enabled the URI pattern input will be shown
const [createCustomUriPatternForNewRule, setCreateCustomUriPatternForNewRule] = useState<boolean>(false)
const [uriPatternSuggestions, setUriPatternSuggestions] = useState<IUriPattern[]>([])
const [showUriPatternModal, setShowUriPatternModal] = useState<boolean>(false)
const [targetEntityTypeOptions] = useState<Map<string, any>>(new Map())
const {baseUrl, project, transformTask} = useApiDetails()
const { id, parentId, parent } = props;
const autoCompleteRuleId = id || parentId;
const distinctUriPatterns = Array.from(new Map(uriPatternSuggestions
.filter(p => p.value !== (modifiedValues as any).pattern)
.map(p => [p.value, p])).values())
useEffect(() => {
const { id, scrollIntoView } = props;
// set screen focus to this element
scrollIntoView({ topOffset: 75 });
if (!id) {
EventEmitter.emit(MESSAGES.RULE_VIEW.CHANGE, { id: 0 });
}
}, [])
const uriValue = (uri: string) => {
if(!uri) {
return uri
}
return uri.replaceAll(/(^<)|(>$)/g, "")
}
// Fetch labels for target entity types
useEffect(() => {
if(modifiedValues.targetEntityType && modifiedValues.targetEntityType.length > 0 && baseUrl !== undefined && project && transformTask) {
modifiedValues.targetEntityType.forEach((targetEntityType) => {
if(typeof targetEntityType === "string") {
const value = uriValue(targetEntityType)
if(value !== targetEntityType || value.includes(":")) {
fetchTargetEntityUriInfo(value, targetEntityType)
}
}
})
}
}, [id, parentId, !!modifiedValues.targetEntityType, baseUrl, project, transformTask])
const fetchTargetEntityUriInfo = async (uri: string, originalTargetEntityType: string) => {
const {data} = await silkApi.retrieveTargetVocabularyTypeOrPropertyInfo(baseUrl!!, project!!, transformTask!!, uri)
if(data?.genericInfo) {
const info = data?.genericInfo
const typeInfo = {value: info.uri, label: info.label ?? info.uri, description: info.description}
targetEntityTypeOptions?.set(info.uri, typeInfo)
targetEntityTypeOptions?.set(uri, typeInfo)
updateVocabularyCacheEntry(originalTargetEntityType, info.label, info.description)
setModifiedValues(old => ({
...old,
targetEntityType: old.targetEntityType.map(o => {
const value = typeof o === "string" ? uriValue(o) : uriValue(o.value)
if (targetEntityTypeOptions.has(value)) {
return targetEntityTypeOptions.get(value)
} else {
return o
}
})
}))
}
}
const targetClassUris = () => modifiedValues.targetEntityType.map(t => typeof t === "string" ? pureUri(t) : pureUri(t.value))
useEffect(() => {
if(modifiedValues.targetEntityType && modifiedValues.targetEntityType.length > 0 && baseUrl !== undefined && project) {
silkApi.uriPatternsByTypes(baseUrl, project, targetClassUris())
.then(result => {
setUriPatternSuggestions(result.data.results)
})
}
}, [modifiedValues.targetEntityType ? targetClassUris().join("") : "", baseUrl])
/**
* Saves the modified data
*/
const handleConfirm = (event) => {
event.stopPropagation();
event.persist();
const uriPattern = trimValue(modifiedValues.pattern)
setLoading(true)
createMappingAsync({
id: props.id,
parentId: props.parentId,
type: modifiedValues.type,
comment: modifiedValues.comment,
label: modifiedValues.label,
sourceProperty: trimValue(modifiedValues.sourceProperty),
targetProperty: trimValue(modifiedValues.targetProperty),
targetEntityType: modifiedValues.targetEntityType,
isAttribute: modifiedValues.isAttribute,
// Reset URI pattern if it was previously set and is now empty
pattern: modifiedValues.uriRule?.type === MAPPING_RULE_TYPE_URI && !uriPattern ? null : uriPattern,
entityConnection: modifiedValues.entityConnection === 'to',
}, true)
.subscribe(
() => {
if (props.onAddNewRule) {
props.onAddNewRule(() => {
handleClose(event);
});
} else {
handleClose(event);
}
},
err => {
setSaveObjectError(err.response.body)
setLoading(false)
}
);
}
/**
* Handle input changes from user
*/
const handleChangeValue = (name, value) => {
const { id, ruleData } = props;
const newModifiedValues = {
...modifiedValues,
[name]: value
};
const changed = create || wasTouched(ruleData, newModifiedValues);
if (id) {
if (changed) {
EventEmitter.emit(MESSAGES.RULE_VIEW.CHANGE, { id });
} else {
EventEmitter.emit(MESSAGES.RULE_VIEW.UNCHANGED, { id });
}
}
setChanged(changed)
setModifiedValues(newModifiedValues)
}
/**
* handle form close event
* @param event
*/
const handleClose = (event) => {
event.stopPropagation();
const { id = 0 } = props;
EventEmitter.emit(MESSAGES.RULE_VIEW.UNCHANGED, { id });
EventEmitter.emit(MESSAGES.RULE_VIEW.CLOSE, { id });
}
const checkUriPattern = async(uriPattern: string) => {
const validationResult = await checkUriPatternValidity(uriPattern)
if(validationResult?.valid !== undefined) {
setUriPatternIsValid(validationResult?.valid as boolean)
}
return validationResult
}
if (loading) {
return <Spinner />;
}
const allowConfirm =
modifiedValues.type === MAPPING_RULE_TYPE_ROOT || !_.isEmpty(modifiedValues.targetProperty) || modifiedValues.sourceProperty && !_.isEmpty(modifiedValues.sourceProperty.trim());
const errorMessage = saveObjectError && (
<ErrorView {...saveObjectError} />
);
const title = !id && <CardTitle>Add object mapping</CardTitle>;
let targetPropertyInput: JSX.Element | undefined = undefined
let targetCardinality: JSX.Element | undefined = undefined
let entityRelationInput: JSX.Element | undefined = undefined
let sourcePropertyInput: JSX.Element | undefined = undefined
targetCardinality = (
<TargetCardinality
className="ecc-silk-mapping__ruleseditor__isAttribute"
isAttribute={modifiedValues.isAttribute}
isObjectMapping={true}
onChange={(value) => handleChangeValue('isAttribute', value)}
/>
);
if (modifiedValues.type !== MAPPING_RULE_TYPE_ROOT) {
targetPropertyInput = (
<AutoComplete
placeholder="Target property"
className="ecc-silk-mapping__ruleseditor__targetProperty"
entity="targetProperty"
newOptionCreator={convertToUri}
isValidNewOption={newValueIsIRI}
creatable
ruleId={autoCompleteRuleId}
data-id="autocomplete_target_prop"
value={modifiedValues.targetProperty}
onChange={value => { handleChangeValue('targetProperty', value); }}
resetQueryToValue={true}
itemDisplayLabel={(item) => item.label ? `${item.label} <${item.value}>` : item.value}
/>
);
entityRelationInput = (
<FieldItem>
<RadioGroup
onChange={({ value }) => { handleChangeValue('entityConnection', value); }}
value={
!_.isEmpty(modifiedValues.entityConnection)
? modifiedValues.entityConnection
: 'from'
}
name=""
disabled={false}
data-id="entity_radio_group"
>
<Radio
value="from"
label={
<span>
Connect from{' '}
<ParentElement parent={parent} />
</span>
}
/>
<Radio
value="to"
label={
<span>
Connect to{' '}
<ParentElement parent={parent} />
</span>
}
/>
</RadioGroup>
</FieldItem>
);
const valuePath = modifiedValues.sourceProperty == null ? "" : typeof modifiedValues.sourceProperty === "string" ? modifiedValues.sourceProperty : modifiedValues.sourceProperty.value
sourcePropertyInput = (
<AutoSuggestion
id={"object-value-path-auto-suggestion"}
label="Value path"
initialValue={valuePath}
clearIconText={"Clear value path"}
validationErrorText={"The entered value path is invalid."}
onChange={value => {
handleChangeValue('sourceProperty', value);
}}
fetchSuggestions={(input, cursorPosition) => fetchValuePathSuggestions(parentId, input, cursorPosition)}
checkInput={checkValuePathValidity}
onInputChecked={setObjectPathValid}
/>
);
}
let patternInput: JSX.Element | undefined
// URI pattern
if (!id || modifiedValues.uriRuleType === 'uri') {
if (!modifiedValues.pattern && !createCustomUriPatternForNewRule && (!id || !(props.ruleData as any).pattern)) {
patternInput = <FieldItem labelAttributes={{text: "URI pattern"}}>
<TextField
data-test-id="object-rule-form-default-pattern"
disabled
value="Default pattern."
rightElement={<Button
data-test-id="object-rule-form-default-pattern-custom-pattern-btn"
onClick={() => setCreateCustomUriPatternForNewRule(true)}
>Create custom pattern</Button>}
/>
</FieldItem>
} else {
patternInput = <AutoSuggestion
id={"uri-pattern-auto-suggestion"}
label="URI pattern"
initialValue={modifiedValues.pattern}
clearIconText={"Clear URI pattern"}
validationErrorText={"The entered URI pattern is invalid."}
onChange={value => {
handleChangeValue('pattern', value);
}}
fetchSuggestions={(input, cursorPosition) =>
fetchUriPatternAutoCompletions(parentId ? parentId : "root", input, cursorPosition, modifiedValues.sourceProperty)}
checkInput={checkUriPattern}
rightElement={distinctUriPatterns.length > 0 ? <>
<Spacing vertical={true} size={"tiny"} />
<Button
data-test-id="object-rule-form-uri-pattern-selection-btn"
elevated={true}
tooltip={`Choose URI pattern from ${distinctUriPatterns.length} existing URI pattern/s.`}
onClick={() => setShowUriPatternModal(true)}
>Choose</Button>
</> : undefined}
/>
}
} else {
patternInput = (
<LegacyTextField
disabled
label="URI formula"
value="This URI cannot be edited in the edit form."
/>
);
}
let previewExamples: null | JSX.Element = null
if(!modifiedValues.pattern && (!modifiedValues.uriRule || modifiedValues.uriRule.type === MAPPING_RULE_TYPE_URI)) {
previewExamples =
<Notification data-test-id={"object-rule-form-preview-no-pattern"}>No preview shown for default URI pattern.</Notification>
} else if (!uriPatternIsValid || !objectPathValid) {
previewExamples =
<Notification warning={true} data-test-id={"object-rule-form-preview-invalid-input"}>URI pattern or value
path is invalid. No preview shown.</Notification>
} else if (modifiedValues.pattern || modifiedValues.uriRule) {
previewExamples = <ExampleView
id={parentId || 'root'}
rawRule={
// when not "pattern" then it is "uriRule"
modifiedValues.pattern ?
{
type: MAPPING_RULE_TYPE_URI,
pattern: modifiedValues.pattern,
}
: modifiedValues.uriRule
}
ruleType={
// when not "pattern" then it is "uriRule"
modifiedValues.pattern ? MAPPING_RULE_TYPE_URI : modifiedValues.uriRule.type
}
objectSourcePathContext={modifiedValues.sourceProperty}
/>
}
return (
<div className="ecc-silk-mapping__ruleseditor">
<Card shadow={!id ? 1 : 0}>
{title}
<CardContent>
{errorMessage}
{targetPropertyInput}
{entityRelationInput}
<MultiAutoComplete
placeholder="Target entity type"
className="ecc-silk-mapping__ruleseditor__targetEntityType"
entity="targetEntityType"
isValidNewOption={newValueIsIRI}
ruleId={autoCompleteRuleId}
value={modifiedValues.targetEntityType}
creatable
onChange={value => { handleChangeValue('targetEntityType', value); }}
/>
{targetCardinality}
{patternInput}
{showUriPatternModal && distinctUriPatterns.length > 0 && <UriPatternSelectionModal
onClose={() => setShowUriPatternModal(false)}
uriPatterns={distinctUriPatterns}
onSelect={uriPattern => handleChangeValue('pattern', uriPattern.value)}
/>}
{
<FieldItem data-test-id="object-rule-form-example-preview" labelAttributes={{text: "Examples of target data"}}>
{previewExamples}
</FieldItem>
}
{sourcePropertyInput}
<LegacyTextField
data-test-id={"object-rule-form-label-input"}
label="Label"
className="ecc-silk-mapping__ruleseditor__label"
value={modifiedValues.label}
onChange={({ value }) => { handleChangeValue('label', value); }}
/>
<LegacyTextField
multiline
label="Description"
className="ecc-silk-mapping__ruleseditor__comment"
value={modifiedValues.comment}
onChange={({ value }) => { handleChangeValue('comment', value); }}
/>
</CardContent>
<CardActions className="ecc-silk-mapping__ruleseditor__actionrow">
<AffirmativeButton
className="ecc-silk-mapping__ruleseditor__actionrow-save"
raised
onClick={handleConfirm}
disabled={!allowConfirm || !changed || !uriPatternIsValid && modifiedValues.pattern || !objectPathValid}
>
Save
</AffirmativeButton>
<DismissiveButton
className="ecc-silk-mapping__ruleseditor__actionrow-cancel"
raised
onClick={handleClose}
>
Cancel
</DismissiveButton>
</CardActions>
</Card>
</div>
);
}
export default ScrollingHOC(ObjectRuleForm); | the_stack |
import {RotatingSprite} from "app/rotating-sprite";
import {TweenLite} from "gsap";
import "howler";
import {
Dom,
PixiAppWrapper as Wrapper,
pixiAppWrapperEvent as WrapperEvent,
PixiAppWrapperOptions as WrapperOpts,
} from "pixi-app-wrapper";
import {Asset, AssetPriority, LoadAsset, PixiAssetsLoader, SoundAsset} from "pixi-assets-loader";
import {
AsciiFilter,
CRTFilter,
GlowFilter,
OldFilmFilter,
OutlineFilter,
ShockwaveFilter,
} from "pixi-filters";
import "pixi-particles";
import "pixi-spine";
/**
* Showcase for PixiAppWrapper class.
*/
export class SampleApp {
private app: Wrapper;
private screenBorder: PIXI.Graphics;
private fullScreenButton: PIXI.Container;
private fullScreenText: PIXI.extras.BitmapText;
private loadingText: PIXI.Text;
private explorer: RotatingSprite;
private filteredBunnies: PIXI.Container;
private layeredBunnies: PIXI.Container;
private particlesContainer: PIXI.particles.ParticleContainer;
private playMusicContainer: PIXI.Container;
private spineBoy: PIXI.spine.Spine;
private particlesEmitter: PIXI.particles.Emitter;
private sound: Howl;
private loader: PixiAssetsLoader;
private totalAssets: number;
private loadingProgress: number;
private assetsCount: { [key: number]: { total: number, progress: number } } = {};
private textStyle = new PIXI.TextStyle({
fontFamily: "Verdana",
fontSize: 24,
fill: "#FFFFFF",
wordWrap: true,
wordWrapWidth: 440,
});
private bitmapTextStyle: PIXI.extras.BitmapTextStyle = {font: "35px Desyrel", align: "center"};
constructor() {
const canvas = Dom.getElementOrCreateNew<HTMLCanvasElement>("app-canvas", "canvas", document.getElementById("app-root"));
// if no view is specified, it appends canvas to body
const appOptions: WrapperOpts = {
width: 1920,
height: 1080,
scale: "keep-aspect-ratio",
align: "middle",
resolution: window.devicePixelRatio,
roundPixels: true,
transparent: false,
backgroundColor: 0x000000,
view: canvas,
showFPS: true,
showMediaInfo: true,
changeOrientation: true,
};
this.app = new Wrapper(appOptions);
this.app.on(WrapperEvent.RESIZE_START, this.onResizeStart.bind(this));
this.app.on(WrapperEvent.RESIZE_END, this.onResizeEnd.bind(this));
this.createViews(); // Draw views that can be already drawn
const assets = [
{id: "desyrel", url: "assets/fonts/desyrel.xml", priority: AssetPriority.HIGHEST, type: "font"},
{id: "play", url: "assets/gfx/play.png", priority: AssetPriority.LOW, type: "texture"},
{id: "stop", url: "assets/gfx/stop.png", priority: AssetPriority.LOW, type: "texture"},
{id: "bunny", url: "assets/gfx/bunny.png", priority: AssetPriority.HIGH, type: "texture"},
{id: "spineboy", url: "assets/gfx/spineboy.json", priority: AssetPriority.HIGHEST, type: "animation"},
{id: "bubble", url: "assets/gfx/Bubbles99.png", priority: AssetPriority.NORMAL, type: "texture"},
{id: "sound1", url: "assets/sfx/sound1.mp3", priority: AssetPriority.LOW, autoplay: false, loop: false, mute: false, rate: 1, type: "sound"} as Asset,
{id: "atlas1", url: "assets/gfx/treasureHunter.json", priority: AssetPriority.LOWEST, type: "atlas"},
// 404 Assets to test loading errors
{id: "explorer", url: "assets/gfx/explorer.png", priority: AssetPriority.LOWEST, type: "texture"},
{id: "sound2", url: "assets/sfx/sound2.mp3", priority: AssetPriority.LOW, autoplay: false, loop: false, mute: false, rate: 1, type: "sound"} as Asset,
];
assets.forEach(asset => {
if (!this.assetsCount[asset.priority]) {
this.assetsCount[asset.priority] = {total: 1, progress: 0};
} else {
this.assetsCount[asset.priority].total++;
}
});
this.loadingProgress = 0;
this.totalAssets = assets.length;
this.loader = new PixiAssetsLoader();
this.loader.on(PixiAssetsLoader.PRIORITY_GROUP_LOADED, this.onAssetsLoaded.bind(this));
this.loader.on(PixiAssetsLoader.PRIORITY_GROUP_PROGRESS, this.onAssetsProgress.bind(this));
this.loader.on(PixiAssetsLoader.ASSET_ERROR, this.onAssetsError.bind(this));
this.loader.on(PixiAssetsLoader.ALL_ASSETS_LOADED, this.onAllAssetsLoaded.bind(this));
this.loader.addAssets(assets).load();
}
public drawSquare(x = 0, y = 0, s = 50, r = 10): void {
this.drawRoundedRectangle(x, y, s, s, r);
}
public drawRoundedRectangle(x = 0, y = 0, w = 50, h = 50, r = 10): void {
this.fullScreenButton = new PIXI.Container();
const button = new PIXI.Graphics();
button.lineStyle(2, 0xFF00FF, 1);
button.beginFill(0xFF00BB, 0.25);
button.drawRoundedRect(0, 0, w, h, r);
button.endFill();
button.interactive = true;
button.buttonMode = true;
button.on("pointerup", () => {
// pointerdown does not trigger a user event in chrome-android
Wrapper.toggleFulscreen(document.getElementById("app-root"));
});
this.fullScreenButton.addChild(button);
this.fullScreenButton.position.set(x, y);
this.app.stage.addChild(this.fullScreenButton);
}
private onAssetsLoaded(args: { priority: number, assets: LoadAsset[] }): void {
window.console.log(`[SAMPLE APP] onAssetsLoaded ${args.assets.map(loadAsset => loadAsset.asset.id)}`);
args.assets.forEach(loadAsset => {
if (loadAsset.asset.id === "sound1" && loadAsset.loaded) {
this.sound = (loadAsset.asset as SoundAsset).howl!;
}
});
this.createViewsByPriority(args.priority);
}
private onAssetsProgress(args: { priority: number, progress: number }): void {
window.console.log(`[SAMPLE APP] onAssetsProgress ${JSON.stringify(args)}`);
const percentFactor = this.assetsCount[args.priority].total / this.totalAssets;
this.loadingProgress += (args.progress - this.assetsCount[args.priority].progress) * percentFactor;
this.assetsCount[args.priority].progress = args.progress;
this.loadingText.text = `Loading... ${this.loadingProgress}%`;
}
private onAssetsError(args: LoadAsset): void {
window.console.log(`[SAMPLE APP] onAssetsError ${args.asset.id}: ${args.error!.message}`);
}
private onAllAssetsLoaded(): void {
window.console.log("[SAMPLE APP] onAllAssetsLoaded !!!!");
}
private drawScreenBorder(width = 4): void {
const halfWidth = width / 2;
this.screenBorder = new PIXI.Graphics();
this.screenBorder.lineStyle(width, 0xFF00FF, 1);
this.screenBorder.drawRect(halfWidth, halfWidth, this.app.initialWidth - width, this.app.initialHeight - width);
this.app.stage.addChild(this.screenBorder);
}
private onResizeStart(): void {
window.console.log("RESIZE STARTED!");
}
private onResizeEnd(args: any): void {
window.console.log("RESIZE ENDED!", args);
if (args.stage.orientation.changed) {
this.relocateViews();
}
}
private stopEmittingParticles(): void {
if (this.particlesEmitter) {
this.particlesEmitter.emit = false;
this.particlesEmitter.cleanup();
}
}
private startEmittingParticles(): void {
if (this.particlesEmitter) {
this.particlesEmitter.emit = true;
}
}
private addFullscreenText(x: number, y: number): void {
this.fullScreenText = new PIXI.extras.BitmapText("Click on the square\n to toggle fullscreen!", this.bitmapTextStyle);
this.fullScreenText.position.set(x - this.fullScreenText.width / 2, y);
this.app.stage.addChild(this.fullScreenText);
}
private drawLoadingText(x: number, y: number): void {
this.loadingText = new PIXI.Text("Loading... 0%", this.textStyle);
this.loadingText.position.set(x, y);
this.app.stage.addChild(this.loadingText);
}
private createViews(): void {
this.drawSquare(this.app.initialWidth / 2 - 25, this.app.initialHeight / 2 - 25);
this.drawScreenBorder();
this.drawLoadingText(this.app.initialWidth / 5, 10);
}
private createViewsByPriority(priority: number): void {
switch (priority) {
case AssetPriority.HIGHEST:
this.addFullscreenText(this.app.initialWidth / 2, this.app.initialHeight / 2 - 125);
this.drawSpineBoyAnim();
break;
case AssetPriority.HIGH:
this.drawBunnies();
this.drawLayeredBunnies();
break;
case AssetPriority.NORMAL:
this.drawParticles();
break;
case AssetPriority.LOW:
this.drawPlayMusic();
break;
case AssetPriority.LOWEST:
this.drawRotatingExplorer();
break;
default:
break;
}
}
private removeViews(): void {
this.app.stage.removeChildren();
}
private drawRotatingExplorer(): void {
// This creates a texture from a "explorer.png" within the atlas
this.explorer = new RotatingSprite(PIXI.loader.resources.atlas1.textures!["explorer.png"]);
this.explorer.scale.set(2, 2);
// Setup the position of the explorer
const maxEdge = Math.max(this.explorer.width, this.explorer.height);
this.explorer.position.set(Math.ceil(maxEdge / 2) + 10, Math.ceil(maxEdge / 2) + 10);
// Rotate around the center
this.explorer.anchor.set(0.5, 0.5);
this.explorer.interactive = true;
this.explorer.buttonMode = true;
this.explorer.rotationVelocity = 0.02;
this.explorer.on("pointerdown", () => {
this.explorer.rotationVelocity *= -1;
});
// Add the explorer to the scene we are building
this.app.stage.addChild(this.explorer);
// Listen for frame updates
this.app.ticker.add(() => {
// each frame we spin the explorer around a bit
this.explorer.rotation += this.explorer.rotationVelocity;
});
TweenLite.to(this.explorer, 2, {y: this.app.initialHeight / 2});
}
private drawBunnies(): void {
this.filteredBunnies = new PIXI.Container();
this.app.stage.addChild(this.filteredBunnies);
const text = new PIXI.Text("Click us!", this.textStyle);
text.anchor.set(0.5, 0.5);
this.filteredBunnies.addChild(text);
const bunniesContainer = new PIXI.Container();
bunniesContainer.position.set(0, text.height + 5);
bunniesContainer.interactive = true;
bunniesContainer.buttonMode = true;
bunniesContainer.on("pointerdown", () => {
const index = Math.round(Math.random() * (filters.length - 1));
const randomFilter = filters[index];
bunniesContainer.filters = [randomFilter];
});
this.filteredBunnies.addChild(bunniesContainer);
// Create a 5x5 grid of bunnies
for (let i = 0; i < 25; i++) {
const bunny = new PIXI.Sprite(PIXI.loader.resources.bunny.texture);
bunny.x = (i % 5) * 40;
bunny.y = Math.floor(i / 5) * 40;
bunniesContainer.addChild(bunny);
}
text.position.set(bunniesContainer.width / 2, 0);
bunniesContainer.hitArea = new PIXI.Rectangle(0, 0, bunniesContainer.width, bunniesContainer.height);
this.filteredBunnies.x = this.app.initialWidth - this.filteredBunnies.width - 10;
this.filteredBunnies.y = this.app.initialHeight - this.filteredBunnies.height;
// Filters
const filters = [
new AsciiFilter(),
new CRTFilter(),
new GlowFilter(),
new OldFilmFilter(),
new ShockwaveFilter(new PIXI.Point(bunniesContainer.width / 2, bunniesContainer.height / 2)),
new OutlineFilter(1, 0xFF0000),
];
}
private drawLayeredBunnies(): void {
const layer = new PIXI.display.Layer();
layer.group.enableSort = true;
this.app.stage.addChild(layer);
this.layeredBunnies = new PIXI.Container();
this.app.stage.addChild(this.layeredBunnies);
this.layeredBunnies.parentLayer = layer;
// Create a 5x5 grid of bunnies
for (let i = 0; i < 25; i++) {
const bunny = new PIXI.Sprite(PIXI.loader.resources.bunny.texture);
bunny.x = (i % 5) * 20;
bunny.y = Math.floor(i / 5) * 20;
this.layeredBunnies.addChild(bunny);
bunny.parentLayer = layer;
if (i % 2 === 0) {
bunny.tint = 0x999999;
bunny.zIndex = 0;
// bunny.zOrder = 1;
} else {
bunny.zIndex = 1;
// bunny.zOrder = 0;
}
}
this.layeredBunnies.x = (this.app.initialWidth - this.layeredBunnies.width) - 10;
this.layeredBunnies.y = 10;
}
private drawParticles(): void {
this.particlesContainer = new PIXI.particles.ParticleContainer();
this.particlesContainer.position.set(this.app.initialWidth * 0.75, this.app.initialHeight * 0.5);
this.app.stage.addChild(this.particlesContainer);
this.particlesEmitter = new PIXI.particles.Emitter(this.particlesContainer, PIXI.loader.resources.bubble.texture, {
alpha: {
start: 0.8,
end: 0.1,
},
scale: {
start: 1,
end: 0.3,
},
color: {
start: "ffffff",
end: "0000ff",
},
speed: {
start: 200,
end: 100,
},
startRotation: {
min: 0,
max: 360,
},
rotationSpeed: {
min: 0,
max: 0,
},
lifetime: {
min: 0.5,
max: 2,
},
frequency: 0.1,
emitterLifetime: -1,
maxParticles: 1000,
pos: {
x: 0,
y: 0,
},
addAtBack: false,
spawnType: "circle",
spawnCircle: {
x: 0,
y: 0,
r: 10,
},
emit: false,
autoUpdate: true,
});
// Calculate the current time
let elapsed = Date.now();
// Update function every frame
const update = () => {
// Update the next frame
// requestAnimationFrame(update);
const now = Date.now();
// The emitter requires the elapsed
// number of seconds since the last update
this.particlesEmitter.update((now - elapsed) * 0.001);
elapsed = now;
};
// Start emitting
this.startEmittingParticles();
// Start the update
// update();
this.app.ticker.add(update);
}
private drawSpineBoyAnim(): void {
// create a spine boy
this.spineBoy = new PIXI.spine.Spine(PIXI.loader.resources.spineboy.spineData);
this.spineBoy.scale.set(0.5);
// set the position
this.spineBoy.x = this.app.initialWidth * 0.5;
this.spineBoy.y = this.app.initialHeight;
// set up the mixes!
this.spineBoy.stateData.setMix("walk", "jump", 0.2);
this.spineBoy.stateData.setMix("jump", "walk", 0.4);
// play animation
this.spineBoy.state.setAnimation(0, "walk", true);
this.spineBoy.interactive = true;
this.spineBoy.buttonMode = true;
this.spineBoy.on("pointerdown", () => {
this.spineBoy.state.setAnimation(0, "jump", false);
this.spineBoy.state.addAnimation(0, "walk", true, 0);
});
this.app.stage.addChild(this.spineBoy);
}
private drawPlayMusic(): void {
this.sound.on("end", () => {
playButton.visible = true;
stopButton.visible = false;
});
this.playMusicContainer = new PIXI.Container();
const playButton = new PIXI.Sprite(PIXI.loader.resources.play.texture);
playButton.scale.set(0.75, 0.75);
playButton.interactive = true;
playButton.buttonMode = true;
playButton.on("pointerup", () => {
this.sound.play();
playButton.visible = false;
stopButton.visible = true;
});
const stopButton = new PIXI.Sprite(PIXI.loader.resources.stop.texture);
stopButton.scale.set(0.75, 0.75);
stopButton.interactive = true;
stopButton.buttonMode = true;
stopButton.visible = false;
stopButton.on("pointerup", () => {
this.sound.stop();
stopButton.visible = false;
playButton.visible = true;
});
const text = new PIXI.extras.BitmapText("Click to play music!", this.bitmapTextStyle);
text.position.set(playButton.width + 10, playButton.height / 2 - text.height / 2);
this.playMusicContainer.addChild(playButton);
this.playMusicContainer.addChild(stopButton);
this.playMusicContainer.addChild(text);
this.playMusicContainer.position.set(this.app.initialWidth / 2 - this.playMusicContainer.width / 2, this.app.initialHeight * 0.1);
this.app.stage.addChild(this.playMusicContainer);
}
private relocateViews(): void {
/*
this.screenBorder.width = this.app.initialWidth - 2;
this.screenBorder.height = this.app.initialHeight - 2;
window.console.log(this.screenBorder.width, this.screenBorder.height);
*/
this.app.stage.removeChild(this.screenBorder);
this.drawScreenBorder();
if (this.fullScreenButton) {
this.fullScreenButton.position.set(this.app.initialWidth / 2 - this.fullScreenButton.width / 2, this.app.initialHeight / 2 - this.fullScreenButton.height / 2);
}
if (this.fullScreenText) {
this.fullScreenText.position.set(this.app.initialWidth / 2 - this.fullScreenText.width / 2, this.app.initialHeight / 2 - 125);
}
if (this.loadingText) {
this.loadingText.position.set(this.app.initialWidth / 5, 10);
}
if (this.filteredBunnies) {
this.filteredBunnies.position.set(this.app.initialWidth - this.filteredBunnies.width - 10, this.app.initialHeight - this.filteredBunnies.height);
}
if (this.layeredBunnies) {
this.layeredBunnies.position.set((this.app.initialWidth - this.layeredBunnies.width) - 10, 10);
}
if (this.particlesContainer) {
this.particlesContainer.position.set(this.app.initialWidth * 0.75, this.app.initialHeight * 0.5);
}
if (this.spineBoy) {
this.spineBoy.position.set(this.app.initialWidth * 0.5, this.app.initialHeight);
}
if (this.playMusicContainer) {
this.playMusicContainer.position.set(this.app.initialWidth / 2 - this.playMusicContainer.width / 2, this.app.initialHeight * 0.1);
}
if (this.explorer) {
TweenLite.killTweensOf(this.explorer, true);
const maxEdge = Math.max(this.explorer.width, this.explorer.height);
this.explorer.position.set(Math.ceil(maxEdge / 2) + 10, Math.ceil(maxEdge / 2) + 10);
TweenLite.to(this.explorer, 2, {y: this.app.initialHeight / 2});
}
}
} | the_stack |
import { isClassProvider, isExistingProvider, isFactoryProvider, isValueProvider, NormalizedProvider, ProviderWithScope, Tag, TagProvider, TagRegistry, Token } from './provider';
import { ClassType, CompilerContext, CustomError, getClassName, isClass, isFunction, isPrototypeOfBase } from '@deepkit/core';
import { getClassSchema, isFieldDecorator, PropertySchema } from '@deepkit/type';
import { InjectOptions, InjectorReference, InjectorToken, isInjectDecorator } from './decorator';
import { ConfigDefinition, ConfigSlice, ConfigToken } from './config';
import { findModuleForConfig, getScope, InjectorModule, PreparedProvider } from './module';
export class CircularDependencyError extends CustomError {
}
export class TokenNotFoundError extends CustomError {
}
export class DependenciesUnmetError extends CustomError {
}
export function tokenLabel(token: any): string {
if (token === null) return 'null';
if (token === undefined) return 'undefined';
if (token instanceof TagProvider) return 'Tag(' + getClassName(token.provider.provide) + ')';
if (isClass(token)) return getClassName(token);
if (isFunction(token.toString)) return token.name;
return token + '';
}
function constructorParameterNotFound(ofName: string, name: string, position: number, token: any) {
const argsCheck: string[] = [];
for (let i = 0; i < position; i++) argsCheck.push('✓');
argsCheck.push('?');
throw new DependenciesUnmetError(
`Unknown constructor argument '${name}: ${tokenLabel(token)}' of ${ofName}(${argsCheck.join(', ')}). Make sure '${tokenLabel(token)}' is provided.`
);
}
function tokenNotfoundError(token: any, moduleName: string) {
throw new TokenNotFoundError(
`Token '${tokenLabel(token)}' in ${moduleName} not found. Make sure '${tokenLabel(token)}' is provided.`
);
}
function factoryDependencyNotFound(ofName: string, name: string, position: number, token: any) {
const argsCheck: string[] = [];
for (let i = 0; i < position; i++) argsCheck.push('✓');
argsCheck.push('?');
for (const reset of CircularDetectorResets) reset();
throw new DependenciesUnmetError(
`Unknown factory dependency argument '${tokenLabel(token)}' of ${ofName}(${argsCheck.join(', ')}). Make sure '${tokenLabel(token)}' is provided.`
);
}
function propertyParameterNotFound(ofName: string, name: string, position: number, token: any) {
for (const reset of CircularDetectorResets) reset();
throw new DependenciesUnmetError(
`Unknown property parameter ${name} of ${ofName}. Make sure '${tokenLabel(token)}' is provided.`
);
}
let CircularDetector: any[] = [];
let CircularDetectorResets: (() => void)[] = [];
function throwCircularDependency() {
const path = CircularDetector.map(tokenLabel).join(' -> ');
CircularDetector.length = 0;
for (const reset of CircularDetectorResets) reset();
throw new CircularDependencyError(`Circular dependency found ${path}`);
}
export type SetupProviderCalls = {
type: 'call', methodName: string | symbol | number, args: any[], order: number
}
| { type: 'property', property: string | symbol | number, value: any, order: number }
| { type: 'stop', order: number }
;
export class SetupProviderRegistry {
public calls = new Map<Token, SetupProviderCalls[]>();
public add(token: any, ...newCalls: SetupProviderCalls[]) {
this.get(token).push(...newCalls);
}
mergeInto(registry: SetupProviderRegistry): void {
for (const [token, calls] of this.calls) {
registry.add(token, ...calls);
}
}
public get(token: Token): SetupProviderCalls[] {
let calls = this.calls.get(token);
if (!calls) {
calls = [];
this.calls.set(token, calls);
}
return calls;
}
}
interface Scope {
name: string;
instances: { [name: string]: any };
}
export type ResolveToken<T> = T extends ClassType<infer R> ? R : T extends InjectorToken<infer R> ? R : T;
export function resolveToken(provider: ProviderWithScope): Token {
if (isClass(provider)) return provider;
if (provider instanceof TagProvider) return resolveToken(provider.provider);
return provider.provide;
}
export interface InjectorInterface {
get<T>(token: T, scope?: Scope): ResolveToken<T>;
}
/**
* This is the actual dependency injection container.
* Every module has its own injector.
*/
export class Injector implements InjectorInterface {
private resolver?: (token: any, scope?: Scope) => any;
private setter?: (token: any, value: any, scope?: Scope) => any;
private instantiations?: (token: any, scope?: string) => number;
/**
* All unscoped provider instances. Scoped instances are attached to `Scope`.
*/
private instances: { [name: string]: any } = {};
private instantiated: { [name: string]: number } = {};
constructor(
public readonly module: InjectorModule,
private buildContext: BuildContext,
) {
module.injector = this;
this.build(buildContext);
}
static from(providers: ProviderWithScope[], parent?: Injector): Injector {
return new Injector(new InjectorModule(providers, parent?.module), new BuildContext);
}
static fromModule(module: InjectorModule, parent?: Injector): Injector {
return new Injector(module, new BuildContext);
}
get<T>(token: T, scope?: Scope): ResolveToken<T> {
if (!this.resolver) throw new Error('Injector was not built');
return this.resolver(token, scope);
}
set<T>(token: T, value: any, scope?: Scope): void {
if (!this.setter) throw new Error('Injector was not built');
this.setter(token, value, scope);
}
instantiationCount<T>(token: any, scope?: string): number {
if (!this.instantiations) throw new Error('Injector was not built');
return this.instantiations(token, scope);
}
clear() {
this.instances = {};
}
protected build(buildContext: BuildContext): void {
const resolverCompiler = new CompilerContext();
resolverCompiler.context.set('CircularDetector', CircularDetector);
resolverCompiler.context.set('CircularDetectorResets', CircularDetectorResets);
resolverCompiler.context.set('throwCircularDependency', throwCircularDependency);
resolverCompiler.context.set('tokenNotfoundError', tokenNotfoundError);
resolverCompiler.context.set('injector', this);
const lines: string[] = [];
const resets: string[] = [];
const creating: string[] = [];
const instantiationCompiler = new CompilerContext();
instantiationCompiler.context.set('injector', this);
const instantiationLines: string[] = [];
const setterCompiler = new CompilerContext();
setterCompiler.context.set('injector', this);
const setterLines: string[] = [];
for (const [token, prepared] of this.module.getPreparedProviders(buildContext).entries()) {
//scopes will be created first, so they are returned instead of the unscoped instance
prepared.providers.sort((a, b) => {
if (a.scope && !b.scope) return -1;
if (!a.scope && b.scope) return +1;
return 0;
});
for (const provider of prepared.providers) {
const scope = getScope(provider);
const name = 'i' + this.buildContext.providerIndex.reserve();
creating.push(`let creating_${name} = false;`);
resets.push(`creating_${name} = false;`);
const accessor = scope ? 'scope.instances.' + name : 'injector.instances.' + name;
const scopeObjectCheck = scope ? ` && scope && scope.name === ${JSON.stringify(scope)}` : '';
const scopeCheck = scope ? ` && scope === ${JSON.stringify(scope)}` : '';
setterLines.push(`case token === ${setterCompiler.reserveVariable('token', token)}${scopeObjectCheck}: {
if (${accessor} === undefined) {
injector.instantiated.${name} = injector.instantiated.${name} ? injector.instantiated.${name} + 1 : 1;
}
${accessor} = value;
break;
}`);
if (prepared.resolveFrom) {
//its a redirect
lines.push(`
case token === ${resolverCompiler.reserveConst(token, 'token')}${scopeObjectCheck}: {
return ${resolverCompiler.reserveConst(prepared.resolveFrom, 'resolveFrom')}.injector.resolver(${resolverCompiler.reserveConst(token, 'token')}, scope);
}
`);
instantiationLines.push(`
case token === ${instantiationCompiler.reserveConst(token, 'token')}${scopeCheck}: {
return ${instantiationCompiler.reserveConst(prepared.resolveFrom, 'resolveFrom')}.injector.instantiations(${instantiationCompiler.reserveConst(token, 'token')}, scope);
}
`)
} else {
//we own and instantiate the service
lines.push(this.buildProvider(buildContext, resolverCompiler, name, accessor, scope, provider, prepared.modules));
instantiationLines.push(`
case token === ${instantiationCompiler.reserveConst(token, 'token')}${scopeCheck}: {
return injector.instantiated.${name} || 0;
}
`)
}
}
}
this.instantiations = instantiationCompiler.build(`
//for ${getClassName(this.module)}
switch (true) {
${instantiationLines.join('\n')}
}
return 0;
`, 'token', 'scope');
this.setter = setterCompiler.build(`
//for ${getClassName(this.module)}
switch (true) {
${setterLines.join('\n')}
}
`, 'token', 'value', 'scope');
this.resolver = resolverCompiler.raw(`
//for ${getClassName(this.module)}
${creating.join('\n')};
CircularDetectorResets.push(() => {
${resets.join('\n')};
});
return function(token, scope) {
switch (true) {
${lines.join('\n')}
}
tokenNotfoundError(token, '${getClassName(this.module)}');
}
`) as any;
}
protected buildProvider(
buildContext: BuildContext,
compiler: CompilerContext,
name: string,
accessor: string,
scope: string,
provider: NormalizedProvider,
resolveDependenciesFrom: InjectorModule[],
) {
let transient = false;
const token = provider.provide;
let factory: { code: string, dependencies: number } = { code: '', dependencies: 0 };
const tokenVar = compiler.reserveConst(token);
if (isValueProvider(provider)) {
transient = provider.transient === true;
const valueVar = compiler.reserveVariable('useValue', provider.useValue);
factory.code = `${accessor} = ${valueVar};`;
} else if (isClassProvider(provider)) {
transient = provider.transient === true;
let useClass = provider.useClass;
if (!useClass) {
if (!isClass(provider.provide)) {
throw new Error(`UseClassProvider needs to set either 'useClass' or 'provide' as a ClassType. Got ${provider.provide as any}`);
}
useClass = provider.provide;
}
factory = this.createFactory(provider, accessor, compiler, useClass, resolveDependenciesFrom);
} else if (isExistingProvider(provider)) {
transient = provider.transient === true;
factory.code = `${accessor} = injector.resolver(${compiler.reserveConst(provider.useExisting)}, scope)`;
} else if (isFactoryProvider(provider)) {
transient = provider.transient === true;
const args: string[] = [];
let i = 0;
for (const dep of provider.deps || []) {
let optional = false;
let token = dep;
if (isInjectDecorator(dep)) {
optional = dep.options.optional;
token = dep.options.token;
}
if (isFieldDecorator(dep)) {
const propertySchema = dep.buildPropertySchema();
optional = propertySchema.isOptional;
if (propertySchema.type === 'literal' || propertySchema.type === 'class') {
token = propertySchema.literalValue !== undefined ? propertySchema.literalValue : propertySchema.getResolvedClassType();
}
}
if (!token) {
throw new Error(`No token defined for dependency ${i} in 'deps' of useFactory for ${tokenLabel(provider.provide)}`);
}
factory.dependencies++;
args.push(this.createFactoryProperty({
name: i++,
token,
optional,
}, provider, compiler, resolveDependenciesFrom, 'useFactory', args.length, 'factoryDependencyNotFound'));
}
factory.code = `${accessor} = ${compiler.reserveVariable('factory', provider.useFactory)}(${args.join(', ')});`;
} else {
throw new Error('Invalid provider');
}
const configureProvider: string[] = [];
const configuredProviderCalls = resolveDependenciesFrom[0].setupProviderRegistry?.get(token);
configuredProviderCalls.push(...buildContext.globalSetupProviderRegistry.get(token));
if (configuredProviderCalls) {
configuredProviderCalls.sort((a, b) => {
return a.order - b.order;
});
for (const call of configuredProviderCalls) {
if (call.type === 'stop') break;
if (call.type === 'call') {
const args: string[] = [];
const methodName = 'symbol' === typeof call.methodName ? '[' + compiler.reserveVariable('arg', call.methodName) + ']' : call.methodName;
for (const arg of call.args) {
if (arg instanceof InjectorReference) {
const injector = arg.module ? compiler.reserveConst(arg.module) + '.injector' : 'injector';
args.push(`${injector}.resolver(${compiler.reserveConst(arg.to)}, scope)`);
} else {
args.push(`${compiler.reserveVariable('arg', arg)}`);
}
}
configureProvider.push(`${accessor}.${methodName}(${args.join(', ')});`);
}
if (call.type === 'property') {
const property = 'symbol' === typeof call.property ? '[' + compiler.reserveVariable('property', call.property) + ']' : call.property;
const value = call.value instanceof InjectorReference ? `frontInjector.get(${compiler.reserveVariable('forward', call.value.to)})` : compiler.reserveVariable('value', call.value);
configureProvider.push(`${accessor}.${property} = ${value};`);
}
}
} else {
configureProvider.push('//no custom provider setup');
}
const scopeCheck = scope ? ` && scope && scope.name === ${JSON.stringify(scope)}` : '';
//circular dependencies can happen, when for example a service with InjectorContext injected manually instantiates a service.
//if that service references back to the first one, it will be a circular loop. So we track that with `creating` state.
const creatingVar = `creating_${name}`;
const circularDependencyCheckStart = factory.dependencies ? `if (${creatingVar}) throwCircularDependency();${creatingVar} = true;` : '';
const circularDependencyCheckEnd = factory.dependencies ? `${creatingVar} = false;` : '';
return `
//${tokenLabel(token)}, from ${resolveDependenciesFrom.map(getClassName).join(', ')}
case token === ${tokenVar}${scopeCheck}: {
${!transient ? `if (${accessor} !== undefined) return ${accessor};` : ''}
CircularDetector.push(${tokenVar});
${circularDependencyCheckStart}
injector.instantiated.${name} = injector.instantiated.${name} ? injector.instantiated.${name} + 1 : 1;
${factory.code}
${circularDependencyCheckEnd}
CircularDetector.pop();
${configureProvider.join('\n')}
return ${accessor};
}
`;
}
protected createFactory(
provider: NormalizedProvider,
resolvedName: string,
compiler: CompilerContext,
classType: ClassType,
resolveDependenciesFrom: InjectorModule[]
): { code: string, dependencies: number } {
if (!classType) throw new Error('Can not create factory for undefined ClassType');
const schema = getClassSchema(classType);
const args: string[] = [];
const propertyAssignment: string[] = [];
const classTypeVar = compiler.reserveVariable('classType', classType);
let dependencies: number = 0;
for (const property of schema.getMethodProperties('constructor')) {
if (!property) {
throw new Error(`Constructor arguments hole in ${getClassName(classType)}`);
}
dependencies++;
args.push(this.createFactoryProperty(this.optionsFromProperty(property), provider, compiler, resolveDependenciesFrom, getClassName(classType), args.length, 'constructorParameterNotFound'));
}
for (const property of schema.getProperties()) {
if (!('deepkit/inject' in property.data)) continue;
if (property.methodName === 'constructor') continue;
dependencies++;
try {
const resolveProperty = this.createFactoryProperty(this.optionsFromProperty(property), provider, compiler, resolveDependenciesFrom, getClassName(classType), -1, 'propertyParameterNotFound');
propertyAssignment.push(`${resolvedName}.${property.name} = ${resolveProperty};`);
} catch (error) {
throw new Error(`Could not resolve property injection token ${getClassName(classType)}.${property.name}: ${error.message}`);
}
}
return {
code: `${resolvedName} = new ${classTypeVar}(${args.join(',')});\n${propertyAssignment.join('\n')}`,
dependencies
};
}
protected createFactoryProperty(
options: { name: string | number, token: any, optional: boolean },
fromProvider: NormalizedProvider,
compiler: CompilerContext,
resolveDependenciesFrom: InjectorModule[],
ofName: string,
argPosition: number,
notFoundFunction: string
): string {
const token = options.token;
let of = `${ofName}.${options.name}`;
//regarding configuration values: the attached module is not necessarily in resolveDependenciesFrom[0]
//if the parent module overwrites its, then the parent module is at 0th position.
if (isClass(token) && resolveDependenciesFrom[0] instanceof token) {
return compiler.reserveConst(resolveDependenciesFrom[0], 'module');
} else if (token instanceof ConfigDefinition) {
try {
const module = findModuleForConfig(token, resolveDependenciesFrom);
return compiler.reserveVariable('fullConfig', module.getConfig());
} catch (error) {
throw new DependenciesUnmetError(`Undefined configuration dependency '${options.name}' of ${of}. ${error.message}`);
}
} else if (token instanceof ConfigToken) {
try {
const module = findModuleForConfig(token.config, resolveDependenciesFrom);
const config = module.getConfig();
return compiler.reserveVariable(token.name, (config as any)[token.name]);
} catch (error) {
throw new DependenciesUnmetError(`Undefined configuration dependency '${options.name}' of ${of}. ${error.message}`);
}
} else if (isClass(token) && (Object.getPrototypeOf(Object.getPrototypeOf(token)) === ConfigSlice || Object.getPrototypeOf(token) === ConfigSlice)) {
try {
const value: ConfigSlice<any> = new token;
const module = findModuleForConfig(value.config, resolveDependenciesFrom);
value.bag = module.getConfig();
return compiler.reserveVariable('configSlice', value);
} catch (error) {
throw new DependenciesUnmetError(`Undefined configuration dependency '${options.name}' of ${of}. ${error.message}`);
}
} else if (token === TagRegistry) {
return compiler.reserveVariable('tagRegistry', this.buildContext.tagRegistry);
} else if (isPrototypeOfBase(token, Tag)) {
const tokenVar = compiler.reserveVariable('token', token);
const resolvedVar = compiler.reserveVariable('tagResolved');
const entries = this.buildContext.tagRegistry.resolve(token);
const args: string[] = [];
for (const entry of entries) {
args.push(`${compiler.reserveConst(entry.module)}.injector.resolver(${compiler.reserveConst(entry.tagProvider.provider.provide)}, scope)`);
}
return `new ${tokenVar}(${resolvedVar} || (${resolvedVar} = [${args.join(', ')}]))`;
} else {
if (token === undefined) {
if (argPosition >= 0) {
const argsCheck: string[] = [];
for (let i = 0; i < argPosition; i++) argsCheck.push('✓');
argsCheck.push('?');
of = `${ofName}(${argsCheck.join(', ')})`;
}
throw new DependenciesUnmetError(
`Undefined dependency '${options.name}: undefined' of ${of}. Dependency '${options.name}' has no type. Imported reflect-metadata correctly? ` +
`Use '@inject(PROVIDER) ${options.name}: T' if T is an interface. For circular references use @inject(() => T) ${options.name}: T.`
);
}
const tokenVar = compiler.reserveVariable('token', token);
let foundPreparedProvider: PreparedProvider | undefined = undefined;
for (const module of resolveDependenciesFrom) {
foundPreparedProvider = module.getPreparedProvider(token);
if (foundPreparedProvider) {
if (foundPreparedProvider) {
//check if the found provider was actually exported to this current module.
//if not it means that provider is encapsulated living only in its module and can not be accessed from other modules.
const moduleHasAccessToThisProvider = foundPreparedProvider.modules.some(m => m === module);
if (!moduleHasAccessToThisProvider) {
foundPreparedProvider = undefined;
}
}
}
}
if (!foundPreparedProvider) {
//try if parents have anything
const foundInModule = this.module.resolveToken(token);
if (foundInModule) {
foundPreparedProvider = foundInModule.getPreparedProvider(token);
}
}
if (!foundPreparedProvider && options.optional) return 'undefined';
if (!foundPreparedProvider) {
throw new DependenciesUnmetError(
`Unknown dependency '${options.name}: ${tokenLabel(token)}' of ${of}.`
);
}
const allPossibleScopes = foundPreparedProvider.providers.map(getScope);
const fromScope = getScope(fromProvider);
const unscoped = allPossibleScopes.includes('') && allPossibleScopes.length === 1;
if (!unscoped && !allPossibleScopes.includes(fromScope)) {
throw new DependenciesUnmetError(
`Dependency '${options.name}: ${tokenLabel(token)}' of ${of} can not be injected into ${fromScope ? 'scope ' + fromScope : 'no scope'}, ` +
`since ${tokenLabel(token)} only exists in scope${allPossibleScopes.length === 1 ? '' : 's'} ${allPossibleScopes.join(', ')}.`
);
}
//when the dependency is FactoryProvider it might return undefined.
//in this case, if the dependency is not optional, we throw an error.
const orThrow = options.optional ? '' : `?? ${notFoundFunction}(${JSON.stringify(ofName)}, ${JSON.stringify(options.name)}, ${argPosition}, ${tokenVar})`;
const resolveFromModule = foundPreparedProvider.resolveFrom || foundPreparedProvider.modules[0];
if (resolveFromModule === this.module) {
return `injector.resolver(${tokenVar}, scope)`;
}
return `${compiler.reserveConst(resolveFromModule)}.injector.resolver(${tokenVar}, scope) ${orThrow}`;
}
}
protected optionsFromProperty(property: PropertySchema): { token: any, name: string | number, optional: boolean } {
const options = property.data['deepkit/inject'] as InjectOptions | undefined;
let token: any = property.resolveClassType;
if (options && options.token) {
token = isFunction(options.token) ? options.token() : options.token;
} else if (property.type === 'class') {
token = property.getResolvedClassType();
} else if (property.type === 'literal') {
token = property.literalValue;
}
return { token, name: property.name, optional: property.isOptional ? true : (!!options && options.optional) };
}
}
class BuildProviderIndex {
protected offset: number = 0;
reserve(): number {
return this.offset++;
}
}
export class BuildContext {
static ids: number = 0;
public id: number = BuildContext.ids++;
tagRegistry: TagRegistry = new TagRegistry;
providerIndex: BuildProviderIndex = new BuildProviderIndex;
/**
* In the process of preparing providers, each module redirects their
* global setup calls in this registry.
*/
globalSetupProviderRegistry: SetupProviderRegistry = new SetupProviderRegistry;
}
/**
* A InjectorContext is responsible for taking a root InjectorModule and build all Injectors.
*
* It also can create scopes aka a sub InjectorContext with providers from a particular scope.
*/
export class InjectorContext {
constructor(
public rootModule: InjectorModule,
public readonly scope?: Scope,
protected buildContext: BuildContext = new BuildContext,
) {
}
get<T>(token: T | Token, module?: InjectorModule): ResolveToken<T> {
return this.getInjector(module || this.rootModule).get(token, this.scope);
}
instantiationCount(token: Token, module?: InjectorModule, scope?: string): number {
return this.getInjector(module || this.rootModule).instantiationCount(token, this.scope ? this.scope.name : scope);
}
set<T>(token: T, value: any, module?: InjectorModule): void {
return this.getInjector(module || this.rootModule).set(token, value, this.scope);
}
static forProviders(providers: ProviderWithScope[]) {
return new InjectorContext(new InjectorModule(providers));
}
/**
* Returns the unscoped injector. Use `.get(T, Scope)` for resolving scoped token.
*/
getInjector(module: InjectorModule): Injector {
return module.getOrCreateInjector(this.buildContext);
}
getRootInjector(): Injector {
return this.getInjector(this.rootModule);
}
public createChildScope(scope: string): InjectorContext {
return new InjectorContext(this.rootModule, { name: scope, instances: {} }, this.buildContext);
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_approval_Information {
interface Header extends DevKit.Controls.IHeader {
/** Shows the status of the approval. */
msdyn_approvalstatus: DevKit.Controls.OptionSet;
/** Unique identifier of the user or team who owns the activity. */
OwnerId: DevKit.Controls.Lookup;
/** Status of the activity. */
StateCode: DevKit.Controls.OptionSet;
/** Person who is the receiver of the activity. */
To: DevKit.Controls.Lookup;
}
interface Tabs {
}
interface Body {
/** Skill for approval */
msdyn_Characteristic: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
/** Unique identifier of the user or team who owns the activity. */
OwnerId: DevKit.Controls.Lookup;
/** Subject associated with the activity. */
Subject: DevKit.Controls.String;
}
}
class Formmsdyn_approval_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_approval_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_approval_Information */
Body: DevKit.Formmsdyn_approval_Information.Body;
/** The Header section of form msdyn_approval_Information */
Header: DevKit.Formmsdyn_approval_Information.Header;
}
class msdyn_approvalApi {
/**
* DynamicsCrm.DevKit msdyn_approvalApi
* @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;
/** Additional information provided by the external application as JSON. For internal use only. */
ActivityAdditionalParams: DevKit.WebApi.StringValue;
/** Unique identifier of the activity. */
ActivityId: DevKit.WebApi.GuidValue;
/** Actual duration of the activity in minutes. */
ActualDurationMinutes: DevKit.WebApi.IntegerValue;
/** Actual end time of the activity. */
ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Actual start time of the activity. */
ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */
Community: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the user who created the activity. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the activity was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows the delegate user who created the activity. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the delivery of the activity was last attempted. */
DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Priority of delivery of the activity to the email server. */
DeliveryPriorityCode: DevKit.WebApi.OptionSetValue;
/** Description of the activity. */
Description: DevKit.WebApi.StringValue;
/** The message id of activity which is returned from Exchange Server. */
ExchangeItemId: DevKit.WebApi.StringValue;
/** Exchange rate for the currency associated with the activitypointer with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Shows the web link of Activity of type email. */
ExchangeWebLink: DevKit.WebApi.StringValue;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Type of instance of a recurring series. */
InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** Information regarding whether the activity was billed as part of resolving a case. */
IsBilled: DevKit.WebApi.BooleanValue;
/** For internal use only. */
IsMapiPrivate: DevKit.WebApi.BooleanValue;
/** Information regarding whether the activity is a regular activity type or event type. */
IsRegularActivity: DevKit.WebApi.BooleanValueReadonly;
/** Information regarding whether the activity was created from a workflow rule. */
IsWorkflowCreated: DevKit.WebApi.BooleanValue;
/** Contains the date and time stamp of the last on hold time. */
LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Left the voice mail */
LeftVoiceMail: DevKit.WebApi.BooleanValue;
/** Unique identifier of user who last modified the activity. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when activity was last modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows the delegate user who last modified the activity. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the status of the approval. */
msdyn_approvalstatus: DevKit.WebApi.OptionSetValue;
/** Skill for approval */
msdyn_Characteristic: DevKit.WebApi.LookupValue;
/** 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;
/** Unique identifier of the business unit that owns the activity. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team that owns the activity. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user that owns the activity. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** For internal use only. */
PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Priority of the activity. */
PriorityCode: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the Process. */
ProcessId: DevKit.WebApi.GuidValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_account_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bookableresourcebooking_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bookableresourcebookingheader_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_bulkoperation_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_campaign_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_campaignactivity_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_contact_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_contract_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_entitlement_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_entitlementtemplate_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_incident_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_new_interactionforemail_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_invoice_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_knowledgearticle_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_knowledgebaserecord_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_lead_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreement_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingdate_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingincident_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingservice_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingservicetask_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementbookingsetup_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoicedate_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoiceproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_agreementinvoicesetup_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingalertstatus_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingrule_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_bookingtimestamp_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_customerasset_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_fieldservicesetting_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypecharacteristic_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypeproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_incidenttypeservice_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryadjustment_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryadjustmentproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventoryjournal_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_inventorytransfer_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_payment_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentdetail_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentmethod_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_paymentterm_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_playbookinstance_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_postalbum_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_postalcode_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_processnotes_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_productinventory_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_projectteam_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorder_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderbill_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderreceipt_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseorderreceiptproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_purchaseordersubstatus_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingincident_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingservice_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_quotebookingservicetask_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_resourceterritory_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rma_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmaproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmareceipt_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmareceiptproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rmasubstatus_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtv_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtvproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_rtvsubstatus_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_shipvia_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_systemuserschedulersetting_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timegroup_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timegroupdetail_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_timeoffrequest_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_warehouse_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorder_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workordercharacteristic_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderincident_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderproduct_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderresourcerestriction_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderservice_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_msdyn_workorderservicetask_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_opportunity_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_quote_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_salesorder_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_site_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_action_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_hostedapplication_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_nonhostedapplication_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_option_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_savedsession_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflow_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflowstep_msdyn_approval: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the activity is associated. */
regardingobjectid_uii_workflow_workflowstep_mapping_msdyn_approval: DevKit.WebApi.LookupValue;
RegardingObjectIdYomiName: DevKit.WebApi.StringValue;
/** Scheduled duration of the activity, specified in minutes. */
ScheduledDurationMinutes: DevKit.WebApi.IntegerValue;
/** Scheduled end time of the activity. */
ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Scheduled start time of the activity. */
ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Unique identifier of the mailbox associated with the sender of the email message. */
SenderMailboxId: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the activity was sent. */
SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows the ID of the recurring series of an instance. */
SeriesId: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of an associated service. */
ServiceId: DevKit.WebApi.LookupValue;
/** Choose the service level agreement (SLA) that you want to apply to the case 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 date and time by which the activities are sorted. */
SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Unique identifier of the Stage. */
StageId: DevKit.WebApi.GuidValue;
/** Status of the activity. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the activity. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Subject associated with the activity. */
Subject: DevKit.WebApi.StringValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the currency associated with the activitypointer. */
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 activity. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** The array of object that can cast object to ActivityPartyApi class */
ActivityParties: Array<any>;
}
}
declare namespace OptionSet {
namespace msdyn_approval {
enum Community {
/** 5 */
Cortana,
/** 6 */
Direct_Line,
/** 8 */
Direct_Line_Speech,
/** 9 */
Email,
/** 1 */
Facebook,
/** 10 */
GroupMe,
/** 11 */
Kik,
/** 3 */
Line,
/** 7 */
Microsoft_Teams,
/** 0 */
Other,
/** 13 */
Skype,
/** 14 */
Slack,
/** 12 */
Telegram,
/** 2 */
Twitter,
/** 4 */
Wechat,
/** 15 */
WhatsApp
}
enum DeliveryPriorityCode {
/** 2 */
High,
/** 0 */
Low,
/** 1 */
Normal
}
enum InstanceTypeCode {
/** 0 */
Not_Recurring,
/** 3 */
Recurring_Exception,
/** 4 */
Recurring_Future_Exception,
/** 2 */
Recurring_Instance,
/** 1 */
Recurring_Master
}
enum msdyn_approvalstatus {
/** 192350003 */
Approved,
/** 192350001 */
Pending_Approval,
/** 192350004 */
Recalled,
/** 192350002 */
Rejected,
/** 192350000 */
Saved
}
enum PriorityCode {
/** 2 */
High,
/** 0 */
Low,
/** 1 */
Normal
}
enum StateCode {
/** 2 */
Canceled,
/** 1 */
Completed,
/** 0 */
Open,
/** 3 */
Scheduled
}
enum StatusCode {
/** 3 */
Canceled,
/** 2 */
Completed,
/** 1 */
Open,
/** 4 */
Scheduled
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {GristDoc} from "app/client/components/GristDoc";
import {buildParseOptionsForm, ParseOptionValues} from 'app/client/components/ParseOptions';
import {PluginScreen} from "app/client/components/PluginScreen";
import {ImportSourceElement} from 'app/client/lib/ImportSourceElement';
import {fetchURL, isDriveUrl, selectFiles, uploadFiles} from 'app/client/lib/uploads';
import {reportError} from 'app/client/models/AppModel';
import {ViewSectionRec} from 'app/client/models/DocModel';
import {SortedRowSet} from "app/client/models/rowset";
import {openFilePicker} from "app/client/ui/FileDialog";
import {bigBasicButton, bigPrimaryButton} from 'app/client/ui2018/buttons';
import {colors, testId, vars} from 'app/client/ui2018/cssVars';
import {icon} from 'app/client/ui2018/icons';
import {IOptionFull, linkSelect, multiSelect} from 'app/client/ui2018/menus';
import {cssModalButtons, cssModalTitle} from 'app/client/ui2018/modals';
import {loadingSpinner} from "app/client/ui2018/loaders";
import {DataSourceTransformed, ImportResult, ImportTableResult, MergeOptions,
MergeOptionsMap,
MergeStrategy, TransformColumn, TransformRule, TransformRuleMap} from "app/common/ActiveDocAPI";
import {byteString} from "app/common/gutil";
import {FetchUrlOptions, UploadResult} from 'app/common/uploads';
import {ParseOptions, ParseOptionSchema} from 'app/plugin/FileParserAPI';
import {Computed, Disposable, dom, DomContents, IDisposable, MutableObsArray, obsArray, Observable,
styled} from 'grainjs';
import {labeledSquareCheckbox} from "app/client/ui2018/checkbox";
import {ACCESS_DENIED, AUTH_INTERRUPTED, canReadPrivateFiles, getGoogleCodeForReading} from "app/client/ui/googleAuth";
import debounce = require('lodash/debounce');
// Special values for import destinations; null means "new table".
// TODO We should also support "skip table" (needs server support), so that one can open, say,
// an Excel file with many tabs, and import only some of them.
type DestId = string | null;
// We expect a function for creating the preview GridView, to avoid the need to require the
// GridView module here. That brings many dependencies, making a simple test fixture difficult.
type CreatePreviewFunc = (vs: ViewSectionRec) => GridView;
type GridView = IDisposable & {viewPane: HTMLElement, sortedRows: SortedRowSet, listenTo: (...args: any[]) => void};
export interface SourceInfo {
// The source table id.
hiddenTableId: string;
uploadFileIndex: number;
origTableName: string;
sourceSection: ViewSectionRec;
// A viewsection containing transform (formula) columns pointing to the original source columns.
transformSection: Observable<ViewSectionRec|null>;
// The destination table id.
destTableId: Observable<DestId>;
// True if there is at least one request in progress to create a new transform section.
isLoadingSection: Observable<boolean>;
// Reference to last promise for the GenImporterView action (which creates `transformSection`).
lastGenImporterViewPromise: Promise<any>|null;
}
interface MergeOptionsStateMap {
[hiddenTableId: string]: MergeOptionsState|undefined;
}
// UI state of merge options for a SourceInfo.
interface MergeOptionsState {
updateExistingRecords: Observable<boolean>;
mergeCols: MutableObsArray<string>;
mergeStrategy: Observable<MergeStrategy>;
hasInvalidMergeCols: Observable<boolean>;
}
/**
* Importer manages an import files to Grist tables and shows Preview
*/
export class Importer extends Disposable {
/**
* Imports using the given plugin importer, or the built-in file-picker when null is passed in.
*/
public static async selectAndImport(
gristDoc: GristDoc,
imports: ImportSourceElement[],
importSourceElem: ImportSourceElement|null,
createPreview: CreatePreviewFunc
) {
// In case of using built-in file picker we want to get upload result before instantiating Importer
// because if the user dismisses the dialog without picking a file,
// there is no good way to detect this and dispose Importer.
let uploadResult: UploadResult|null = null;
if (!importSourceElem) {
// Use the built-in file picker. On electron, it uses the native file selector (without
// actually uploading anything), which is why this requires a slightly different flow.
const files: File[] = await openFilePicker({multiple: true});
// Important to fork first before trying to import, so we end up uploading to a
// consistent doc worker.
await gristDoc.forkIfNeeded();
const label = files.map(f => f.name).join(', ');
const size = files.reduce((acc, f) => acc + f.size, 0);
const app = gristDoc.app.topAppModel.appObs.get();
const progress = app ? app.notifier.createProgressIndicator(label, byteString(size)) : null;
const onProgress = (percent: number) => progress && progress.setProgress(percent);
try {
onProgress(0);
uploadResult = await uploadFiles(files, {docWorkerUrl: gristDoc.docComm.docWorkerUrl,
sizeLimit: 'import'}, onProgress);
onProgress(100);
} finally {
if (progress) {
progress.dispose();
}
}
}
// HACK: The url plugin does not support importing from google drive, and we don't want to
// ask a user for permission to access all his files (needed to download a single file from an URL).
// So to have a nice user experience, we will switch to the built-in google drive plugin and allow
// user to chose a file manually.
// Suggestion for the future is:
// (1) ask the user for the greater permission,
// (2) detect when the permission is not granted, and open the picker-based plugin in that case.
try {
// Importer disposes itself when its dialog is closed, so we do not take ownership of it.
await Importer.create(null, gristDoc, importSourceElem, createPreview).pickAndUploadSource(uploadResult);
} catch(err1) {
// If the url was a Google Drive Url, run the google drive plugin.
if (!(err1 instanceof GDriveUrlNotSupported)) {
reportError(err1);
} else {
const gdrivePlugin = imports.find((p) => p.plugin.definition.id === 'builtIn/gdrive' && p !== importSourceElem);
if (!gdrivePlugin) {
reportError(err1);
} else {
try {
await Importer.create(null, gristDoc, gdrivePlugin, createPreview).pickAndUploadSource(uploadResult);
} catch(err2) {
reportError(err2);
}
}
}
}
}
private _docComm = this._gristDoc.docComm;
private _uploadResult?: UploadResult;
private _screen: PluginScreen;
private _mergeOptions: MergeOptionsStateMap = {};
private _parseOptions = Observable.create<ParseOptions>(this, {});
private _sourceInfoArray = Observable.create<SourceInfo[]>(this, []);
private _sourceInfoSelected = Observable.create<SourceInfo|null>(this, null);
private _previewViewSection: Observable<ViewSectionRec|null> =
Computed.create(this, this._sourceInfoSelected, (use, info) => {
if (!info) { return null; }
const isLoading = use(info.isLoadingSection);
if (isLoading) { return null; }
const viewSection = use(info.transformSection);
return viewSection && !use(viewSection._isDeleted) ? viewSection : null;
});
// True if there is at least one request in progress to generate an import diff.
private _isLoadingDiff = Observable.create(this, false);
// Promise for the most recent generateImportDiff action.
private _lastGenImportDiffPromise: Promise<any>|null = null;
private _updateImportDiff = debounce(this._updateDiff, 1000, {leading: true, trailing: true});
// destTables is a list of options for import destinations, and includes all tables in the
// document, plus two values: to import as a new table, and to skip an import table entirely.
private _destTables = Computed.create<Array<IOptionFull<DestId>>>(this, (use) => [
{value: null, label: 'New Table'},
...use(this._gristDoc.docModel.allTableIds.getObservable()).map((t) => ({value: t, label: t})),
]);
// null tells to use the built-in file picker.
constructor(private _gristDoc: GristDoc, private _importSourceElem: ImportSourceElement|null,
private _createPreview: CreatePreviewFunc) {
super();
this._screen = PluginScreen.create(this, _importSourceElem?.importSource.label || "Import from file");
this.onDispose(() => {
this._resetImportDiffState();
});
}
/*
* Get new import sources and update the current one.
*/
public async pickAndUploadSource(uploadResult: UploadResult|null) {
try {
if (!this._importSourceElem) {
// Use upload result if it was passed in or the built-in file picker.
// On electron, it uses the native file selector (without actually uploading anything),
// which is why this requires a slightly different flow.
uploadResult = uploadResult || await selectFiles({docWorkerUrl: this._docComm.docWorkerUrl,
multiple: true, sizeLimit: 'import'});
} else {
const plugin = this._importSourceElem.plugin;
const handle = this._screen.renderPlugin(plugin);
const importSource = await this._importSourceElem.importSourceStub.getImportSource(handle);
plugin.removeRenderTarget(handle);
this._screen.renderSpinner();
if (importSource) {
// If data has been picked, upload it.
const item = importSource.item;
if (item.kind === "fileList") {
const files = item.files.map(({content, name}) => new File([content], name));
uploadResult = await uploadFiles(files, {docWorkerUrl: this._docComm.docWorkerUrl,
sizeLimit: 'import'});
} else if (item.kind === "url") {
if (isDriveUrl(item.url)) {
uploadResult = await this._fetchFromDrive(item.url);
} else {
uploadResult = await fetchURL(this._docComm, item.url);
}
} else {
throw new Error(`Import source of kind ${(item as any).kind} are not yet supported!`);
}
}
}
} catch (err) {
if (err instanceof CancelledError) {
await this._cancelImport();
return;
}
if (err instanceof GDriveUrlNotSupported) {
await this._cancelImport();
throw err;
}
this._screen.renderError(err.message);
return;
}
if (uploadResult) {
this._uploadResult = uploadResult;
await this._reImport(uploadResult);
} else {
await this._cancelImport();
}
}
private _getPrimaryViewSection(tableId: string): ViewSectionRec {
const tableModel = this._gristDoc.getTableModel(tableId);
const viewRow = tableModel.tableMetaRow.primaryView.peek();
return viewRow.viewSections.peek().peek()[0];
}
private _getSectionByRef(sectionRef: number): ViewSectionRec {
return this._gristDoc.docModel.viewSections.getRowModel(sectionRef);
}
private async _updateTransformSection(sourceInfo: SourceInfo) {
this._resetImportDiffState();
sourceInfo.isLoadingSection.set(true);
sourceInfo.transformSection.set(null);
const genImporterViewPromise = this._gristDoc.docData.sendAction(
['GenImporterView', sourceInfo.hiddenTableId, sourceInfo.destTableId.get(), null]);
sourceInfo.lastGenImporterViewPromise = genImporterViewPromise;
const transformSectionRef = await genImporterViewPromise;
// If the request is superseded by a newer request, or the Importer is disposed, do nothing.
if (this.isDisposed() || sourceInfo.lastGenImporterViewPromise !== genImporterViewPromise) {
return;
}
// Otherwise, update the transform section for `sourceInfo`.
sourceInfo.transformSection.set(this._gristDoc.docModel.viewSections.getRowModel(transformSectionRef));
sourceInfo.isLoadingSection.set(false);
}
private _getTransformedDataSource(upload: UploadResult): DataSourceTransformed {
const transforms: TransformRuleMap[] = upload.files.map((file, i) => this._createTransformRuleMap(i));
return {uploadId: upload.uploadId, transforms};
}
private _getMergeOptionMaps(upload: UploadResult): MergeOptionsMap[] {
return upload.files.map((_file, i) => this._createMergeOptionsMap(i));
}
private _createTransformRuleMap(uploadFileIndex: number): TransformRuleMap {
const result: TransformRuleMap = {};
for (const sourceInfo of this._sourceInfoArray.get()) {
if (sourceInfo.uploadFileIndex === uploadFileIndex) {
result[sourceInfo.origTableName] = this._createTransformRule(sourceInfo);
}
}
return result;
}
private _createMergeOptionsMap(uploadFileIndex: number): MergeOptionsMap {
const result: MergeOptionsMap = {};
for (const sourceInfo of this._sourceInfoArray.get()) {
if (sourceInfo.uploadFileIndex === uploadFileIndex) {
result[sourceInfo.origTableName] = this._getMergeOptionsForSource(sourceInfo);
}
}
return result;
}
private _createTransformRule(sourceInfo: SourceInfo): TransformRule {
const transformSection = sourceInfo.transformSection.get();
if (!transformSection) {
throw new Error(`Table ${sourceInfo.hiddenTableId} is missing transform section`);
}
const transformFields = transformSection.viewFields().peek();
const sourceFields = sourceInfo.sourceSection.viewFields().peek();
const destTableId: DestId = sourceInfo.destTableId.get();
return {
destTableId,
destCols: transformFields.map<TransformColumn>((field) => ({
label: field.label(),
colId: destTableId ? field.colId() : null, // if inserting into new table, colId isnt defined
type: field.column().type(),
formula: field.column().formula()
})),
sourceCols: sourceFields.map((field) => field.colId())
};
}
private _getMergeOptionsForSource(sourceInfo: SourceInfo): MergeOptions|undefined {
const mergeOptions = this._mergeOptions[sourceInfo.hiddenTableId];
if (!mergeOptions) { return undefined; }
const {updateExistingRecords, mergeCols, mergeStrategy} = mergeOptions;
return {
mergeCols: updateExistingRecords.get() ? mergeCols.get() : [],
mergeStrategy: mergeStrategy.get()
};
}
private _getHiddenTableIds(): string[] {
return this._sourceInfoArray.get().map((t: SourceInfo) => t.hiddenTableId);
}
private async _reImport(upload: UploadResult) {
this._screen.renderSpinner();
this._resetImportDiffState();
try {
const parseOptions = {...this._parseOptions.get(), NUM_ROWS: 0};
const importResult: ImportResult = await this._docComm.importFiles(
this._getTransformedDataSource(upload), parseOptions, this._getHiddenTableIds());
this._parseOptions.set(importResult.options);
this._sourceInfoArray.set(importResult.tables.map((info: ImportTableResult) => ({
hiddenTableId: info.hiddenTableId,
uploadFileIndex: info.uploadFileIndex,
origTableName: info.origTableName,
sourceSection: this._getPrimaryViewSection(info.hiddenTableId)!,
transformSection: Observable.create(null, this._getSectionByRef(info.transformSectionRef)),
destTableId: Observable.create<DestId>(null, info.destTableId),
isLoadingSection: Observable.create(null, false),
lastGenImporterViewPromise: null
})));
if (this._sourceInfoArray.get().length === 0) {
throw new Error("No data was imported");
}
this._mergeOptions = {};
this._getHiddenTableIds().forEach(tableId => {
this._mergeOptions[tableId] = {
updateExistingRecords: Observable.create(null, false),
mergeCols: obsArray(),
mergeStrategy: Observable.create(null, {type: 'replace-with-nonblank-source'}),
hasInvalidMergeCols: Observable.create(null, false),
};
});
// Select the first sourceInfo to show in preview.
this._sourceInfoSelected.set(this._sourceInfoArray.get()[0] || null);
this._renderMain(upload);
} catch (e) {
console.warn("Import failed", e);
this._screen.renderError(e.message);
}
}
private async _maybeFinishImport(upload: UploadResult) {
const isConfigValid = this._validateImportConfiguration();
if (!isConfigValid) { return; }
this._screen.renderSpinner();
this._resetImportDiffState();
const parseOptions = {...this._parseOptions.get(), NUM_ROWS: 0};
const mergeOptionMaps = this._getMergeOptionMaps(upload);
const importResult: ImportResult = await this._docComm.finishImportFiles(
this._getTransformedDataSource(upload), this._getHiddenTableIds(), {mergeOptionMaps, parseOptions});
if (importResult.tables[0].hiddenTableId) {
const tableRowModel = this._gristDoc.docModel.dataTables[importResult.tables[0].hiddenTableId].tableMetaRow;
await this._gristDoc.openDocPage(tableRowModel.primaryViewId());
}
this._screen.close();
this.dispose();
}
private async _cancelImport() {
this._resetImportDiffState();
if (this._uploadResult) {
await this._docComm.cancelImportFiles(
this._getTransformedDataSource(this._uploadResult), this._getHiddenTableIds());
}
this._screen.close();
this.dispose();
}
private _resetTableMergeOptions(tableId: string) {
this._mergeOptions[tableId]?.mergeCols.set([]);
}
private _validateImportConfiguration(): boolean {
let isValid = true;
const selectedSourceInfo = this._sourceInfoSelected.get();
if (!selectedSourceInfo) { return isValid; } // No configuration to validate.
const mergeOptions = this._mergeOptions[selectedSourceInfo.hiddenTableId];
if (!mergeOptions) { return isValid; } // No configuration to validate.
const {updateExistingRecords, mergeCols, hasInvalidMergeCols} = mergeOptions;
if (updateExistingRecords.get() && mergeCols.get().length === 0) {
hasInvalidMergeCols.set(true);
isValid = false;
}
return isValid;
}
private _buildModalTitle(rightElement?: DomContents) {
const title = this._importSourceElem ? this._importSourceElem.importSource.label : 'Import from file';
return cssModalHeader(cssModalTitle(title), rightElement);
}
/**
* Triggers an update of the import diff in the preview table. When called in quick succession,
* only the most recent call will result in an update being made to the preview table.
*
* NOTE: This method should not be called directly. Instead, use _updateImportDiff, which
* wraps this method and debounces it.
*
* @param {SourceInfo} info The source to update the diff for.
*/
private async _updateDiff(info: SourceInfo) {
const mergeOptions = this._mergeOptions[info.hiddenTableId]!;
this._isLoadingDiff.set(true);
if (!mergeOptions.updateExistingRecords.get() || mergeOptions.mergeCols.get().length === 0) {
// We can simply disable document comparison mode when merging isn't configured.
this._gristDoc.comparison = null;
} else {
// Request a diff of the current source and wait for a response.
const genImportDiffPromise = this._docComm.generateImportDiff(info.hiddenTableId,
this._createTransformRule(info), this._getMergeOptionsForSource(info)!);
this._lastGenImportDiffPromise = genImportDiffPromise;
const diff = await genImportDiffPromise;
// If the request is superseded by a newer request, or the Importer is disposed, do nothing.
if (this.isDisposed() || genImportDiffPromise !== this._lastGenImportDiffPromise) { return; }
// Otherwise, put the document in comparison mode with the diff data.
this._gristDoc.comparison = diff;
}
this._isLoadingDiff.set(false);
}
/**
* Resets all state variables related to diffs to their default values.
*/
private _resetImportDiffState() {
this._cancelPendingDiffRequests();
this._gristDoc.comparison = null;
}
/**
* Effectively cancels all pending diff requests by causing their fulfilled promises to
* be ignored by their attached handlers. Since we can't natively cancel the promises, this
* is functionally equivalent to canceling the outstanding requests.
*/
private _cancelPendingDiffRequests() {
this._updateImportDiff.cancel();
this._lastGenImportDiffPromise = null;
this._isLoadingDiff.set(false);
}
// The importer state showing import in progress, with a list of tables, and a preview.
private _renderMain(upload: UploadResult) {
const schema = this._parseOptions.get().SCHEMA;
this._screen.render([
this._buildModalTitle(
schema ? cssActionLink(cssLinkIcon('Settings'), 'Import options',
testId('importer-options-link'),
dom.on('click', () => this._renderParseOptions(schema, upload))
) : null,
),
cssPreviewWrapper(
cssTableList(
dom.forEach(this._sourceInfoArray, (info) => {
const destTableId = Computed.create(null, (use) => use(info.destTableId))
.onWrite(async (destId) => {
info.destTableId.set(destId);
this._resetTableMergeOptions(info.hiddenTableId);
await this._updateTransformSection(info);
});
return cssTableInfo(
dom.autoDispose(destTableId),
cssTableLine(cssToFrom('From'),
cssTableSource(getSourceDescription(info, upload), testId('importer-from'))),
cssTableLine(cssToFrom('To'), linkSelect<DestId>(destTableId, this._destTables)),
cssTableInfo.cls('-selected', (use) => use(this._sourceInfoSelected) === info),
dom.on('click', async () => {
if (info === this._sourceInfoSelected.get() || !this._validateImportConfiguration()) {
return;
}
this._cancelPendingDiffRequests();
this._sourceInfoSelected.set(info);
await this._updateDiff(info);
}),
testId('importer-source'),
);
}),
),
dom.maybe(this._sourceInfoSelected, (info) => {
const {mergeCols, updateExistingRecords, hasInvalidMergeCols} = this._mergeOptions[info.hiddenTableId]!;
return [
dom.maybe(info.destTableId, (_dest) => {
const updateRecordsListener = updateExistingRecords.addListener(async () => {
await this._updateImportDiff(info);
});
return cssMergeOptions(
cssMergeOptionsToggle(labeledSquareCheckbox(
updateExistingRecords,
'Update existing records',
dom.autoDispose(updateRecordsListener),
testId('importer-update-existing-records')
)),
dom.maybe(updateExistingRecords, () => [
cssMergeOptionsMessage(
'Imported rows will be merged with records that have the same values for all of these fields:',
testId('importer-merge-fields-message')
),
dom.domComputed(info.transformSection, section => {
const mergeColsListener = mergeCols.addListener(async val => {
// Reset the error state of the multiSelect on change.
if (val.length !== 0 && hasInvalidMergeCols.get()) {
hasInvalidMergeCols.set(false);
}
await this._updateImportDiff(info);
});
return multiSelect(
mergeCols,
section?.viewFields().peek().map(field => field.label()) ?? [],
{
placeholder: 'Select fields to match on',
error: hasInvalidMergeCols
},
dom.autoDispose(mergeColsListener),
testId('importer-merge-fields-select')
);
})
])
);
}),
cssSectionHeader('Preview'),
dom.domComputed(use => {
const previewSection = use(this._previewViewSection);
if (use(this._isLoadingDiff) || !previewSection) {
return cssPreviewSpinner(loadingSpinner());
}
const gridView = this._createPreview(previewSection);
// When changes are made to the preview table, update the import diff.
gridView.listenTo(gridView.sortedRows, 'rowNotify', async () => {
await this._updateImportDiff(info);
});
return cssPreviewGrid(
dom.autoDispose(gridView),
gridView.viewPane,
testId('importer-preview'),
);
})
];
}),
),
cssModalButtons(
bigPrimaryButton('Import',
dom.on('click', () => this._maybeFinishImport(upload)),
dom.boolAttr('disabled', use => use(this._previewViewSection) === null),
testId('modal-confirm'),
),
bigBasicButton('Cancel',
dom.on('click', () => this._cancelImport()),
testId('modal-cancel'),
),
),
]);
}
// The importer state showing parse options that may be changed.
private _renderParseOptions(schema: ParseOptionSchema[], upload: UploadResult) {
this._screen.render([
this._buildModalTitle(),
dom.create(buildParseOptionsForm, schema, this._parseOptions.get() as ParseOptionValues,
(p: ParseOptions) => {
this._parseOptions.set(p);
this._reImport(upload).catch((err) => reportError(err));
},
() => { this._renderMain(upload); },
)
]);
}
private async _fetchFromDrive(itemUrl: string) {
// First we will assume that this is public file, so no need to ask for permissions.
try {
return await fetchURL(this._docComm, itemUrl);
} catch(err) {
// It is not a public file or the file id in the url is wrong,
// but we have no way to check it, so we assume that it is private file
// and ask the user for the permission (if we are configured to do so)
if (canReadPrivateFiles()) {
const options: FetchUrlOptions = {};
try {
// Request for authorization code from Google.
const code = await getGoogleCodeForReading(this);
options.googleAuthorizationCode = code;
} catch(permError) {
if (permError?.message === ACCESS_DENIED) {
// User declined to give us full readonly permission, fallback to GoogleDrive plugin
// or cancel import if GoogleDrive plugin is not configured.
throw new GDriveUrlNotSupported(itemUrl);
} else if(permError?.message === AUTH_INTERRUPTED) {
// User closed the window - we assume he doesn't want to continue.
throw new CancelledError();
} else {
// Some other error happened during authentication, report to user.
throw err;
}
}
// Download file from private drive, if it fails, report the error to user.
return await fetchURL(this._docComm, itemUrl, options);
} else {
// We are not allowed to ask for full readonly permission, fallback to GoogleDrive plugin.
throw new GDriveUrlNotSupported(itemUrl);
}
}
}
}
// Used for switching from URL plugin to Google drive plugin.
class GDriveUrlNotSupported extends Error {
constructor(public url: string) {
super(`This url ${url} is not supported`);
}
}
// Used to cancel import (close the dialog without any error).
class CancelledError extends Error {
}
function getSourceDescription(sourceInfo: SourceInfo, upload: UploadResult) {
const origName = upload.files[sourceInfo.uploadFileIndex].origName;
return sourceInfo.origTableName ? origName + ' - ' + sourceInfo.origTableName : origName;
}
const cssActionLink = styled('div', `
display: inline-flex;
align-items: center;
cursor: pointer;
color: ${colors.lightGreen};
--icon-color: ${colors.lightGreen};
&:hover {
color: ${colors.darkGreen};
--icon-color: ${colors.darkGreen};
}
`);
const cssLinkIcon = styled(icon, `
flex: none;
margin-right: 4px;
`);
const cssModalHeader = styled('div', `
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
& > .${cssModalTitle.className} {
margin-bottom: 0px;
}
`);
const cssPreviewWrapper = styled('div', `
width: 600px;
padding: 8px 12px 8px 0;
overflow-y: auto;
`);
// This partly duplicates cssSectionHeader from HomeLeftPane.ts
const cssSectionHeader = styled('div', `
margin-bottom: 8px;
color: ${colors.slate};
text-transform: uppercase;
font-weight: 500;
font-size: ${vars.xsmallFontSize};
letter-spacing: 1px;
`);
const cssTableList = styled('div', `
display: flex;
flex-flow: row wrap;
justify-content: space-between;
margin-bottom: 16px;
align-items: flex-start;
`);
const cssTableInfo = styled('div', `
padding: 4px 8px;
margin: 4px 0px;
width: calc(50% - 16px);
border-radius: 3px;
border: 1px solid ${colors.darkGrey};
&:hover, &-selected {
background-color: ${colors.mediumGrey};
}
`);
const cssTableLine = styled('div', `
display: flex;
align-items: center;
margin: 4px 0;
`);
const cssToFrom = styled('span', `
flex: none;
margin-right: 8px;
color: ${colors.slate};
text-transform: uppercase;
font-weight: 500;
font-size: ${vars.xsmallFontSize};
letter-spacing: 1px;
width: 40px;
text-align: right;
`);
const cssTableSource = styled('div', `
overflow-wrap: anywhere;
`);
const cssPreview = styled('div', `
display: flex;
height: 300px;
`);
const cssPreviewSpinner = styled(cssPreview, `
align-items: center;
justify-content: center;
`);
const cssPreviewGrid = styled(cssPreview, `
border: 1px solid ${colors.darkGrey};
`);
const cssMergeOptions = styled('div', `
margin-bottom: 16px;
`);
const cssMergeOptionsToggle = styled('div', `
margin-bottom: 8px;
`);
const cssMergeOptionsMessage = styled('div', `
color: ${colors.slate};
margin-bottom: 8px;
`); | the_stack |
import * as pkcs11 from "pkcs11js";
import * as core from "./core";
import { MechanismType, Mechanism } from './mech';
import { SessionObject, SessionObjectCollection, ObjectClass } from "./object";
import * as objects from "./objects";
import { Key, SecretKey } from './objects';
import { Slot } from "./slot";
import { ITemplate, Template } from "./template";
import { Callback } from "./types";
import { Cipher, Decipher, Digest, Sign, Verify } from "./crypto";
export enum SessionFlag {
/**
* `True` if the session is read/write; `false` if the session is read-only
*/
RW_SESSION = 2,
/**
* This flag is provided for backward compatibility, and should always be set to `true`
*/
SERIAL_SESSION = 4,
}
/**
* Enumeration specifies user types
*/
export enum UserType {
/**
* Security Officer
*/
SO,
/**
* User
*/
USER,
/**
* Context specific
*/
CONTEXT_SPECIFIC,
}
/**
* Structure of asymmetric key pair
*/
export interface IKeyPair {
privateKey: objects.PrivateKey;
publicKey: objects.PublicKey;
}
type SessionFindCallback = (obj: SessionObject, index: number) => any;
/**
* Provides information about a session
*/
export class Session extends core.HandleObject {
/**
* Slot
*
* @type {Slot}
*/
public slot: Slot;
/**
* The state of the session
*/
public state: number;
/**
* Bit flags that define the type of session
*/
public flags: number;
/**
* An error code defined by the cryptographic device. Used for errors not covered by Cryptoki
*/
public deviceError: number;
/**
* Creates a new instance of {@link Session}
* @param handle ID of slot's session
* @param slot PKCS#11 slot
* @param lib PKCS#11 module
*/
constructor(handle: core.Handle, slot: Slot, lib: pkcs11.PKCS11) {
super(handle, lib);
this.slot = slot;
this.getInfo();
}
/**
* Closes a session between an application and a token
*/
public close() {
this.lib.C_CloseSession(this.handle);
}
/**
* Initializes the normal user's PIN
* @param pin the normal user's PIN
*/
public initPin(pin: string) {
this.lib.C_InitPIN(this.handle, pin);
}
/**
* modifies the PIN of the user who is logged in
* @param oldPin The old PIN
* @param newPin The new PIN
*/
public setPin(oldPin: string, newPin: string) {
this.lib.C_SetPIN(this.handle, oldPin, newPin);
}
/**
* Obtains a copy of the cryptographic operations state of a session, encoded as a string of bytes
*/
public getOperationState(): Buffer {
throw new Error("Not implemented");
}
/**
* Restores the cryptographic operations state of a session
* from a string of bytes obtained with getOperationState
* @param state the saved state
* @param encryptionKey holds key which will be used for an ongoing encryption
* or decryption operation in the restored session
* (or 0 if no encryption or decryption key is needed,
* either because no such operation is ongoing in the stored session
* or because all the necessary key information is present in the saved state)
* @param authenticationKey holds a handle to the key which will be used for an ongoing signature,
* MACing, or verification operation in the restored session
* (or 0 if no such key is needed, either because no such operation is ongoing in the stored session
* or because all the necessary key information is present in the saved state)
*/
public setOperationState(state: Buffer, encryptionKey: number = 0, authenticationKey: number = 0) {
throw new Error("Not implemented");
}
/**
* Logs a user into a token
* @param pin the user's PIN.
* - This standard allows PIN values to contain any valid `UTF8` character,
* but the token may impose subset restrictions
* @param userType the user type. Default is {@link UserType.USER}
*/
public login(pin: string, userType: UserType = UserType.USER) {
this.lib.C_Login(this.handle, userType, pin);
}
/**
* logs a user out from a token
*/
public logout() {
this.lib.C_Logout(this.handle);
}
/**
* creates a new object
* - Only session objects can be created during a read-only session.
* - Only public objects can be created unless the normal user is logged in.
* @param template the object's template
* @returns The new instance of {@link SessionObject}
*/
public create(template: ITemplate): SessionObject {
const tmpl = Template.toPkcs11(template);
const hObject = this.lib.C_CreateObject(this.handle, tmpl);
return new SessionObject(hObject, this, this.lib);
}
/**
* Copies an object, creating a new object for the copy
* @param object the copied object
* @param template template for new object
* @returns The new instance of {@link SessionObject}
*/
public copy(object: SessionObject, template: ITemplate): SessionObject {
const tmpl = Template.toPkcs11(template);
const hObject = this.lib.C_CopyObject(this.handle, object.handle, tmpl);
return new SessionObject(hObject, this, this.lib);
}
/**
* Removes all session objects matched to template
* @param template The list of attributes
* @returns The number of destroyed objects
*/
public destroy(template: ITemplate): number;
/**
* Removes the specified session object
* @param object Object for destroying
* @returns The number of destroyed objects
*/
public destroy(object: SessionObject): number;
/**
* Removes all session objects
* @returns The number of destroyed objects
*/
public destroy(): number;
public destroy(param?: SessionObject | ITemplate): number {
if (param instanceof SessionObject) {
// destroy(object: SessionObject): number;
this.lib.C_DestroyObject(this.handle, param.handle);
return 1;
} else {
const objs = this.find(param || null);
const removed = objs.length;
for (let i = 0; i < objs.length; i++) {
objs.items(i).destroy();
}
return removed;
}
}
/**
* Removes all session objects
* @returns The number of destroyed objects
*/
public clear(): number {
return this.destroy();
}
/**
* Returns a collection of session objects matched to template
* @param template Th list of attributes
* @param callback Optional callback function which is called for each founded object
* - if callback function returns `false`, it breaks find function.
* @returns Th collection of session objects
*/
public find(): SessionObjectCollection;
public find(callback: SessionFindCallback): SessionObjectCollection;
public find(template?: ITemplate | null, callback?: SessionFindCallback): SessionObjectCollection;
public find(
template: ITemplate | SessionFindCallback | null = null,
callback?: SessionFindCallback,
): SessionObjectCollection {
if (core.isFunction(template)) {
callback = template as SessionFindCallback;
template = null;
}
const tmpl = Template.toPkcs11(template);
this.lib.C_FindObjectsInit(this.handle, tmpl);
const handles: core.Handle[] = [];
try {
while (true) {
const hObject = this.lib.C_FindObjects(this.handle);
if (!hObject) {
break;
}
if (callback && callback(new SessionObject(hObject, this, this.lib), handles.length) === false) {
break;
}
handles.push(hObject);
}
} catch (error) {
this.lib.C_FindObjectsFinal(this.handle);
throw (error);
}
this.lib.C_FindObjectsFinal(this.handle);
return new SessionObjectCollection(handles, this, this.lib);
}
/**
* Returns object from session by handle
* @param handle handle of object
* @returns The session object or null
*/
public getObject<T extends SessionObject>(handle: core.Handle): T | null {
let res: SessionObject | undefined;
this.find((obj) => {
const compare = obj.handle.compare(handle);
if (compare === 0) {
res = obj;
return false;
}
});
if (res) {
return res.toType<T>();
} else {
return null;
}
}
/**
* Generates a secret key or set of domain parameters, creating a new object.
* @param mechanism Generation mechanism
* @param template Template for the new key or set of domain parameters
* @returns The secret key
*/
public generateKey(mechanism: MechanismType, template?: ITemplate): objects.SecretKey;
/**
* Generates a secret key or set of domain parameters, creating a new object.
* @param mechanism Generation mechanism
* @param template Template for the new key or set of domain parameters
* @param callback Async callback with generated key
*/
public generateKey(mechanism: MechanismType, template: ITemplate, callback: Callback<Error, objects.SecretKey>): void;
public generateKey(
mechanism: MechanismType,
template: ITemplate | null = null,
callback?: Callback<Error, objects.SecretKey>,
): objects.SecretKey | void {
try {
const pMech = Mechanism.create(mechanism);
// init default template params
if (template) {
template.class = ObjectClass.SECRET_KEY;
}
const pTemplate = Template.toPkcs11(template);
if (callback) {
this.lib.C_GenerateKey(this.handle, pMech, pTemplate, (err, hKey) => {
if (err) {
callback(err, null);
} else {
// Wrap handle of kry to SecretKey
const obj = new SessionObject(hKey, this, this.lib);
callback(null, obj.toType<objects.SecretKey>());
}
});
} else {
const hKey = this.lib.C_GenerateKey(this.handle, pMech, pTemplate);
// Wrap handle of kry to SecretKey
const obj = new SessionObject(hKey, this, this.lib);
return obj.toType<objects.SecretKey>();
}
} catch (e) {
if (callback) {
callback(e, null);
} else {
throw e;
}
}
}
/**
* Generates an asymmetric key pair
* @param mechanism Generation mechanism
* @param publicTemplate The public key template
* @param privateTemplate The private key template
* @returns The generated key pair
*/
public generateKeyPair(mechanism: MechanismType, publicTemplate: ITemplate, privateTemplate: ITemplate): IKeyPair;
/**
* Generates an asymmetric key pair
* @param mechanism Generation mechanism
* @param publicTemplate The public key template
* @param privateTemplate The private key template
* @param callback Async callback with generated key pair
*/
public generateKeyPair(
mechanism: MechanismType,
publicTemplate: ITemplate,
privateTemplate: ITemplate,
callback: Callback<Error, IKeyPair>,
): void;
public generateKeyPair(
mechanism: MechanismType,
publicTemplate: ITemplate,
privateTemplate: ITemplate,
callback?: Callback<Error, IKeyPair>,
): IKeyPair | void {
try {
const pMech = Mechanism.create(mechanism);
// init default public key template
if (publicTemplate) {
publicTemplate.class = ObjectClass.PUBLIC_KEY;
}
const pubTmpl = Template.toPkcs11(publicTemplate);
// init default private key template
if (privateTemplate) {
privateTemplate.class = ObjectClass.PRIVATE_KEY;
privateTemplate.private = true;
}
const prvTmpl = Template.toPkcs11(privateTemplate);
if (callback) {
// async
this.lib.C_GenerateKeyPair(
this.handle, pMech,
pubTmpl,
prvTmpl,
(err, keys) => {
if (err) {
callback(err, null);
} else {
if (keys) {
callback(null, {
publicKey: new objects.PublicKey(keys.publicKey, this, this.lib),
privateKey: new objects.PrivateKey(keys.privateKey, this, this.lib),
});
}
}
});
} else {
// sync
const keys = this.lib.C_GenerateKeyPair(this.handle, pMech, pubTmpl, prvTmpl);
return {
publicKey: new objects.PublicKey(keys.publicKey, this, this.lib),
privateKey: new objects.PrivateKey(keys.privateKey, this, this.lib),
};
}
} catch (e) {
if (callback) {
callback(e, null);
} else {
throw e;
}
}
}
/**
* Creates the signing operation
* @param alg The signing mechanism
* @param key The signing key
* @returns Signing operation
*/
public createSign(alg: MechanismType, key: Key): Sign {
return new Sign(this, alg, key, this.lib);
}
/**
* Creates the verifying operation
* @param alg The verifying mechanism
* @param key The verifying key
*/
public createVerify(alg: MechanismType, key: Key): Verify {
return new Verify(this, alg, key, this.lib);
}
/**
* Creates the encryption operation
* @param alg The encryption mechanism
* @param key The encryption key
* @returns The encryption operation
*/
public createCipher(alg: MechanismType, key: Key): Cipher {
return new Cipher(this, alg, key, this.lib);
}
/**
* Creates the decryption operation
* @param alg The decryption mechanism
* @param key The decryption key
* @param blockSize Block size in bytes
* @returns The decryption operation
*/
public createDecipher(alg: MechanismType, key: Key, blockSize?: number): Decipher {
return new Decipher(this, alg, key, blockSize || 0, this.lib);
}
/**
* Creates the digest operation
* @param alg The digest mechanism
* @return The digest operation
*/
public createDigest(alg: MechanismType): Digest {
return new Digest(this, alg, this.lib);
}
/**
* Wraps (i.e., encrypts) a key
* @param alg Wrapping mechanism
* @param wrappingKey Wrapping key
* @param key Key to be wrapped
* @returns Wrapped key
*/
public wrapKey(alg: MechanismType, wrappingKey: Key, key: Key): Buffer;
/**
* Wraps (i.e., encrypts) a key
* @param alg Wrapping mechanism
* @param wrappingKey Wrapping key
* @param key Key to be wrapped
* @param callback Async callback function with wrapped key
*/
public wrapKey(alg: MechanismType, wrappingKey: Key, key: Key, callback: Callback<Error, Buffer>): void;
public wrapKey(alg: MechanismType, wrappingKey: Key, key: Key, callback?: Callback<Error, Buffer>): Buffer | void {
try {
const pMech = Mechanism.create(alg);
let wrappedKey = Buffer.alloc(8096);
if (callback) {
// async
this.lib.C_WrapKey(this.handle, pMech, wrappingKey.handle, key.handle, wrappedKey, callback);
} else {
// sync
wrappedKey = this.lib.C_WrapKey(this.handle, pMech, wrappingKey.handle, key.handle, wrappedKey);
return wrappedKey;
}
} catch (e) {
if (callback) {
callback(e, null);
} else {
throw e;
}
}
}
/**
* Unwraps (decrypts) a wrapped key
* @param alg Unwrapping mechanism
* @param unwrappingKey Unwrapping key
* @param wrappedKey Wrapped key
* @param template New key template
* @returns Unwrapped key
*/
public unwrapKey(alg: MechanismType, unwrappingKey: Key, wrappedKey: Buffer, template: ITemplate): Key;
public unwrapKey(
alg: MechanismType,
unwrappingKey: Key,
wrappedKey: Buffer,
template: ITemplate,
callback: Callback<Error, Key>,
): void;
/**
* Unwraps (decrypts) a wrapped key
* @param alg Unwrapping mechanism
* @param unwrappingKey Unwrapping key
* @param wrappedKey Wrapped key
* @param template New key template
* @param callback Async callback function with unwrapped key
*/
public unwrapKey(
alg: MechanismType,
unwrappingKey: Key,
wrappedKey: Buffer,
template: ITemplate,
callback?: Callback<Error, Key>,
): Key | void {
try {
const pMech = Mechanism.create(alg);
const pTemplate = Template.toPkcs11(template);
if (callback) {
// async
this.lib.C_UnwrapKey(this.handle, pMech, unwrappingKey.handle, wrappedKey, pTemplate, (err, hKey) => {
if (err) {
callback(err, null);
} else {
callback(null, new Key(hKey, this, this.lib));
}
});
} else {
// sync
const hKey = this.lib.C_UnwrapKey(this.handle, pMech, unwrappingKey.handle, wrappedKey, pTemplate);
return new Key(hKey, this, this.lib);
}
} catch (e) {
if (callback) {
callback(e, null);
} else {
throw e;
}
}
}
/**
* Derives a key from a base key
* @param alg Key derivation mech
* @param baseKey Base key
* @param template New key template
* @returns Derived key
*/
public deriveKey(alg: MechanismType, baseKey: Key, template: ITemplate): SecretKey;
/**
* Derives a key from a base key
* @param alg Key derivation mech
* @param baseKey Base key
* @param template New key template
* @param callback Async callback function with derived key
*/
public deriveKey(alg: MechanismType, baseKey: Key, template: ITemplate, callback: Callback<Error, Key>): void;
public deriveKey(
alg: MechanismType,
baseKey: Key,
template: ITemplate,
callback?: Callback<Error, Key>,
): SecretKey | void {
try {
const pMech = Mechanism.create(alg);
const pTemplate = Template.toPkcs11(template);
if (callback) {
this.lib.C_DeriveKey(this.handle, pMech, baseKey.handle, pTemplate, (err, hKey) => {
if (err) {
callback(err, null);
} else {
callback(null, new SecretKey(hKey, this, this.lib));
}
});
} else {
const hKey = this.lib.C_DeriveKey(this.handle, pMech, baseKey.handle, pTemplate);
return new SecretKey(hKey, this, this.lib);
}
} catch (e) {
if (callback) {
callback(e, null);
} else {
throw e;
}
}
}
/**
* Generates random data
* @param size Amount of bytes to generate
* @returns New byte array
*/
public generateRandom(size: number): Buffer {
const buf = Buffer.alloc(size);
this.lib.C_GenerateRandom(this.handle, buf);
return buf;
}
protected getInfo() {
const info = this.lib.C_GetSessionInfo(this.handle);
this.state = info.state;
this.flags = info.flags;
this.deviceError = info.deviceError;
}
} | the_stack |
import { describe, it } from "mocha";
import { assert } from "chai";
import rewire from "rewire";
import sinon from "sinon";
import { runHashTests } from "./common";
import { Int_64 } from "../../src/primitives_64";
import {
CSHAKEOptionsNoEncodingType,
CSHAKEOptionsEncodingType,
KMACOptionsNoEncodingType,
KMACOptionsEncodingType,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
} from "../../src/custom_types";
import {
NISTCSHAKERoundIn,
CSHAKEWithFuncRoundIn,
newState,
NISTSHA3Round1In,
NISTSHA3Round1Out,
NISTSHA3Round2In,
NISTSHA3Round2Out,
SHAKE128Len2048Out,
NISTKMACCustomizationRound1In,
NISTKMACCustomizationRound2In,
} from "./test_sha3_consts";
const sha3 = rewire("../../src/sha3");
type VariantNoCSHAKEType = "SHA3-224" | "SHA3-256" | "SHA3-384" | "SHA3-512" | "SHAKE128" | "SHAKE256";
const getNewState = sha3.__get__("getNewState");
describe("Test left_encode", () => {
const left_encode = sha3.__get__("left_encode");
it("For 0-byte Value", () => {
assert.deepEqual(left_encode(0), { value: [0x00000001], binLen: 16 });
});
it("For 1-byte Value", () => {
assert.deepEqual(left_encode(0x11), { value: [0x000001101], binLen: 16 });
});
it("For 2-byte Value", () => {
assert.deepEqual(left_encode(0x1122), { value: [0x000221102], binLen: 24 });
});
it("For 3-byte Value", () => {
assert.deepEqual(left_encode(0x112233), { value: [0x33221103], binLen: 32 });
});
it("For 4-byte Value", () => {
assert.deepEqual(left_encode(0x11223344), { value: [0x33221104, 0x00000044], binLen: 40 });
});
it("For 7-byte Value", () => {
/* 4822678189205111 === 0x0011223344556677 */
assert.deepEqual(left_encode(4822678189205111), { value: [0x33221107 | 0, 0x77665544 | 0], binLen: 64 });
});
});
describe("Test right_encode", () => {
const right_encode = sha3.__get__("right_encode");
it("For 0-byte Value", () => {
assert.deepEqual(right_encode(0), { value: [0x00000100], binLen: 16 });
});
it("For 1-byte Value", () => {
assert.deepEqual(right_encode(0x11), { value: [0x000000111], binLen: 16 });
});
it("For 2-byte Value", () => {
assert.deepEqual(right_encode(0x1122), { value: [0x00022211], binLen: 24 });
});
it("For 3-byte Value", () => {
assert.deepEqual(right_encode(0x112233), { value: [0x03332211], binLen: 32 });
});
it("For 4-byte Value", () => {
assert.deepEqual(right_encode(0x11223344), { value: [0x44332211, 0x00000004], binLen: 40 });
});
it("For 7-byte Value", () => {
/* 4822678189205111 === 0x0011223344556677 */
assert.deepEqual(right_encode(4822678189205111), { value: [0x44332211 | 0, 0x07776655], binLen: 64 });
});
});
describe("Test encode_string", () => {
let i, arr: number[];
const encode_string = sha3.__get__("encode_string");
it("For 0-bit Input", () => {
assert.deepEqual(encode_string({ value: [], binLen: 0 }), { value: [0x00000001], binLen: 16 });
});
it("For 16-bit Input", () => {
/* This checks values that can be encoded in a single int */
assert.deepEqual(encode_string({ value: [0x1122], binLen: 16 }), { value: [0x11221001], binLen: 32 });
});
it("For 24-bit Input", () => {
/* This checks values that can be encoded in 2 ints (and left_encode returns a 16-bit value) */
assert.deepEqual(encode_string({ value: [0x112233], binLen: 24 }), { value: [0x22331801, 0x00000011], binLen: 40 });
});
it("For 256-bit Input", () => {
/* This hits on the case that left_encode returns a 24-bit value */
arr = [];
const retVal = [0x41000102];
for (i = 0; i < 8; i++) {
arr.push(0x41414141);
}
for (i = 0; i < 7; i++) {
retVal.push(0x41414141);
}
retVal.push(0x00414141);
assert.deepEqual(encode_string({ value: arr, binLen: 256 }), { value: retVal, binLen: 280 });
});
it("For 65536-bit Input", () => {
/* This hits on the case that left_encode returns a 32-bit value */
arr = [];
for (i = 0; i < 2048; i++) {
arr.push(0x41414141);
}
assert.deepEqual(encode_string({ value: arr, binLen: 65536 }), { value: [0x00000103].concat(arr), binLen: 65568 });
});
it("For 16777216-bit Input", () => {
/* This hits on the case that left_encode returns a 40-bit value */
arr = [];
for (i = 0; i < 524288; i++) {
arr.push(0x41414141);
}
const retVal = encode_string({ value: arr, binLen: 16777216 });
/* It's extremely time prohibitive to check all the middle bits so just check the interesting ends */
assert.equal(retVal["value"][0], [0x00000104]);
assert.equal(retVal["value"][1], [0x41414100]);
assert.equal(retVal["value"].length, 524288 + 2);
assert.equal(retVal["value"][retVal["value"].length - 1], [0x00000041]);
assert.equal(retVal["binLen"], 16777256);
});
});
describe("Test byte_pad", () => {
const byte_pad = sha3.__get__("byte_pad");
it("For 2-byte Value Padded to 4-bytes", () => {
assert.deepEqual(byte_pad({ value: [0x00001122], binLen: 16 }, 4), [0x11220401]);
});
it("For 2-byte Value Padded to 8-bytes", () => {
assert.deepEqual(byte_pad({ value: [0x00001122], binLen: 16 }, 8), [0x11220801, 0]);
});
it("For 4-byte Value Padded to 8-bytes", () => {
assert.deepEqual(byte_pad({ value: [0x11223344], binLen: 32 }, 8), [0x33440801, 0x00001122]);
});
it("For 6-byte Value Padded to 8-bytes", () => {
assert.deepEqual(byte_pad({ value: [0x44332211, 0x00006655], binLen: 48 }, 8), [0x22110801, 0x66554433]);
});
});
describe("Test resolveCSHAKEOptions", () => {
const resolveCSHAKEOptions = sha3.__get__("resolveCSHAKEOptions");
it("With No Input", () => {
assert.deepEqual(resolveCSHAKEOptions(), {
funcName: { value: [], binLen: 0 },
customization: { value: [], binLen: 0 },
});
});
it("With customization Specified", () => {
assert.deepEqual(resolveCSHAKEOptions({ customization: { value: "00112233", format: "HEX" } }), {
funcName: { value: [], binLen: 0 },
customization: { value: [0x33221100], binLen: 32 },
});
});
it("With funcName Specified", () => {
assert.deepEqual(resolveCSHAKEOptions({ funcName: { value: "00112233", format: "HEX" } }), {
customization: { value: [], binLen: 0 },
funcName: { value: [0x33221100], binLen: 32 },
});
});
});
describe("Test resolveKMACOptions", () => {
const resolveKMACOptions = sha3.__get__("resolveKMACOptions");
it("With No Input", () => {
assert.throws(() => {
resolveKMACOptions();
}, "kmacKey must include a value and format");
});
it("With customization Specified", () => {
assert.deepEqual(
resolveKMACOptions({
kmacKey: { value: "44556677", format: "HEX" },
customization: { value: "00112233", format: "HEX" },
}),
{
funcName: { value: [0x43414d4b], binLen: 32 },
customization: { value: [0x33221100], binLen: 32 },
kmacKey: { value: [0x77665544], binLen: 32 },
}
);
});
it("With funcName Specified", () => {
assert.deepEqual(
resolveKMACOptions({
kmacKey: { value: "44556677", format: "HEX" },
funcName: { value: "00112233", format: "HEX" },
}),
{
funcName: { value: [0x43414d4b], binLen: 32 },
customization: { value: [], binLen: 0 },
kmacKey: { value: [0x77665544], binLen: 32 },
}
);
});
});
describe("Test getNewState", () => {
it("For All Variants", () => {
assert.deepEqual(getNewState("SHA3-224"), newState);
});
});
describe("Test cloneSHA3State", () => {
const cloneSHA3State = sha3.__get__("cloneSHA3State");
const state = [
[new Int_64(0, 1), new Int_64(0, 2), new Int_64(0, 3), new Int_64(0, 4), new Int_64(0, 5)],
[new Int_64(0, 6), new Int_64(0, 7), new Int_64(0, 8), new Int_64(0, 9), new Int_64(0, 0xa)],
[new Int_64(0, 0xb), new Int_64(0, 0xc), new Int_64(0, 0xd), new Int_64(0, 0xb), new Int_64(0, 0xf)],
[new Int_64(0, 0x10), new Int_64(0, 0x11), new Int_64(0, 0x12), new Int_64(0, 0x3), new Int_64(0, 0x14)],
[new Int_64(0, 0x15), new Int_64(0, 0x16), new Int_64(0, 0x17), new Int_64(0, 0x18), new Int_64(0, 0x19)],
];
it("For All Variants", () => {
assert.notEqual(cloneSHA3State(state), state);
assert.deepEqual(cloneSHA3State(state), state);
});
});
describe("Test roundSHA3", () => {
it("With NIST Test Inputs", () => {
assert.deepEqual(sha3.__get__("roundSHA3")(NISTSHA3Round1In.slice(), getNewState()), NISTSHA3Round1Out);
});
});
describe("Test finalizeSHA3", () => {
it("With NIST Test Inputs", () => {
const roundStub = sinon.stub().onCall(0).returns(NISTSHA3Round1Out).onCall(1).returns(NISTSHA3Round2Out);
sha3.__with__({ roundSHA3: roundStub })(() => {
assert.deepEqual(
sha3.__get__("finalizeSHA3")(
NISTSHA3Round1In.concat(NISTSHA3Round2In),
1600,
-1,
getNewState(),
1152,
0x06,
224
),
[0x6a817693, 0x723f50ba, 0xebe76cf9, 0x5d09ac65, 0x4bbee3ee, 0xa1c2bbf9, 0xe0117ecb]
);
});
});
it("With outputLen Greater Than Blocksize", () => {
// This is emulating SHAKE128 */
assert.deepEqual(
sha3.__get__("finalizeSHA3")(
NISTSHA3Round1In.concat(NISTSHA3Round2In),
1600,
-1,
getNewState(),
1344,
0x1f,
2048
),
SHAKE128Len2048Out
);
});
});
describe("Test jsSHA(SHA3)", () => {
const jsSHA = sha3.__get__("jsSHA");
class jsSHAATest extends jsSHA {
constructor(variant: VariantNoCSHAKEType, inputFormat: "TEXT", options?: FixedLengthOptionsEncodingType);
constructor(
variant: VariantNoCSHAKEType,
inputFormat: FormatNoTextType,
options?: FixedLengthOptionsNoEncodingType
);
constructor(variant: "CSHAKE128" | "CSHAKE256", inputFormat: "TEXT", options?: CSHAKEOptionsEncodingType);
constructor(
variant: "CSHAKE128" | "CSHAKE256",
inputFormat: FormatNoTextType,
options?: CSHAKEOptionsNoEncodingType
);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: "TEXT", options: KMACOptionsEncodingType);
constructor(variant: "KMAC128" | "KMAC256", inputFormat: FormatNoTextType, options: KMACOptionsNoEncodingType);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(variant: any, inputFormat: any, options?: any) {
super(variant, inputFormat, options);
}
/*
* Dirty hack function to expose the protected members of jsSHABase
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getter(propName: string): any {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore - Override "any" ban as this is only used in testing
return this[propName];
}
/*
* Dirty hack function to expose the protected members of jsSHABase
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setter(propName: string, value: any): void {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore - Override "any" ban as this is only used in testing
this[propName] = value;
}
}
[
{
variant: "SHA3-224",
outputBinLen: 224,
variantBlockSize: 1152,
delimiter: 0x06,
HMACSupported: true,
isVariableLen: false,
},
{
variant: "SHA3-256",
outputBinLen: 256,
variantBlockSize: 1088,
delimiter: 0x06,
HMACSupported: true,
isVariableLen: false,
},
{
variant: "SHA3-384",
outputBinLen: 384,
variantBlockSize: 832,
delimiter: 0x06,
HMACSupported: true,
isVariableLen: false,
},
{
variant: "SHA3-512",
outputBinLen: 512,
variantBlockSize: 576,
delimiter: 0x06,
HMACSupported: true,
isVariableLen: false,
},
{
variant: "SHAKE128",
outputBinLen: -1,
variantBlockSize: 1344,
delimiter: 0x1f,
HMACSupported: false,
isVariableLen: true,
},
{
variant: "SHAKE256",
outputBinLen: -1,
variantBlockSize: 1088,
delimiter: 0x1f,
HMACSupported: false,
isVariableLen: true,
},
{
// Test whether empty customization + function-name "reverts" CSHAKE to SHAKE
variant: "CSHAKE128",
outputBinLen: -1,
variantBlockSize: 1344,
delimiter: 0x1f,
isVariableLen: true,
HMACSupported: false,
customization: { value: "", format: "TEXT" },
},
{
// Test whether empty customization + function-name "reverts" CSHAKE to SHAKE
variant: "CSHAKE256",
outputBinLen: -1,
variantBlockSize: 1088,
delimiter: 0x1f,
isVariableLen: true,
HMACSupported: false,
customization: { value: "", format: "TEXT" },
},
{
variant: "CSHAKE128",
outputBinLen: -1,
variantBlockSize: 1344,
delimiter: 0x04,
isVariableLen: true,
HMACSupported: false,
customization: { value: "a", format: "TEXT" },
},
{
variant: "CSHAKE256",
outputBinLen: -1,
variantBlockSize: 1088,
delimiter: 0x04,
isVariableLen: true,
HMACSupported: false,
customization: { value: "a", format: "TEXT" },
},
{
variant: "KMAC128",
outputBinLen: -1,
variantBlockSize: 1344,
delimiter: 0x04,
isVariableLen: true,
HMACSupported: false,
kmacKey: { value: "a", format: "TEXT" },
},
{
variant: "KMAC256",
outputBinLen: -1,
variantBlockSize: 1088,
delimiter: 0x04,
isVariableLen: true,
HMACSupported: false,
kmacKey: { value: "a", format: "TEXT" },
},
].forEach((test) => {
it(`${test.variant} State Initialization`, () => {
/*
* Check a few basic things:
* 1. All of the variant parameters are correct
* 2. Calling stateClone function returns a *copy* of the state
* 3. Calling roundFunc, newStateFunc, and finalizeFunc call the expected functions
*/
sinon.reset();
const roundFuncSpy = sinon.spy(),
finalizeFuncSpy = sinon.spy(),
newStateFuncSpy = sinon.spy();
sha3.__with__({ roundSHA3: roundFuncSpy, finalizeSHA3: finalizeFuncSpy, getNewState: newStateFuncSpy })(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
const hash = new jsSHAATest(test.variant, "HEX", { customization: test.customization, kmacKey: test.kmacKey });
// Check #1
assert.equal(hash.getter("bigEndianMod"), 1);
assert.equal(hash.getter("variantBlockSize"), test.variantBlockSize);
assert.equal(hash.getter("outputBinLen"), test.outputBinLen);
assert.equal(hash.getter("isVariableLen"), test.isVariableLen);
assert.equal(hash.getter("HMACSupported"), test.HMACSupported);
// Check #2
const state = [[0xdeadbeef], [0xdeadbeef], [0xdeadbeef], [0xdeadbeef], [0xdeadbeef]];
const clonedState = hash.getter("stateCloneFunc")(state);
assert.notEqual(state, clonedState);
assert.deepEqual(state, clonedState);
// Check #3
hash.getter("roundFunc")([0xdeadbeef], [[0xfacefeed]]);
assert.isTrue(roundFuncSpy.lastCall.calledWithExactly([0xdeadbeef], [[0xfacefeed]]));
//hash.getter("newStateFunc")(test.variant);
assert.isTrue(newStateFuncSpy.lastCall.calledWithExactly(test.variant));
hash.getter("finalizeFunc")([0xdeadbeef], 32, 0, [[0xfacefeed]], test.outputBinLen);
assert.isTrue(
finalizeFuncSpy.lastCall.calledWithExactly(
[0xdeadbeef],
32,
0,
[[0xfacefeed]],
test.variantBlockSize,
test.delimiter,
test.outputBinLen
)
);
});
});
});
it("CSHAKE Without Options", () => {
const hash = new jsSHAATest("CSHAKE128", "HEX");
/* funcName and customization are both empty so nothing should be processed */
assert.deepEqual(hash.getter("intermediateState"), newState);
assert.equal(hash.getter("processedLen"), 0);
});
it("CSHAKE With Customization", () => {
const roundSpy = sinon.spy();
sha3.__with__({ roundSHA3: roundSpy })(() => {
const hash = new jsSHAATest("CSHAKE128", "HEX", { customization: { value: "Email Signature", format: "TEXT" } });
assert.isTrue(roundSpy.calledOnceWithExactly(NISTCSHAKERoundIn, newState.slice()));
assert.equal(hash.getter("processedLen"), hash.getter("variantBlockSize"));
});
});
it("CSHAKE With function-name", () => {
const roundSpy = sinon.spy();
sha3.__with__({ roundSHA3: roundSpy })(() => {
const hash = new jsSHAATest("CSHAKE128", "HEX", { funcName: { value: "TEST", format: "TEXT" } });
assert.isTrue(roundSpy.calledOnceWithExactly(CSHAKEWithFuncRoundIn, newState.slice()));
assert.equal(hash.getter("processedLen"), hash.getter("variantBlockSize"));
});
});
it("KMAC128 With Customization", () => {
const roundSpy = sinon.spy();
sha3.__with__({ roundSHA3: roundSpy })(() => {
const hash = new jsSHAATest("KMAC128", "HEX", {
customization: { value: "My Tagged Application", format: "TEXT" },
kmacKey: { value: "404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F", format: "HEX" },
});
assert.isTrue(roundSpy.getCall(0).calledWith(NISTKMACCustomizationRound1In));
assert.isTrue(roundSpy.getCall(1).calledWith(NISTKMACCustomizationRound2In));
assert.equal(hash.getter("processedLen"), 2 * hash.getter("variantBlockSize"));
});
});
it("With Invalid Variant", () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore - Deliberate bad variant value to test exceptions
assert.throws(() => new jsSHA("SHA-TEST", "HEX"), "Chosen SHA variant is not supported");
});
it("CSHAKE With numRounds", () => {
assert.throws(() => new jsSHA("CSHAKE128", "HEX", { numRounds: 2 }), "Cannot set numRounds for CSHAKE variants");
});
it("CSHAKE Without Customization Value", () => {
assert.throws(
() => new jsSHA("CSHAKE128", "HEX", { customization: { format: "TEXT" } }),
"Customization must include a value and format"
);
});
it("CSHAKE Without Customization Format", () => {
assert.throws(
() => new jsSHA("CSHAKE128", "HEX", { customization: { value: "abc" } }),
"Customization must include a value and format"
);
});
it("CSHAKE With funcName Missing format", () => {
assert.throws(
() =>
new jsSHA("CSHAKE128", "HEX", { customization: { value: "abc", format: "TEXT" }, funcName: { value: "A" } }),
"funcName must include a value and format"
);
});
it("CSHAKE With funcName Missing Value", () => {
assert.throws(
() =>
new jsSHA("CSHAKE128", "HEX", {
customization: { value: "abc", format: "TEXT" },
funcName: { format: "TEXT" },
}),
"funcName must include a value and format"
);
});
it("KMAC128 With numRounds", () => {
assert.throws(
() => new jsSHA("KMAC128", "HEX", { numRounds: 2, kmacKey: { value: "TEST", format: "TEXT" } }),
"Cannot set numRounds with MAC"
);
});
it("KMAC128 Without kmacKey", () => {
assert.throws(() => new jsSHA("KMAC128", "HEX"), "kmacKey must include a value and format");
});
it("KMAC128 With kmacKey Missing Value", () => {
assert.throws(
() => new jsSHA("KMAC128", "HEX", { kmacKey: { format: "HEX" } }),
"kmacKey must include a value and format"
);
});
it("KMAC128 With kmacKey Missing Format", () => {
assert.throws(
() => new jsSHA("KMAC128", "HEX", { kmacKey: { value: "AA" } }),
"kmacKey must include a value and format"
);
});
it("With hmacKey Set at Instantiation", () => {
const hash = new jsSHAATest("SHA3-256", "HEX", { hmacKey: { value: "TEST", format: "TEXT" } });
assert.isTrue(hash.getter("macKeySet"));
});
it("With hmacKey Set at Instantiation but then also setHMACKey", () => {
const hash = new jsSHAATest("SHA3-256", "HEX", { hmacKey: { value: "TEST", format: "TEXT" } });
assert.throws(() => {
hash.setHMACKey("TEST", "TEXT");
}, "MAC key already set");
});
});
runHashTests("SHA3-224", sha3.__get__("jsSHA"));
runHashTests("SHA3-256", sha3.__get__("jsSHA"));
runHashTests("SHA3-384", sha3.__get__("jsSHA"));
runHashTests("SHA3-512", sha3.__get__("jsSHA"));
runHashTests("SHAKE128", sha3.__get__("jsSHA"));
runHashTests("SHAKE256", sha3.__get__("jsSHA"));
runHashTests("CSHAKE128", sha3.__get__("jsSHA"));
runHashTests("CSHAKE256", sha3.__get__("jsSHA"));
runHashTests("KMAC128", sha3.__get__("jsSHA"));
runHashTests("KMAC256", sha3.__get__("jsSHA")); | the_stack |
import { autoBindMethodsForReact } from 'class-autobind-decorator';
import React, { Fragment, PureComponent, ReactNode } from 'react';
import { AUTOBIND_CFG, GlobalActivity, SortOrder } from '../../common/constants';
import { isGrpcRequest } from '../../models/grpc-request';
import { isRemoteProject } from '../../models/project';
import { Request, RequestAuthentication, RequestBody, RequestHeader, RequestParameter } from '../../models/request';
import { Settings } from '../../models/settings';
import { isCollection, isDesign } from '../../models/workspace';
import { EnvironmentsDropdown } from './dropdowns/environments-dropdown';
import { SyncDropdown } from './dropdowns/sync-dropdown';
import { ErrorBoundary } from './error-boundary';
import { PageLayout } from './page-layout';
import { GrpcRequestPane } from './panes/grpc-request-pane';
import { GrpcResponsePane } from './panes/grpc-response-pane';
import { RequestPane } from './panes/request-pane';
import { ResponsePane } from './panes/response-pane';
import { SidebarChildren } from './sidebar/sidebar-children';
import { SidebarFilter } from './sidebar/sidebar-filter';
import { WorkspacePageHeader } from './workspace-page-header';
import type { WrapperProps } from './wrapper';
interface Props {
forceRefreshKey: number;
gitSyncDropdown: ReactNode;
handleActivityChange: (options: {workspaceId?: string; nextActivity: GlobalActivity}) => Promise<void>;
handleChangeEnvironment: Function;
handleDeleteResponse: Function;
handleDeleteResponses: Function;
handleForceUpdateRequest: (r: Request, patch: Partial<Request>) => Promise<Request>;
handleForceUpdateRequestHeaders: (r: Request, headers: RequestHeader[]) => Promise<Request>;
handleImport: Function;
handleRequestCreate: () => void;
handleRequestGroupCreate: () => void;
handleSendAndDownloadRequestWithActiveEnvironment: (filepath?: string) => Promise<void>;
handleSendRequestWithActiveEnvironment: () => void;
handleSetActiveResponse: Function;
handleSetPreviewMode: Function;
handleSetResponseFilter: (filter: string) => void;
handleShowCookiesModal: Function;
handleShowRequestSettingsModal: Function;
handleSidebarSort: (sortOrder: SortOrder) => void;
handleUpdateRequestAuthentication: (r: Request, auth: RequestAuthentication) => Promise<Request>;
handleUpdateRequestBody: (r: Request, body: RequestBody) => Promise<Request>;
handleUpdateRequestHeaders: (r: Request, headers: RequestHeader[]) => Promise<Request>;
handleUpdateRequestMethod: (r: Request, method: string) => Promise<Request>;
handleUpdateRequestParameters: (r: Request, params: RequestParameter[]) => Promise<Request>;
handleUpdateRequestUrl: (r: Request, url: string) => Promise<Request>;
handleUpdateSettingsShowPasswords: (showPasswords: boolean) => Promise<Settings>;
handleUpdateSettingsUseBulkHeaderEditor: Function;
handleUpdateSettingsUseBulkParametersEditor: (useBulkParametersEditor: boolean) => Promise<Settings>;
wrapperProps: WrapperProps;
}
@autoBindMethodsForReact(AUTOBIND_CFG)
export class WrapperDebug extends PureComponent<Props> {
_renderPageHeader() {
const { wrapperProps, gitSyncDropdown, handleActivityChange } = this.props;
const { vcs, activeWorkspace, activeWorkspaceMeta, activeProject, syncItems, isLoggedIn } = this.props.wrapperProps;
if (!activeWorkspace) {
return null;
}
const collection = isCollection(activeWorkspace);
const design = isDesign(activeWorkspace);
let insomniaSync: ReactNode = null;
if (isLoggedIn && collection && isRemoteProject(activeProject) && vcs) {
insomniaSync = <SyncDropdown
workspace={activeWorkspace}
workspaceMeta={activeWorkspaceMeta}
project={activeProject}
vcs={vcs}
syncItems={syncItems}
/>;
}
const gitSync = design && gitSyncDropdown;
const sync = insomniaSync || gitSync;
return (
<WorkspacePageHeader
wrapperProps={wrapperProps}
handleActivityChange={handleActivityChange}
gridRight={sync}
/>
);
}
_renderPageSidebar() {
const {
handleChangeEnvironment,
handleRequestCreate,
handleRequestGroupCreate,
handleShowCookiesModal,
handleSidebarSort,
} = this.props;
const {
activeEnvironment,
activeWorkspace,
environments,
handleActivateRequest,
handleCopyAsCurl,
handleCreateRequest,
handleCreateRequestGroup,
handleDuplicateRequest,
handleDuplicateRequestGroup,
handleGenerateCode,
handleRender,
handleSetRequestGroupCollapsed,
handleSetRequestPinned,
handleSetSidebarFilter,
settings,
sidebarChildren,
sidebarFilter,
} = this.props.wrapperProps;
if (!activeWorkspace) {
return null;
}
return (
<Fragment>
<div className="sidebar__menu">
<EnvironmentsDropdown
handleChangeEnvironment={handleChangeEnvironment}
activeEnvironment={activeEnvironment}
environments={environments}
workspace={activeWorkspace}
environmentHighlightColorStyle={settings.environmentHighlightColorStyle}
hotKeyRegistry={settings.hotKeyRegistry}
/>
{/* @ts-expect-error -- TSCONVERSION onClick event doesn't matter */}
<button className="btn btn--super-compact" onClick={handleShowCookiesModal}>
<div className="sidebar__menu__thing">
<span>Cookies</span>
</div>
</button>
</div>
<SidebarFilter
key={`${activeWorkspace._id}::filter`}
onChange={handleSetSidebarFilter}
requestCreate={handleRequestCreate}
requestGroupCreate={handleRequestGroupCreate}
sidebarSort={handleSidebarSort}
filter={sidebarFilter || ''}
hotKeyRegistry={settings.hotKeyRegistry}
/>
<SidebarChildren
childObjects={sidebarChildren}
handleActivateRequest={handleActivateRequest}
handleCreateRequest={handleCreateRequest}
handleCreateRequestGroup={handleCreateRequestGroup}
handleSetRequestGroupCollapsed={handleSetRequestGroupCollapsed}
handleSetRequestPinned={handleSetRequestPinned}
handleDuplicateRequest={handleDuplicateRequest}
handleDuplicateRequestGroup={handleDuplicateRequestGroup}
handleGenerateCode={handleGenerateCode}
handleCopyAsCurl={handleCopyAsCurl}
handleRender={handleRender}
filter={sidebarFilter || ''}
hotKeyRegistry={settings.hotKeyRegistry}
/>
</Fragment>
);
}
_renderRequestPane() {
const {
forceRefreshKey,
handleForceUpdateRequest,
handleForceUpdateRequestHeaders,
handleImport,
handleSendAndDownloadRequestWithActiveEnvironment,
handleSendRequestWithActiveEnvironment,
handleUpdateRequestAuthentication,
handleUpdateRequestBody,
handleUpdateRequestHeaders,
handleUpdateRequestMethod,
handleUpdateRequestParameters,
handleUpdateRequestUrl,
handleUpdateSettingsShowPasswords,
handleUpdateSettingsUseBulkHeaderEditor,
handleUpdateSettingsUseBulkParametersEditor,
} = this.props;
const {
activeEnvironment,
activeRequest,
activeWorkspace,
handleCreateRequestForWorkspace,
handleGenerateCodeForActiveRequest,
handleGetRenderContext,
handleRender,
handleUpdateDownloadPath,
handleUpdateRequestMimeType,
headerEditorKey,
isVariableUncovered,
oAuth2Token,
responseDownloadPath,
settings,
} = this.props.wrapperProps;
if (!activeWorkspace) {
return null;
}
// activeRequest being truthy only needs to be checked for isGrpcRequest (for now)
// The RequestPane and ResponsePane components already handle the case where activeRequest is null
if (activeRequest && isGrpcRequest(activeRequest)) {
return (
<ErrorBoundary showAlert>
<GrpcRequestPane
activeRequest={activeRequest}
environmentId={activeEnvironment ? activeEnvironment._id : ''}
workspaceId={activeWorkspace._id}
forceRefreshKey={forceRefreshKey}
settings={settings}
handleRender={handleRender}
isVariableUncovered={isVariableUncovered}
handleGetRenderContext={handleGetRenderContext}
/>
</ErrorBoundary>
);
}
return (
<ErrorBoundary showAlert>
<RequestPane
downloadPath={responseDownloadPath}
environmentId={activeEnvironment ? activeEnvironment._id : ''}
forceRefreshCounter={forceRefreshKey}
forceUpdateRequest={handleForceUpdateRequest}
forceUpdateRequestHeaders={handleForceUpdateRequestHeaders}
handleCreateRequest={handleCreateRequestForWorkspace}
handleGenerateCode={handleGenerateCodeForActiveRequest}
handleGetRenderContext={handleGetRenderContext}
handleImport={handleImport}
handleRender={handleRender}
handleSend={handleSendRequestWithActiveEnvironment}
handleSendAndDownload={handleSendAndDownloadRequestWithActiveEnvironment}
handleUpdateDownloadPath={handleUpdateDownloadPath}
headerEditorKey={headerEditorKey}
isVariableUncovered={isVariableUncovered}
oAuth2Token={oAuth2Token}
request={activeRequest}
settings={settings}
updateRequestAuthentication={handleUpdateRequestAuthentication}
updateRequestBody={handleUpdateRequestBody}
updateRequestHeaders={handleUpdateRequestHeaders}
updateRequestMethod={handleUpdateRequestMethod}
updateRequestMimeType={handleUpdateRequestMimeType}
updateRequestParameters={handleUpdateRequestParameters}
updateRequestUrl={handleUpdateRequestUrl}
updateSettingsShowPasswords={handleUpdateSettingsShowPasswords}
updateSettingsUseBulkHeaderEditor={handleUpdateSettingsUseBulkHeaderEditor}
updateSettingsUseBulkParametersEditor={handleUpdateSettingsUseBulkParametersEditor}
workspace={activeWorkspace}
/>
</ErrorBoundary>
);
}
_renderResponsePane() {
const {
forceRefreshKey,
handleDeleteResponse,
handleDeleteResponses,
handleSetActiveResponse,
handleSetPreviewMode,
handleSetResponseFilter,
handleShowCookiesModal,
handleShowRequestSettingsModal,
} = this.props;
const {
activeEnvironment,
activeRequest,
activeRequestResponses,
activeResponse,
activeUnitTestResult,
loadStartTime,
requestVersions,
responseFilter,
responseFilterHistory,
responsePreviewMode,
settings,
} = this.props.wrapperProps;
// activeRequest being truthy only needs to be checked for isGrpcRequest (for now)
// The RequestPane and ResponsePane components already handle the case where activeRequest is null
if (activeRequest && isGrpcRequest(activeRequest)) {
return (
<ErrorBoundary showAlert>
<GrpcResponsePane
activeRequest={activeRequest}
forceRefreshKey={forceRefreshKey}
settings={settings}
/>
</ErrorBoundary>
);
}
return (
<ErrorBoundary showAlert>
<ResponsePane
disableHtmlPreviewJs={settings.disableHtmlPreviewJs}
disableResponsePreviewLinks={settings.disableResponsePreviewLinks}
editorFontSize={settings.editorFontSize}
editorIndentSize={settings.editorIndentSize}
editorKeyMap={settings.editorKeyMap}
editorLineWrapping={settings.editorLineWrapping}
environment={activeEnvironment}
filter={responseFilter}
filterHistory={responseFilterHistory}
handleDeleteResponse={handleDeleteResponse}
handleDeleteResponses={handleDeleteResponses}
handleSetActiveResponse={handleSetActiveResponse}
handleSetFilter={handleSetResponseFilter}
handleSetPreviewMode={handleSetPreviewMode}
handleShowRequestSettings={handleShowRequestSettingsModal}
showCookiesModal={handleShowCookiesModal}
hotKeyRegistry={settings.hotKeyRegistry}
loadStartTime={loadStartTime}
previewMode={responsePreviewMode}
request={activeRequest}
requestVersions={requestVersions}
response={activeResponse}
responses={activeRequestResponses}
unitTestResult={activeUnitTestResult}
/>
</ErrorBoundary>
);
}
render() {
return (
<PageLayout
wrapperProps={this.props.wrapperProps}
renderPageHeader={this._renderPageHeader}
renderPageSidebar={this._renderPageSidebar}
renderPaneOne={this._renderRequestPane}
renderPaneTwo={this._renderResponsePane}
/>
);
}
} | the_stack |
import { ComposedTreeDelegate, IAbstractTreeOptions, IAbstractTreeOptionsUpdate } from 'vs/base/browser/ui/tree/abstractTree';
import { ObjectTree, IObjectTreeOptions, CompressibleObjectTree, ICompressibleTreeRenderer, ICompressibleKeyboardNavigationLabelProvider, ICompressibleObjectTreeOptions, IObjectTreeSetChildrenOptions } from 'vs/base/browser/ui/tree/objectTree';
import { IListVirtualDelegate, IIdentityProvider, IListDragAndDrop, IListDragOverReaction } from 'vs/base/browser/ui/list/list';
import { ITreeElement, ITreeNode, ITreeRenderer, ITreeEvent, ITreeMouseEvent, ITreeContextMenuEvent, ITreeSorter, ICollapseStateChangeEvent, IAsyncDataSource, ITreeDragAndDrop, TreeError, WeakMapper, ITreeFilter, TreeVisibility, TreeFilterResult } from 'vs/base/browser/ui/tree/tree';
import { IDisposable, dispose, DisposableStore } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { timeout, CancelablePromise, createCancelablePromise, Promises } from 'vs/base/common/async';
import { IListStyles } from 'vs/base/browser/ui/list/listWidget';
import { Iterable } from 'vs/base/common/iterator';
import { IDragAndDropData } from 'vs/base/browser/dnd';
import { ElementsDragAndDropData } from 'vs/base/browser/ui/list/listView';
import { isPromiseCanceledError, onUnexpectedError } from 'vs/base/common/errors';
import { ScrollEvent } from 'vs/base/common/scrollable';
import { ICompressedTreeNode, ICompressedTreeElement } from 'vs/base/browser/ui/tree/compressedObjectTreeModel';
import { IThemable } from 'vs/base/common/styler';
import { isFilterResult, getVisibleState } from 'vs/base/browser/ui/tree/indexTreeModel';
import { treeItemLoadingIcon } from 'vs/base/browser/ui/tree/treeIcons';
interface IAsyncDataTreeNode<TInput, T> {
element: TInput | T;
readonly parent: IAsyncDataTreeNode<TInput, T> | null;
readonly children: IAsyncDataTreeNode<TInput, T>[];
readonly id?: string | null;
refreshPromise: Promise<void> | undefined;
hasChildren: boolean;
stale: boolean;
slow: boolean;
collapsedByDefault: boolean | undefined;
}
interface IAsyncDataTreeNodeRequiredProps<TInput, T> extends Partial<IAsyncDataTreeNode<TInput, T>> {
readonly element: TInput | T;
readonly parent: IAsyncDataTreeNode<TInput, T> | null;
readonly hasChildren: boolean;
}
function createAsyncDataTreeNode<TInput, T>(props: IAsyncDataTreeNodeRequiredProps<TInput, T>): IAsyncDataTreeNode<TInput, T> {
return {
...props,
children: [],
refreshPromise: undefined,
stale: true,
slow: false,
collapsedByDefault: undefined
};
}
function isAncestor<TInput, T>(ancestor: IAsyncDataTreeNode<TInput, T>, descendant: IAsyncDataTreeNode<TInput, T>): boolean {
if (!descendant.parent) {
return false;
} else if (descendant.parent === ancestor) {
return true;
} else {
return isAncestor(ancestor, descendant.parent);
}
}
function intersects<TInput, T>(node: IAsyncDataTreeNode<TInput, T>, other: IAsyncDataTreeNode<TInput, T>): boolean {
return node === other || isAncestor(node, other) || isAncestor(other, node);
}
interface IDataTreeListTemplateData<T> {
templateData: T;
}
type AsyncDataTreeNodeMapper<TInput, T, TFilterData> = WeakMapper<ITreeNode<IAsyncDataTreeNode<TInput, T> | null, TFilterData>, ITreeNode<TInput | T, TFilterData>>;
class AsyncDataTreeNodeWrapper<TInput, T, TFilterData> implements ITreeNode<TInput | T, TFilterData> {
get element(): T { return this.node.element!.element as T; }
get children(): ITreeNode<T, TFilterData>[] { return this.node.children.map(node => new AsyncDataTreeNodeWrapper(node)); }
get depth(): number { return this.node.depth; }
get visibleChildrenCount(): number { return this.node.visibleChildrenCount; }
get visibleChildIndex(): number { return this.node.visibleChildIndex; }
get collapsible(): boolean { return this.node.collapsible; }
get collapsed(): boolean { return this.node.collapsed; }
get visible(): boolean { return this.node.visible; }
get filterData(): TFilterData | undefined { return this.node.filterData; }
constructor(private node: ITreeNode<IAsyncDataTreeNode<TInput, T> | null, TFilterData>) { }
}
class AsyncDataTreeRenderer<TInput, T, TFilterData, TTemplateData> implements ITreeRenderer<IAsyncDataTreeNode<TInput, T>, TFilterData, IDataTreeListTemplateData<TTemplateData>> {
readonly templateId: string;
private renderedNodes = new Map<IAsyncDataTreeNode<TInput, T>, IDataTreeListTemplateData<TTemplateData>>();
constructor(
protected renderer: ITreeRenderer<T, TFilterData, TTemplateData>,
protected nodeMapper: AsyncDataTreeNodeMapper<TInput, T, TFilterData>,
readonly onDidChangeTwistieState: Event<IAsyncDataTreeNode<TInput, T>>
) {
this.templateId = renderer.templateId;
}
renderTemplate(container: HTMLElement): IDataTreeListTemplateData<TTemplateData> {
const templateData = this.renderer.renderTemplate(container);
return { templateData };
}
renderElement(node: ITreeNode<IAsyncDataTreeNode<TInput, T>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void {
this.renderer.renderElement(this.nodeMapper.map(node) as ITreeNode<T, TFilterData>, index, templateData.templateData, height);
}
renderTwistie(element: IAsyncDataTreeNode<TInput, T>, twistieElement: HTMLElement): boolean {
if (element.slow) {
twistieElement.classList.add(...treeItemLoadingIcon.classNamesArray);
return true;
} else {
twistieElement.classList.remove(...treeItemLoadingIcon.classNamesArray);
return false;
}
}
disposeElement(node: ITreeNode<IAsyncDataTreeNode<TInput, T>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void {
if (this.renderer.disposeElement) {
this.renderer.disposeElement(this.nodeMapper.map(node) as ITreeNode<T, TFilterData>, index, templateData.templateData, height);
}
}
disposeTemplate(templateData: IDataTreeListTemplateData<TTemplateData>): void {
this.renderer.disposeTemplate(templateData.templateData);
}
dispose(): void {
this.renderedNodes.clear();
}
}
function asTreeEvent<TInput, T>(e: ITreeEvent<IAsyncDataTreeNode<TInput, T> | null>): ITreeEvent<T> {
return {
browserEvent: e.browserEvent,
elements: e.elements.map(e => e!.element as T)
};
}
function asTreeMouseEvent<TInput, T>(e: ITreeMouseEvent<IAsyncDataTreeNode<TInput, T> | null>): ITreeMouseEvent<T> {
return {
browserEvent: e.browserEvent,
element: e.element && e.element.element as T,
target: e.target
};
}
function asTreeContextMenuEvent<TInput, T>(e: ITreeContextMenuEvent<IAsyncDataTreeNode<TInput, T> | null>): ITreeContextMenuEvent<T> {
return {
browserEvent: e.browserEvent,
element: e.element && e.element.element as T,
anchor: e.anchor
};
}
class AsyncDataTreeElementsDragAndDropData<TInput, T, TContext> extends ElementsDragAndDropData<T, TContext> {
override set context(context: TContext | undefined) {
this.data.context = context;
}
override get context(): TContext | undefined {
return this.data.context;
}
constructor(private data: ElementsDragAndDropData<IAsyncDataTreeNode<TInput, T>, TContext>) {
super(data.elements.map(node => node.element as T));
}
}
function asAsyncDataTreeDragAndDropData<TInput, T>(data: IDragAndDropData): IDragAndDropData {
if (data instanceof ElementsDragAndDropData) {
return new AsyncDataTreeElementsDragAndDropData(data);
}
return data;
}
class AsyncDataTreeNodeListDragAndDrop<TInput, T> implements IListDragAndDrop<IAsyncDataTreeNode<TInput, T>> {
constructor(private dnd: ITreeDragAndDrop<T>) { }
getDragURI(node: IAsyncDataTreeNode<TInput, T>): string | null {
return this.dnd.getDragURI(node.element as T);
}
getDragLabel(nodes: IAsyncDataTreeNode<TInput, T>[], originalEvent: DragEvent): string | undefined {
if (this.dnd.getDragLabel) {
return this.dnd.getDragLabel(nodes.map(node => node.element as T), originalEvent);
}
return undefined;
}
onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void {
if (this.dnd.onDragStart) {
this.dnd.onDragStart(asAsyncDataTreeDragAndDropData(data), originalEvent);
}
}
onDragOver(data: IDragAndDropData, targetNode: IAsyncDataTreeNode<TInput, T> | undefined, targetIndex: number | undefined, originalEvent: DragEvent, raw = true): boolean | IListDragOverReaction {
return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element as T, targetIndex, originalEvent);
}
drop(data: IDragAndDropData, targetNode: IAsyncDataTreeNode<TInput, T> | undefined, targetIndex: number | undefined, originalEvent: DragEvent): void {
this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element as T, targetIndex, originalEvent);
}
onDragEnd(originalEvent: DragEvent): void {
if (this.dnd.onDragEnd) {
this.dnd.onDragEnd(originalEvent);
}
}
}
function asObjectTreeOptions<TInput, T, TFilterData>(options?: IAsyncDataTreeOptions<T, TFilterData>): IObjectTreeOptions<IAsyncDataTreeNode<TInput, T>, TFilterData> | undefined {
return options && {
...options,
collapseByDefault: true,
identityProvider: options.identityProvider && {
getId(el) {
return options.identityProvider!.getId(el.element as T);
}
},
dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd),
multipleSelectionController: options.multipleSelectionController && {
isSelectionSingleChangeEvent(e) {
return options.multipleSelectionController!.isSelectionSingleChangeEvent({ ...e, element: e.element } as any);
},
isSelectionRangeChangeEvent(e) {
return options.multipleSelectionController!.isSelectionRangeChangeEvent({ ...e, element: e.element } as any);
}
},
accessibilityProvider: options.accessibilityProvider && {
...options.accessibilityProvider,
getPosInSet: undefined,
getSetSize: undefined,
getRole: options.accessibilityProvider!.getRole ? (el) => {
return options.accessibilityProvider!.getRole!(el.element as T);
} : () => 'treeitem',
isChecked: options.accessibilityProvider!.isChecked ? (e) => {
return !!(options.accessibilityProvider?.isChecked!(e.element as T));
} : undefined,
getAriaLabel(e) {
return options.accessibilityProvider!.getAriaLabel(e.element as T);
},
getWidgetAriaLabel() {
return options.accessibilityProvider!.getWidgetAriaLabel();
},
getWidgetRole: options.accessibilityProvider!.getWidgetRole ? () => options.accessibilityProvider!.getWidgetRole!() : () => 'tree',
getAriaLevel: options.accessibilityProvider!.getAriaLevel && (node => {
return options.accessibilityProvider!.getAriaLevel!(node.element as T);
}),
getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && (node => {
return options.accessibilityProvider!.getActiveDescendantId!(node.element as T);
})
},
filter: options.filter && {
filter(e, parentVisibility) {
return options.filter!.filter(e.element as T, parentVisibility);
}
},
keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
...options.keyboardNavigationLabelProvider,
getKeyboardNavigationLabel(e) {
return options.keyboardNavigationLabelProvider!.getKeyboardNavigationLabel(e.element as T);
}
},
sorter: undefined,
expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === 'undefined' ? undefined : (
typeof options.expandOnlyOnTwistieClick !== 'function' ? options.expandOnlyOnTwistieClick : (
e => (options.expandOnlyOnTwistieClick as ((e: T) => boolean))(e.element as T)
)
),
additionalScrollHeight: options.additionalScrollHeight
};
}
export interface IAsyncDataTreeOptionsUpdate extends IAbstractTreeOptionsUpdate { }
export interface IAsyncDataTreeUpdateChildrenOptions<T> extends IObjectTreeSetChildrenOptions<T> { }
export interface IAsyncDataTreeOptions<T, TFilterData = void> extends IAsyncDataTreeOptionsUpdate, Pick<IAbstractTreeOptions<T, TFilterData>, Exclude<keyof IAbstractTreeOptions<T, TFilterData>, 'collapseByDefault'>> {
readonly collapseByDefault?: { (e: T): boolean; };
readonly identityProvider?: IIdentityProvider<T>;
readonly sorter?: ITreeSorter<T>;
readonly autoExpandSingleChildren?: boolean;
}
export interface IAsyncDataTreeViewState {
readonly focus?: string[];
readonly selection?: string[];
readonly expanded?: string[];
readonly scrollTop?: number;
}
interface IAsyncDataTreeViewStateContext<TInput, T> {
readonly viewState: IAsyncDataTreeViewState;
readonly selection: IAsyncDataTreeNode<TInput, T>[];
readonly focus: IAsyncDataTreeNode<TInput, T>[];
}
function dfs<TInput, T>(node: IAsyncDataTreeNode<TInput, T>, fn: (node: IAsyncDataTreeNode<TInput, T>) => void): void {
fn(node);
node.children.forEach(child => dfs(child, fn));
}
export class AsyncDataTree<TInput, T, TFilterData = void> implements IDisposable, IThemable {
protected readonly tree: ObjectTree<IAsyncDataTreeNode<TInput, T>, TFilterData>;
protected readonly root: IAsyncDataTreeNode<TInput, T>;
private readonly nodes = new Map<null | T, IAsyncDataTreeNode<TInput, T>>();
private readonly sorter?: ITreeSorter<T>;
private readonly collapseByDefault?: { (e: T): boolean; };
private readonly subTreeRefreshPromises = new Map<IAsyncDataTreeNode<TInput, T>, Promise<void>>();
private readonly refreshPromises = new Map<IAsyncDataTreeNode<TInput, T>, CancelablePromise<Iterable<T>>>();
protected readonly identityProvider?: IIdentityProvider<T>;
private readonly autoExpandSingleChildren: boolean;
private readonly _onDidRender = new Emitter<void>();
protected readonly _onDidChangeNodeSlowState = new Emitter<IAsyncDataTreeNode<TInput, T>>();
protected readonly nodeMapper: AsyncDataTreeNodeMapper<TInput, T, TFilterData> = new WeakMapper(node => new AsyncDataTreeNodeWrapper(node));
protected readonly disposables = new DisposableStore();
get onDidScroll(): Event<ScrollEvent> { return this.tree.onDidScroll; }
get onDidChangeFocus(): Event<ITreeEvent<T>> { return Event.map(this.tree.onDidChangeFocus, asTreeEvent); }
get onDidChangeSelection(): Event<ITreeEvent<T>> { return Event.map(this.tree.onDidChangeSelection, asTreeEvent); }
get onKeyDown(): Event<KeyboardEvent> { return this.tree.onKeyDown; }
get onMouseClick(): Event<ITreeMouseEvent<T>> { return Event.map(this.tree.onMouseClick, asTreeMouseEvent); }
get onMouseDblClick(): Event<ITreeMouseEvent<T>> { return Event.map(this.tree.onMouseDblClick, asTreeMouseEvent); }
get onContextMenu(): Event<ITreeContextMenuEvent<T>> { return Event.map(this.tree.onContextMenu, asTreeContextMenuEvent); }
get onTap(): Event<ITreeMouseEvent<T>> { return Event.map(this.tree.onTap, asTreeMouseEvent); }
get onPointer(): Event<ITreeMouseEvent<T>> { return Event.map(this.tree.onPointer, asTreeMouseEvent); }
get onDidFocus(): Event<void> { return this.tree.onDidFocus; }
get onDidBlur(): Event<void> { return this.tree.onDidBlur; }
get onDidChangeCollapseState(): Event<ICollapseStateChangeEvent<IAsyncDataTreeNode<TInput, T> | null, TFilterData>> { return this.tree.onDidChangeCollapseState; }
get onDidUpdateOptions(): Event<IAsyncDataTreeOptionsUpdate> { return this.tree.onDidUpdateOptions; }
get filterOnType(): boolean { return this.tree.filterOnType; }
get expandOnlyOnTwistieClick(): boolean | ((e: T) => boolean) {
if (typeof this.tree.expandOnlyOnTwistieClick === 'boolean') {
return this.tree.expandOnlyOnTwistieClick;
}
const fn = this.tree.expandOnlyOnTwistieClick;
return element => fn(this.nodes.get((element === this.root.element ? null : element) as T) || null);
}
get onDidDispose(): Event<void> { return this.tree.onDidDispose; }
constructor(
protected user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<T>,
renderers: ITreeRenderer<T, TFilterData, any>[],
private dataSource: IAsyncDataSource<TInput, T>,
options: IAsyncDataTreeOptions<T, TFilterData> = {}
) {
this.identityProvider = options.identityProvider;
this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === 'undefined' ? false : options.autoExpandSingleChildren;
this.sorter = options.sorter;
this.collapseByDefault = options.collapseByDefault;
this.tree = this.createTree(user, container, delegate, renderers, options);
this.root = createAsyncDataTreeNode({
element: undefined!,
parent: null,
hasChildren: true
});
if (this.identityProvider) {
this.root = {
...this.root,
id: null
};
}
this.nodes.set(null, this.root);
this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables);
}
protected createTree(
user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<T>,
renderers: ITreeRenderer<T, TFilterData, any>[],
options: IAsyncDataTreeOptions<T, TFilterData>
): ObjectTree<IAsyncDataTreeNode<TInput, T>, TFilterData> {
const objectTreeDelegate = new ComposedTreeDelegate<TInput | T, IAsyncDataTreeNode<TInput, T>>(delegate);
const objectTreeRenderers = renderers.map(r => new AsyncDataTreeRenderer(r, this.nodeMapper, this._onDidChangeNodeSlowState.event));
const objectTreeOptions = asObjectTreeOptions<TInput, T, TFilterData>(options) || {};
return new ObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
}
updateOptions(options: IAsyncDataTreeOptionsUpdate = {}): void {
this.tree.updateOptions(options);
}
get options(): IAsyncDataTreeOptions<T, TFilterData> {
return this.tree.options as IAsyncDataTreeOptions<T, TFilterData>;
}
// Widget
getHTMLElement(): HTMLElement {
return this.tree.getHTMLElement();
}
get contentHeight(): number {
return this.tree.contentHeight;
}
get onDidChangeContentHeight(): Event<number> {
return this.tree.onDidChangeContentHeight;
}
get scrollTop(): number {
return this.tree.scrollTop;
}
set scrollTop(scrollTop: number) {
this.tree.scrollTop = scrollTop;
}
get scrollLeft(): number {
return this.tree.scrollLeft;
}
set scrollLeft(scrollLeft: number) {
this.tree.scrollLeft = scrollLeft;
}
get scrollHeight(): number {
return this.tree.scrollHeight;
}
get renderHeight(): number {
return this.tree.renderHeight;
}
get lastVisibleElement(): T {
return this.tree.lastVisibleElement!.element as T;
}
get ariaLabel(): string {
return this.tree.ariaLabel;
}
set ariaLabel(value: string) {
this.tree.ariaLabel = value;
}
domFocus(): void {
this.tree.domFocus();
}
layout(height?: number, width?: number): void {
this.tree.layout(height, width);
}
style(styles: IListStyles): void {
this.tree.style(styles);
}
// Model
getInput(): TInput | undefined {
return this.root.element as TInput;
}
async setInput(input: TInput, viewState?: IAsyncDataTreeViewState): Promise<void> {
this.refreshPromises.forEach(promise => promise.cancel());
this.refreshPromises.clear();
this.root.element = input!;
const viewStateContext = viewState && { viewState, focus: [], selection: [] } as IAsyncDataTreeViewStateContext<TInput, T>;
await this._updateChildren(input, true, false, viewStateContext);
if (viewStateContext) {
this.tree.setFocus(viewStateContext.focus);
this.tree.setSelection(viewStateContext.selection);
}
if (viewState && typeof viewState.scrollTop === 'number') {
this.scrollTop = viewState.scrollTop;
}
}
async updateChildren(element: TInput | T = this.root.element, recursive = true, rerender = false, options?: IAsyncDataTreeUpdateChildrenOptions<T>): Promise<void> {
await this._updateChildren(element, recursive, rerender, undefined, options);
}
private async _updateChildren(element: TInput | T = this.root.element, recursive = true, rerender = false, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>, options?: IAsyncDataTreeUpdateChildrenOptions<T>): Promise<void> {
if (typeof this.root.element === 'undefined') {
throw new TreeError(this.user, 'Tree input not set');
}
if (this.root.refreshPromise) {
await this.root.refreshPromise;
await Event.toPromise(this._onDidRender.event);
}
const node = this.getDataNode(element);
await this.refreshAndRenderNode(node, recursive, viewStateContext, options);
if (rerender) {
try {
this.tree.rerender(node);
} catch {
// missing nodes are fine, this could've resulted from
// parallel refresh calls, removing `node` altogether
}
}
}
resort(element: TInput | T = this.root.element, recursive = true): void {
this.tree.resort(this.getDataNode(element), recursive);
}
hasNode(element: TInput | T): boolean {
return element === this.root.element || this.nodes.has(element as T);
}
// View
rerender(element?: T): void {
if (element === undefined || element === this.root.element) {
this.tree.rerender();
return;
}
const node = this.getDataNode(element);
this.tree.rerender(node);
}
updateWidth(element: T): void {
const node = this.getDataNode(element);
this.tree.updateWidth(node);
}
// Tree
getNode(element: TInput | T = this.root.element): ITreeNode<TInput | T, TFilterData> {
const dataNode = this.getDataNode(element);
const node = this.tree.getNode(dataNode === this.root ? null : dataNode);
return this.nodeMapper.map(node);
}
collapse(element: T, recursive: boolean = false): boolean {
const node = this.getDataNode(element);
return this.tree.collapse(node === this.root ? null : node, recursive);
}
async expand(element: T, recursive: boolean = false): Promise<boolean> {
if (typeof this.root.element === 'undefined') {
throw new TreeError(this.user, 'Tree input not set');
}
if (this.root.refreshPromise) {
await this.root.refreshPromise;
await Event.toPromise(this._onDidRender.event);
}
const node = this.getDataNode(element);
if (this.tree.hasElement(node) && !this.tree.isCollapsible(node)) {
return false;
}
if (node.refreshPromise) {
await this.root.refreshPromise;
await Event.toPromise(this._onDidRender.event);
}
if (node !== this.root && !node.refreshPromise && !this.tree.isCollapsed(node)) {
return false;
}
const result = this.tree.expand(node === this.root ? null : node, recursive);
if (node.refreshPromise) {
await this.root.refreshPromise;
await Event.toPromise(this._onDidRender.event);
}
return result;
}
toggleCollapsed(element: T, recursive: boolean = false): boolean {
return this.tree.toggleCollapsed(this.getDataNode(element), recursive);
}
expandAll(): void {
this.tree.expandAll();
}
collapseAll(): void {
this.tree.collapseAll();
}
isCollapsible(element: T): boolean {
return this.tree.isCollapsible(this.getDataNode(element));
}
isCollapsed(element: TInput | T): boolean {
return this.tree.isCollapsed(this.getDataNode(element));
}
toggleKeyboardNavigation(): void {
this.tree.toggleKeyboardNavigation();
}
refilter(): void {
this.tree.refilter();
}
setAnchor(element: T | undefined): void {
this.tree.setAnchor(typeof element === 'undefined' ? undefined : this.getDataNode(element));
}
getAnchor(): T | undefined {
const node = this.tree.getAnchor();
return node?.element as T;
}
setSelection(elements: T[], browserEvent?: UIEvent): void {
const nodes = elements.map(e => this.getDataNode(e));
this.tree.setSelection(nodes, browserEvent);
}
getSelection(): T[] {
const nodes = this.tree.getSelection();
return nodes.map(n => n!.element as T);
}
setFocus(elements: T[], browserEvent?: UIEvent): void {
const nodes = elements.map(e => this.getDataNode(e));
this.tree.setFocus(nodes, browserEvent);
}
focusNext(n = 1, loop = false, browserEvent?: UIEvent): void {
this.tree.focusNext(n, loop, browserEvent);
}
focusPrevious(n = 1, loop = false, browserEvent?: UIEvent): void {
this.tree.focusPrevious(n, loop, browserEvent);
}
focusNextPage(browserEvent?: UIEvent): Promise<void> {
return this.tree.focusNextPage(browserEvent);
}
focusPreviousPage(browserEvent?: UIEvent): Promise<void> {
return this.tree.focusPreviousPage(browserEvent);
}
focusLast(browserEvent?: UIEvent): void {
this.tree.focusLast(browserEvent);
}
focusFirst(browserEvent?: UIEvent): void {
this.tree.focusFirst(browserEvent);
}
getFocus(): T[] {
const nodes = this.tree.getFocus();
return nodes.map(n => n!.element as T);
}
reveal(element: T, relativeTop?: number): void {
this.tree.reveal(this.getDataNode(element), relativeTop);
}
getRelativeTop(element: T): number | null {
return this.tree.getRelativeTop(this.getDataNode(element));
}
// Tree navigation
getParentElement(element: T): TInput | T {
const node = this.tree.getParentElement(this.getDataNode(element));
return (node && node.element)!;
}
getFirstElementChild(element: TInput | T = this.root.element): TInput | T | undefined {
const dataNode = this.getDataNode(element);
const node = this.tree.getFirstElementChild(dataNode === this.root ? null : dataNode);
return (node && node.element)!;
}
// Implementation
private getDataNode(element: TInput | T): IAsyncDataTreeNode<TInput, T> {
const node: IAsyncDataTreeNode<TInput, T> | undefined = this.nodes.get((element === this.root.element ? null : element) as T);
if (!node) {
throw new TreeError(this.user, `Data tree node not found: ${element}`);
}
return node;
}
private async refreshAndRenderNode(node: IAsyncDataTreeNode<TInput, T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>, options?: IAsyncDataTreeUpdateChildrenOptions<T>): Promise<void> {
await this.refreshNode(node, recursive, viewStateContext);
this.render(node, viewStateContext, options);
}
private async refreshNode(node: IAsyncDataTreeNode<TInput, T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): Promise<void> {
let result: Promise<void> | undefined;
this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => {
if (!result && intersects(refreshNode, node)) {
result = refreshPromise.then(() => this.refreshNode(node, recursive, viewStateContext));
}
});
if (result) {
return result;
}
return this.doRefreshSubTree(node, recursive, viewStateContext);
}
private async doRefreshSubTree(node: IAsyncDataTreeNode<TInput, T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): Promise<void> {
let done: () => void;
node.refreshPromise = new Promise(c => done = c);
this.subTreeRefreshPromises.set(node, node.refreshPromise);
node.refreshPromise.finally(() => {
node.refreshPromise = undefined;
this.subTreeRefreshPromises.delete(node);
});
try {
const childrenToRefresh = await this.doRefreshNode(node, recursive, viewStateContext);
node.stale = false;
await Promises.settled(childrenToRefresh.map(child => this.doRefreshSubTree(child, recursive, viewStateContext)));
} finally {
done!();
}
}
private async doRefreshNode(node: IAsyncDataTreeNode<TInput, T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): Promise<IAsyncDataTreeNode<TInput, T>[]> {
node.hasChildren = !!this.dataSource.hasChildren(node.element!);
let childrenPromise: Promise<Iterable<T>>;
if (!node.hasChildren) {
childrenPromise = Promise.resolve(Iterable.empty());
} else {
const slowTimeout = timeout(800);
slowTimeout.then(() => {
node.slow = true;
this._onDidChangeNodeSlowState.fire(node);
}, _ => null);
childrenPromise = this.doGetChildren(node)
.finally(() => slowTimeout.cancel());
}
try {
const children = await childrenPromise;
return this.setChildren(node, children, recursive, viewStateContext);
} catch (err) {
if (node !== this.root && this.tree.hasElement(node)) {
this.tree.collapse(node);
}
if (isPromiseCanceledError(err)) {
return [];
}
throw err;
} finally {
if (node.slow) {
node.slow = false;
this._onDidChangeNodeSlowState.fire(node);
}
}
}
private doGetChildren(node: IAsyncDataTreeNode<TInput, T>): Promise<Iterable<T>> {
let result = this.refreshPromises.get(node);
if (result) {
return result;
}
result = createCancelablePromise(async () => {
const children = await this.dataSource.getChildren(node.element!);
return this.processChildren(children);
});
this.refreshPromises.set(node, result);
return result.finally(() => { this.refreshPromises.delete(node); });
}
private _onDidChangeCollapseState({ node, deep }: ICollapseStateChangeEvent<IAsyncDataTreeNode<TInput, T> | null, any>): void {
if (node.element === null) {
return;
}
if (!node.collapsed && node.element.stale) {
if (deep) {
this.collapse(node.element.element as T);
} else {
this.refreshAndRenderNode(node.element, false)
.catch(onUnexpectedError);
}
}
}
private setChildren(node: IAsyncDataTreeNode<TInput, T>, childrenElementsIterable: Iterable<T>, recursive: boolean, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): IAsyncDataTreeNode<TInput, T>[] {
const childrenElements = [...childrenElementsIterable];
// perf: if the node was and still is a leaf, avoid all this hassle
if (node.children.length === 0 && childrenElements.length === 0) {
return [];
}
const nodesToForget = new Map<T, IAsyncDataTreeNode<TInput, T>>();
const childrenTreeNodesById = new Map<string, { node: IAsyncDataTreeNode<TInput, T>, collapsed: boolean }>();
for (const child of node.children) {
nodesToForget.set(child.element as T, child);
if (this.identityProvider) {
const collapsed = this.tree.isCollapsed(child);
childrenTreeNodesById.set(child.id!, { node: child, collapsed });
}
}
const childrenToRefresh: IAsyncDataTreeNode<TInput, T>[] = [];
const children = childrenElements.map<IAsyncDataTreeNode<TInput, T>>(element => {
const hasChildren = !!this.dataSource.hasChildren(element);
if (!this.identityProvider) {
const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, hasChildren });
if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
asyncDataTreeNode.collapsedByDefault = false;
childrenToRefresh.push(asyncDataTreeNode);
}
return asyncDataTreeNode;
}
const id = this.identityProvider.getId(element).toString();
const result = childrenTreeNodesById.get(id);
if (result) {
const asyncDataTreeNode = result.node;
nodesToForget.delete(asyncDataTreeNode.element as T);
this.nodes.delete(asyncDataTreeNode.element as T);
this.nodes.set(element, asyncDataTreeNode);
asyncDataTreeNode.element = element;
asyncDataTreeNode.hasChildren = hasChildren;
if (recursive) {
if (result.collapsed) {
asyncDataTreeNode.children.forEach(node => dfs(node, node => this.nodes.delete(node.element as T)));
asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length);
asyncDataTreeNode.stale = true;
} else {
childrenToRefresh.push(asyncDataTreeNode);
}
} else if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
asyncDataTreeNode.collapsedByDefault = false;
childrenToRefresh.push(asyncDataTreeNode);
}
return asyncDataTreeNode;
}
const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node, id, hasChildren });
if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id) > -1) {
viewStateContext.focus.push(childAsyncDataTreeNode);
}
if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id) > -1) {
viewStateContext.selection.push(childAsyncDataTreeNode);
}
if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id) > -1) {
childrenToRefresh.push(childAsyncDataTreeNode);
} else if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
childAsyncDataTreeNode.collapsedByDefault = false;
childrenToRefresh.push(childAsyncDataTreeNode);
}
return childAsyncDataTreeNode;
});
for (const node of nodesToForget.values()) {
dfs(node, node => this.nodes.delete(node.element as T));
}
for (const child of children) {
this.nodes.set(child.element as T, child);
}
node.children.splice(0, node.children.length, ...children);
// TODO@joao this doesn't take filter into account
if (node !== this.root && this.autoExpandSingleChildren && children.length === 1 && childrenToRefresh.length === 0) {
children[0].collapsedByDefault = false;
childrenToRefresh.push(children[0]);
}
return childrenToRefresh;
}
protected render(node: IAsyncDataTreeNode<TInput, T>, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>, options?: IAsyncDataTreeUpdateChildrenOptions<T>): void {
const children = node.children.map(node => this.asTreeElement(node, viewStateContext));
const objectTreeOptions: IObjectTreeSetChildrenOptions<IAsyncDataTreeNode<TInput, T>> | undefined = options && {
...options,
diffIdentityProvider: options!.diffIdentityProvider && {
getId(node: IAsyncDataTreeNode<TInput, T>): { toString(): string; } {
return options!.diffIdentityProvider!.getId(node.element as T);
}
}
};
this.tree.setChildren(node === this.root ? null : node, children, objectTreeOptions);
if (node !== this.root) {
this.tree.setCollapsible(node, node.hasChildren);
}
this._onDidRender.fire();
}
protected asTreeElement(node: IAsyncDataTreeNode<TInput, T>, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): ITreeElement<IAsyncDataTreeNode<TInput, T>> {
if (node.stale) {
return {
element: node,
collapsible: node.hasChildren,
collapsed: true
};
}
let collapsed: boolean | undefined;
if (viewStateContext && viewStateContext.viewState.expanded && node.id && viewStateContext.viewState.expanded.indexOf(node.id) > -1) {
collapsed = false;
} else {
collapsed = node.collapsedByDefault;
}
node.collapsedByDefault = undefined;
return {
element: node,
children: node.hasChildren ? Iterable.map(node.children, child => this.asTreeElement(child, viewStateContext)) : [],
collapsible: node.hasChildren,
collapsed
};
}
protected processChildren(children: Iterable<T>): Iterable<T> {
if (this.sorter) {
children = [...children].sort(this.sorter.compare.bind(this.sorter));
}
return children;
}
// view state
getViewState(): IAsyncDataTreeViewState {
if (!this.identityProvider) {
throw new TreeError(this.user, 'Can\'t get tree view state without an identity provider');
}
const getId = (element: T) => this.identityProvider!.getId(element).toString();
const focus = this.getFocus().map(getId);
const selection = this.getSelection().map(getId);
const expanded: string[] = [];
const root = this.tree.getNode();
const stack = [root];
while (stack.length > 0) {
const node = stack.pop()!;
if (node !== root && node.collapsible && !node.collapsed) {
expanded.push(getId(node.element!.element as T));
}
stack.push(...node.children);
}
return { focus, selection, expanded, scrollTop: this.scrollTop };
}
dispose(): void {
this.disposables.dispose();
}
}
type CompressibleAsyncDataTreeNodeMapper<TInput, T, TFilterData> = WeakMapper<ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>>, TFilterData>, ITreeNode<ICompressedTreeNode<TInput | T>, TFilterData>>;
class CompressibleAsyncDataTreeNodeWrapper<TInput, T, TFilterData> implements ITreeNode<ICompressedTreeNode<TInput | T>, TFilterData> {
get element(): ICompressedTreeNode<TInput | T> {
return {
elements: this.node.element.elements.map(e => e.element),
incompressible: this.node.element.incompressible
};
}
get children(): ITreeNode<ICompressedTreeNode<TInput | T>, TFilterData>[] { return this.node.children.map(node => new CompressibleAsyncDataTreeNodeWrapper(node)); }
get depth(): number { return this.node.depth; }
get visibleChildrenCount(): number { return this.node.visibleChildrenCount; }
get visibleChildIndex(): number { return this.node.visibleChildIndex; }
get collapsible(): boolean { return this.node.collapsible; }
get collapsed(): boolean { return this.node.collapsed; }
get visible(): boolean { return this.node.visible; }
get filterData(): TFilterData | undefined { return this.node.filterData; }
constructor(private node: ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>>, TFilterData>) { }
}
class CompressibleAsyncDataTreeRenderer<TInput, T, TFilterData, TTemplateData> implements ICompressibleTreeRenderer<IAsyncDataTreeNode<TInput, T>, TFilterData, IDataTreeListTemplateData<TTemplateData>> {
readonly templateId: string;
private renderedNodes = new Map<IAsyncDataTreeNode<TInput, T>, IDataTreeListTemplateData<TTemplateData>>();
private disposables: IDisposable[] = [];
constructor(
protected renderer: ICompressibleTreeRenderer<T, TFilterData, TTemplateData>,
protected nodeMapper: AsyncDataTreeNodeMapper<TInput, T, TFilterData>,
private compressibleNodeMapperProvider: () => CompressibleAsyncDataTreeNodeMapper<TInput, T, TFilterData>,
readonly onDidChangeTwistieState: Event<IAsyncDataTreeNode<TInput, T>>
) {
this.templateId = renderer.templateId;
}
renderTemplate(container: HTMLElement): IDataTreeListTemplateData<TTemplateData> {
const templateData = this.renderer.renderTemplate(container);
return { templateData };
}
renderElement(node: ITreeNode<IAsyncDataTreeNode<TInput, T>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void {
this.renderer.renderElement(this.nodeMapper.map(node) as ITreeNode<T, TFilterData>, index, templateData.templateData, height);
}
renderCompressedElements(node: ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void {
this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node) as ITreeNode<ICompressedTreeNode<T>, TFilterData>, index, templateData.templateData, height);
}
renderTwistie(element: IAsyncDataTreeNode<TInput, T>, twistieElement: HTMLElement): boolean {
if (element.slow) {
twistieElement.classList.add(...treeItemLoadingIcon.classNamesArray);
return true;
} else {
twistieElement.classList.remove(...treeItemLoadingIcon.classNamesArray);
return false;
}
}
disposeElement(node: ITreeNode<IAsyncDataTreeNode<TInput, T>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void {
if (this.renderer.disposeElement) {
this.renderer.disposeElement(this.nodeMapper.map(node) as ITreeNode<T, TFilterData>, index, templateData.templateData, height);
}
}
disposeCompressedElements(node: ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>>, TFilterData>, index: number, templateData: IDataTreeListTemplateData<TTemplateData>, height: number | undefined): void {
if (this.renderer.disposeCompressedElements) {
this.renderer.disposeCompressedElements(this.compressibleNodeMapperProvider().map(node) as ITreeNode<ICompressedTreeNode<T>, TFilterData>, index, templateData.templateData, height);
}
}
disposeTemplate(templateData: IDataTreeListTemplateData<TTemplateData>): void {
this.renderer.disposeTemplate(templateData.templateData);
}
dispose(): void {
this.renderedNodes.clear();
this.disposables = dispose(this.disposables);
}
}
export interface ITreeCompressionDelegate<T> {
isIncompressible(element: T): boolean;
}
function asCompressibleObjectTreeOptions<TInput, T, TFilterData>(options?: ICompressibleAsyncDataTreeOptions<T, TFilterData>): ICompressibleObjectTreeOptions<IAsyncDataTreeNode<TInput, T>, TFilterData> | undefined {
const objectTreeOptions = options && asObjectTreeOptions(options);
return objectTreeOptions && {
...objectTreeOptions,
keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && {
...objectTreeOptions.keyboardNavigationLabelProvider,
getCompressedNodeKeyboardNavigationLabel(els) {
return options!.keyboardNavigationLabelProvider!.getCompressedNodeKeyboardNavigationLabel(els.map(e => e.element as T));
}
}
};
}
export interface ICompressibleAsyncDataTreeOptions<T, TFilterData = void> extends IAsyncDataTreeOptions<T, TFilterData> {
readonly compressionEnabled?: boolean;
readonly keyboardNavigationLabelProvider?: ICompressibleKeyboardNavigationLabelProvider<T>;
}
export interface ICompressibleAsyncDataTreeOptionsUpdate extends IAsyncDataTreeOptionsUpdate {
readonly compressionEnabled?: boolean;
}
export class CompressibleAsyncDataTree<TInput, T, TFilterData = void> extends AsyncDataTree<TInput, T, TFilterData> {
protected override readonly tree!: CompressibleObjectTree<IAsyncDataTreeNode<TInput, T>, TFilterData>;
protected readonly compressibleNodeMapper: CompressibleAsyncDataTreeNodeMapper<TInput, T, TFilterData> = new WeakMapper(node => new CompressibleAsyncDataTreeNodeWrapper(node));
private filter?: ITreeFilter<T, TFilterData>;
constructor(
user: string,
container: HTMLElement,
virtualDelegate: IListVirtualDelegate<T>,
private compressionDelegate: ITreeCompressionDelegate<T>,
renderers: ICompressibleTreeRenderer<T, TFilterData, any>[],
dataSource: IAsyncDataSource<TInput, T>,
options: ICompressibleAsyncDataTreeOptions<T, TFilterData> = {}
) {
super(user, container, virtualDelegate, renderers, dataSource, options);
this.filter = options.filter;
}
protected override createTree(
user: string,
container: HTMLElement,
delegate: IListVirtualDelegate<T>,
renderers: ICompressibleTreeRenderer<T, TFilterData, any>[],
options: ICompressibleAsyncDataTreeOptions<T, TFilterData>
): ObjectTree<IAsyncDataTreeNode<TInput, T>, TFilterData> {
const objectTreeDelegate = new ComposedTreeDelegate<TInput | T, IAsyncDataTreeNode<TInput, T>>(delegate);
const objectTreeRenderers = renderers.map(r => new CompressibleAsyncDataTreeRenderer(r, this.nodeMapper, () => this.compressibleNodeMapper, this._onDidChangeNodeSlowState.event));
const objectTreeOptions = asCompressibleObjectTreeOptions<TInput, T, TFilterData>(options) || {};
return new CompressibleObjectTree(user, container, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
}
protected override asTreeElement(node: IAsyncDataTreeNode<TInput, T>, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): ICompressedTreeElement<IAsyncDataTreeNode<TInput, T>> {
return {
incompressible: this.compressionDelegate.isIncompressible(node.element as T),
...super.asTreeElement(node, viewStateContext)
};
}
override updateOptions(options: ICompressibleAsyncDataTreeOptionsUpdate = {}): void {
this.tree.updateOptions(options);
}
override getViewState(): IAsyncDataTreeViewState {
if (!this.identityProvider) {
throw new TreeError(this.user, 'Can\'t get tree view state without an identity provider');
}
const getId = (element: T) => this.identityProvider!.getId(element).toString();
const focus = this.getFocus().map(getId);
const selection = this.getSelection().map(getId);
const expanded: string[] = [];
const root = this.tree.getCompressedTreeNode();
const queue = [root];
while (queue.length > 0) {
const node = queue.shift()!;
if (node !== root && node.collapsible && !node.collapsed) {
for (const asyncNode of node.element!.elements) {
expanded.push(getId(asyncNode.element as T));
}
}
queue.push(...node.children);
}
return { focus, selection, expanded, scrollTop: this.scrollTop };
}
protected override render(node: IAsyncDataTreeNode<TInput, T>, viewStateContext?: IAsyncDataTreeViewStateContext<TInput, T>): void {
if (!this.identityProvider) {
return super.render(node, viewStateContext);
}
// Preserve traits across compressions. Hacky but does the trick.
// This is hard to fix properly since it requires rewriting the traits
// across trees and lists. Let's just keep it this way for now.
const getId = (element: T) => this.identityProvider!.getId(element).toString();
const getUncompressedIds = (nodes: IAsyncDataTreeNode<TInput, T>[]): Set<string> => {
const result = new Set<string>();
for (const node of nodes) {
const compressedNode = this.tree.getCompressedTreeNode(node === this.root ? null : node);
if (!compressedNode.element) {
continue;
}
for (const node of compressedNode.element.elements) {
result.add(getId(node.element as T));
}
}
return result;
};
const oldSelection = getUncompressedIds(this.tree.getSelection() as IAsyncDataTreeNode<TInput, T>[]);
const oldFocus = getUncompressedIds(this.tree.getFocus() as IAsyncDataTreeNode<TInput, T>[]);
super.render(node, viewStateContext);
const selection = this.getSelection();
let didChangeSelection = false;
const focus = this.getFocus();
let didChangeFocus = false;
const visit = (node: ITreeNode<ICompressedTreeNode<IAsyncDataTreeNode<TInput, T>> | null, TFilterData>) => {
const compressedNode = node.element;
if (compressedNode) {
for (let i = 0; i < compressedNode.elements.length; i++) {
const id = getId(compressedNode.elements[i].element as T);
const element = compressedNode.elements[compressedNode.elements.length - 1].element as T;
// github.com/microsoft/vscode/issues/85938
if (oldSelection.has(id) && selection.indexOf(element) === -1) {
selection.push(element);
didChangeSelection = true;
}
if (oldFocus.has(id) && focus.indexOf(element) === -1) {
focus.push(element);
didChangeFocus = true;
}
}
}
node.children.forEach(visit);
};
visit(this.tree.getCompressedTreeNode(node === this.root ? null : node));
if (didChangeSelection) {
this.setSelection(selection);
}
if (didChangeFocus) {
this.setFocus(focus);
}
}
// For compressed async data trees, `TreeVisibility.Recurse` doesn't currently work
// and we have to filter everything beforehand
// Related to #85193 and #85835
protected override processChildren(children: Iterable<T>): Iterable<T> {
if (this.filter) {
children = Iterable.filter(children, e => {
const result = this.filter!.filter(e, TreeVisibility.Visible);
const visibility = getVisibility(result);
if (visibility === TreeVisibility.Recurse) {
throw new Error('Recursive tree visibility not supported in async data compressed trees');
}
return visibility === TreeVisibility.Visible;
});
}
return super.processChildren(children);
}
}
function getVisibility<TFilterData>(filterResult: TreeFilterResult<TFilterData>): TreeVisibility {
if (typeof filterResult === 'boolean') {
return filterResult ? TreeVisibility.Visible : TreeVisibility.Hidden;
} else if (isFilterResult(filterResult)) {
return getVisibleState(filterResult.visibility);
} else {
return getVisibleState(filterResult);
}
} | the_stack |
import Reconciler from 'react-reconciler'
import * as OGL from 'ogl'
import * as React from 'react'
import { toPascalCase, applyProps, attach, detach, classExtends } from './utils'
import { RESERVED_PROPS } from './constants'
import { Fiber, Instance, InstanceProps } from './types'
// Custom objects that extend the OGL namespace
const catalogue: { [name: string]: any } = {}
// Effectful catalogue elements that require a `WebGLRenderingContext`.
const catalogueGL: any[] = [
// Core
OGL.Camera,
OGL.Geometry,
OGL.Mesh,
OGL.Program,
OGL.RenderTarget,
OGL.Texture,
// Extras
OGL.Flowmap,
OGL.GPGPU,
OGL.NormalProgram,
OGL.Polyline,
OGL.Post,
OGL.Shadow,
]
/**
* Extends the OGL namespace, accepting an object of keys pointing to external classes.
* `passGL` will flag the element to receive a `WebGLRenderingContext` on creation.
*/
export const extend = (objects: typeof catalogue, passGL = false) => {
for (const key in objects) {
const value = objects[key]
catalogue[key] = value
if (passGL) catalogueGL.push(value)
}
}
/**
* Creates an OGL element from a React node.
*/
const createInstance = (type: string, { object = null, args = [], ...props }: InstanceProps, root: Fiber) => {
// Convert lowercase primitive to PascalCase
const name = toPascalCase(type)
// Get class from extended OGL namespace
const target = catalogue[name] ?? OGL[name]
// Validate OGL elements
if (type !== 'primitive' && !target) throw `${type} is not a part of the OGL catalogue! Did you forget to extend?`
// Validate primitives
if (type === 'primitive' && !object) throw `"object" must be set when using primitives.`
// Create instance
const instance: Instance = {
root,
parent: null,
children: [],
type,
props: { ...props, args },
object,
}
return instance
}
/**
* Adds elements to our scene and attaches children to their parents.
*/
const appendChild = (parent: Instance, child: Instance) => {
child.parent = parent
parent.children.push(child)
}
/**
* Removes elements from scene and disposes of them.
*/
const removeChild = (parent: Instance, child: Instance) => {
child.parent = null
const childIndex = parent.children.indexOf(child)
if (childIndex !== -1) parent.children.splice(childIndex, 1)
if (child.props.attach) detach(parent, child)
else if (child.object instanceof OGL.Transform) parent.object.removeChild(child.object)
if (child.props.dispose !== null) child.object.dispose?.()
child.object = null
}
const commitInstance = (instance: Instance) => {
// Don't handle commit for containers
if (!instance.parent) return
if (instance.type !== 'primitive' && !instance.object) {
const name = toPascalCase(instance.type)
const target = catalogue[name] ?? OGL[name]
// Pass internal state to elements which depend on it.
// This lets them be immutable upon creation and use props
const isGLInstance = Object.values(catalogueGL).some((elem) => classExtends(elem, target))
if (isGLInstance) {
const { gl } = instance.root.getState()
const { args, ...props } = instance.props
const attrs = args.find((arg) => arg !== gl) ?? {}
// Accept props as args
const propAttrs = Object.entries(props).reduce((acc, [key, value]) => {
if (!key.includes('-')) acc[key] = value
return acc
}, attrs)
instance.object = new target(gl, propAttrs)
} else {
instance.object = new target(...instance.props.args)
}
}
// Auto-attach geometry and programs to meshes
if (!instance.props.attach) {
if (instance.object instanceof OGL.Geometry) {
instance.props.attach = 'geometry'
} else if (instance.object instanceof OGL.Program) {
instance.props.attach = 'program'
}
}
// Append children
for (const child of instance.children) {
if (child.props.attach) {
attach(instance, child)
} else if (child.object instanceof OGL.Transform) {
child.object.setParent(instance.object)
}
}
// Append to container
if (!instance.parent.parent) {
if (instance.props.attach) {
attach(instance.parent, instance)
} else if (instance.object instanceof OGL.Transform) {
instance.object.setParent(instance.parent.object)
}
}
applyProps(instance.object, instance.props)
}
/**
* Switches instance to a new one, moving over children.
*/
const switchInstance = (instance: Instance, type: string, props: InstanceProps, root: Fiber) => {
// Create a new instance
const newInstance = createInstance(type, props, root)
// Replace instance in scene-graph
const parent = instance.parent
if (instance.props.attach) detach(parent, instance)
removeChild(parent, instance)
appendChild(parent, newInstance)
// Commit new instance object
commitInstance(newInstance)
// Append to scene-graph
if (parent.parent) {
if (newInstance.props.attach) {
attach(parent, newInstance)
} else if (newInstance.object instanceof OGL.Transform) {
newInstance.object.setParent(parent.object)
}
}
// Move children to new instance
if (instance.type !== 'primitive') {
for (const child of instance.children) {
appendChild(newInstance, child)
if (child.props.attach) {
detach(instance, child)
attach(newInstance, child)
}
}
instance.children = []
}
// Switches the react-internal fiber node
// https://github.com/facebook/react/issues/14983
;[root, root.alternate].forEach((fiber) => {
if (fiber !== null) {
fiber.stateNode = newInstance
if (fiber.ref) {
if (typeof fiber.ref === 'function') (fiber as unknown as any).ref(newInstance.object)
else (fiber.ref as Reconciler.RefObject).current = newInstance.object
}
}
})
return newInstance
}
/**
* Shallow checks objects.
*/
const checkShallow = (a: any, b: any) => {
// If comparing arrays, shallow compare
if (Array.isArray(a)) {
// Check if types match
if (!Array.isArray(b)) return false
// Shallow compare for match
if (a == b) return true
// Sort through keys
if (a.every((v, i) => v === b[i])) return true
}
// Atomically compare
if (a === b) return true
return false
}
/**
* Prepares a set of changes to be applied to the instance.
*/
const diffProps = (instance: Instance, newProps: InstanceProps, oldProps: InstanceProps) => {
const changedProps: InstanceProps = {}
// Sort through props
for (const key in newProps) {
// Skip reserved keys
if (RESERVED_PROPS.includes(key as typeof RESERVED_PROPS[number])) continue
// Skip primitives
if (instance.type === 'primitive' && key === 'object') continue
// Skip if props match
if (checkShallow(newProps[key], oldProps[key])) continue
// Props changed, add them
changedProps[key] = newProps[key]
}
return changedProps
}
/**
* Inserts an instance between instances of a ReactNode.
*/
const insertBefore = (parent: Instance, child: Instance, beforeChild: Instance) => {
if (!child) return
child.parent = parent
parent.children.splice(parent.children.indexOf(beforeChild), 0, child)
}
/**
* Centralizes and handles mutations through an OGL scene-graph.
*/
export const reconciler = Reconciler({
// Configure renderer for tree-like mutation and interop w/react-dom
isPrimaryRenderer: false,
supportsMutation: true,
supportsHydration: false,
supportsPersistence: false,
// Add SSR time fallbacks
now: typeof performance !== 'undefined' ? performance.now : Date.now,
scheduleTimeout: typeof setTimeout !== 'undefined' ? setTimeout : undefined,
cancelTimeout: typeof clearTimeout !== 'undefined' ? clearTimeout : undefined,
noTimeout: -1,
// Text isn't supported so we skip it
shouldSetTextContent: () => false,
createTextInstance: () => console.warn('Text is not allowed in the OGL scene-graph!'),
// Modifies the ref to return the instance object itself.
getPublicInstance: (instance: Instance) => instance.object,
// We can optionally access different host contexts on instance creation/update.
// Instances' data structures are self-sufficient, so we don't make use of this
getRootHostContext: () => null,
getChildHostContext: (parentHostContext: any) => parentHostContext,
// We can optionally mutate portal containers here, but we do that in createPortal instead from state
preparePortalMount: (container: any) => container,
// This lets us store stuff at the container-level before/after React mutates our OGL elements.
// Elements are mutated in isolation, so we don't do anything here.
prepareForCommit: () => null,
resetAfterCommit: () => {},
// This can modify the container and clear children.
// Might be useful for disposing on demand later
clearContainer: () => false,
// This creates a OGL element from a React element
createInstance,
// These methods add elements to the scene
appendChild,
appendInitialChild: appendChild,
appendChildToContainer: () => {},
// These methods remove elements from the scene
removeChild,
removeChildFromContainer: () => {},
// We can specify an order for children to be inserted here.
// This is useful if you want to override stuff like materials
insertBefore,
insertInContainerBefore: () => {},
// Used to calculate updates in the render phase or commitUpdate.
// Greatly improves performance by reducing paint to rapid mutations.
// Returns [shouldReconstruct: boolean, changedProps: Record<string, any>]
prepareUpdate(instance: Instance, type: string, oldProps: InstanceProps, newProps: InstanceProps) {
// Element is a primitive. We must recreate it when its object prop is changed
if (instance.type === 'primitive' && oldProps.object !== newProps.object) return [true]
// Element is a program. Check whether its vertex or fragment props changed to recreate
if (type === 'program') {
if (oldProps.vertex !== newProps.vertex) return [true]
if (oldProps.fragment !== newProps.fragment) return [true]
}
// Element is a geometry. Check whether its attribute props changed to recreate.
if (instance instanceof OGL.Geometry) {
for (const key in oldProps) {
if (!key.startsWith('attributes-') && oldProps[key] !== newProps[key]) return [true]
}
}
// If the instance has new args, recreate it
if (newProps.args?.some((value, index) => value !== oldProps.args[index])) return [true]
// Diff through props and flag with changes
const changedProps = diffProps(instance, newProps, oldProps)
if (Object.keys(changedProps).length) return [false, changedProps]
// No changes, don't update the instance
return null
},
// This is where we mutate OGL elements in the render phase
commitUpdate(
instance: Instance,
[reconstruct, changedProps]: [boolean, InstanceProps],
type: string,
oldProps: InstanceProps,
newProps: InstanceProps,
root: Fiber,
) {
// If flagged for recreation, swap to a new instance.
if (reconstruct) return switchInstance(instance, type, newProps, root)
// Handle attach update
if (changedProps.attach) {
if (oldProps.attach) detach(instance.parent, instance)
instance.props.attach = newProps.attach
if (newProps.attach) attach(instance.parent, instance)
}
// Update instance props
Object.assign(instance.props, newProps)
// Apply changed props
applyProps(instance.object, newProps)
},
// Methods to toggle instance visibility on demand.
// React uses this with React.Suspense to display fallback content
hideInstance(instance: Instance) {
if (instance.object instanceof OGL.Transform) {
instance.object.visible = false
}
},
unhideInstance(instance: Instance) {
if (instance.object instanceof OGL.Transform) {
instance.object.visible = (instance.props.visible as boolean) ?? true
}
},
// Configures a callback once finalized and instances are linked up to one another.
// This is a safe time to create instances' respective OGL elements without worrying
// about side-effects if react changes its mind and discards an instance (e.g. React.Suspense)
finalizeInitialChildren: () => true,
commitMount: commitInstance,
})
// Inject renderer meta into devtools
const isProd = typeof process === 'undefined' || process.env?.['NODE_ENV'] === 'production'
reconciler.injectIntoDevTools({
findFiberByHostInstance: (instance: Instance) => instance.root,
bundleType: isProd ? 0 : 1,
version: React.version,
rendererPackageName: 'react-ogl',
}) | the_stack |
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
import {
check,
getBrowserBodyText,
getRedboxHeader,
getRedboxSource,
hasRedbox,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
describe('basic HMR', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(join(__dirname, 'hmr/pages')),
components: new FileRef(join(__dirname, 'hmr/components')),
},
})
})
afterAll(() => next.destroy())
describe('Hot Module Reloading', () => {
describe('delete a page and add it back', () => {
it('should load the page properly', async () => {
const contactPagePath = join('pages', 'hmr', 'contact.js')
const newContactPagePath = join('pages', 'hmr', '_contact.js')
let browser
try {
const start = next.cliOutput.length
browser = await webdriver(next.appPort, '/hmr/contact')
const text = await browser.elementByCss('p').text()
expect(text).toBe('This is the contact page.')
// Rename the file to mimic a deleted page
await next.renameFile(contactPagePath, newContactPagePath)
await check(
() => getBrowserBodyText(browser),
/This page could not be found/
)
// Rename the file back to the original filename
await next.renameFile(newContactPagePath, contactPagePath)
// wait until the page comes back
await check(
() => getBrowserBodyText(browser),
/This is the contact page/
)
expect(next.cliOutput.slice(start)).toContain('compiling...')
expect(next.cliOutput.slice(start)).toContain(
'compiling /hmr/contact (client and server)...'
)
expect(next.cliOutput).toContain(
'compiling /_error (client and server)...'
)
} finally {
if (browser) {
await browser.close()
}
await next
.renameFile(newContactPagePath, contactPagePath)
.catch(() => {})
}
})
})
describe('editing a page', () => {
it('should detect the changes and display it', async () => {
let browser
try {
browser = await webdriver(next.appPort, '/hmr/about')
const text = await browser.elementByCss('p').text()
expect(text).toBe('This is the about page.')
const aboutPagePath = join('pages', 'hmr', 'about.js')
const originalContent = await next.readFile(aboutPagePath)
const editedContent = originalContent.replace(
'This is the about page',
'COOL page'
)
// change the content
try {
await next.patchFile(aboutPagePath, editedContent)
await check(() => getBrowserBodyText(browser), /COOL page/)
} finally {
// add the original content
await next.patchFile(aboutPagePath, originalContent)
}
await check(
() => getBrowserBodyText(browser),
/This is the about page/
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should not reload unrelated pages', async () => {
let browser
try {
browser = await webdriver(next.appPort, '/hmr/counter')
const text = await browser
.elementByCss('button')
.click()
.elementByCss('button')
.click()
.elementByCss('p')
.text()
expect(text).toBe('COUNT: 2')
const aboutPagePath = join('pages', 'hmr', 'about.js')
const originalContent = await next.readFile(aboutPagePath)
const editedContent = originalContent.replace(
'This is the about page',
'COOL page'
)
try {
// Change the about.js page
await next.patchFile(aboutPagePath, editedContent)
// Check whether the this page has reloaded or not.
await check(() => browser.elementByCss('p').text(), /COUNT: 2/)
} finally {
// restore the about page content.
await next.patchFile(aboutPagePath, originalContent)
}
} finally {
if (browser) {
await browser.close()
}
}
})
// Added because of a regression in react-hot-loader, see issues: #4246 #4273
// Also: https://github.com/vercel/styled-jsx/issues/425
it('should update styles correctly', async () => {
let browser
try {
browser = await webdriver(next.appPort, '/hmr/style')
const pTag = await browser.elementByCss('.hmr-style-page p')
const initialFontSize = await pTag.getComputedCss('font-size')
expect(initialFontSize).toBe('100px')
const pagePath = join('pages', 'hmr', 'style.js')
const originalContent = await next.readFile(pagePath)
const editedContent = originalContent.replace('100px', '200px')
// Change the page
await next.patchFile(pagePath, editedContent)
try {
// Check whether the this page has reloaded or not.
await check(async () => {
const editedPTag = await browser.elementByCss('.hmr-style-page p')
return editedPTag.getComputedCss('font-size')
}, /200px/)
} finally {
// Finally is used so that we revert the content back to the original regardless of the test outcome
// restore the about page content.
await next.patchFile(pagePath, originalContent)
}
} finally {
if (browser) {
await browser.close()
}
}
})
// Added because of a regression in react-hot-loader, see issues: #4246 #4273
// Also: https://github.com/vercel/styled-jsx/issues/425
it('should update styles in a stateful component correctly', async () => {
let browser
const pagePath = join('pages', 'hmr', 'style-stateful-component.js')
const originalContent = await next.readFile(pagePath)
try {
browser = await webdriver(
next.appPort,
'/hmr/style-stateful-component'
)
const pTag = await browser.elementByCss('.hmr-style-page p')
const initialFontSize = await pTag.getComputedCss('font-size')
expect(initialFontSize).toBe('100px')
const editedContent = originalContent.replace('100px', '200px')
// Change the page
await next.patchFile(pagePath, editedContent)
// Check whether the this page has reloaded or not.
await check(async () => {
const editedPTag = await browser.elementByCss('.hmr-style-page p')
return editedPTag.getComputedCss('font-size')
}, /200px/)
} finally {
if (browser) {
await browser.close()
}
await next.patchFile(pagePath, originalContent)
}
})
// Added because of a regression in react-hot-loader, see issues: #4246 #4273
// Also: https://github.com/vercel/styled-jsx/issues/425
it('should update styles in a dynamic component correctly', async () => {
let browser = null
let secondBrowser = null
const pagePath = join('components', 'hmr', 'dynamic.js')
const originalContent = await next.readFile(pagePath)
try {
browser = await webdriver(
next.appPort,
'/hmr/style-dynamic-component'
)
const div = await browser.elementByCss('#dynamic-component')
const initialClientClassName = await div.getAttribute('class')
const initialFontSize = await div.getComputedCss('font-size')
expect(initialFontSize).toBe('100px')
const initialHtml = await renderViaHTTP(
next.appPort,
'/hmr/style-dynamic-component'
)
expect(initialHtml.includes('100px')).toBeTruthy()
const $initialHtml = cheerio.load(initialHtml)
const initialServerClassName =
$initialHtml('#dynamic-component').attr('class')
expect(initialClientClassName === initialServerClassName).toBeTruthy()
const editedContent = originalContent.replace('100px', '200px')
// Change the page
await next.patchFile(pagePath, editedContent)
// wait for 5 seconds
await waitFor(5000)
secondBrowser = await webdriver(
next.appPort,
'/hmr/style-dynamic-component'
)
// Check whether the this page has reloaded or not.
const editedDiv = await secondBrowser.elementByCss(
'#dynamic-component'
)
const editedClientClassName = await editedDiv.getAttribute('class')
const editedFontSize = await editedDiv.getComputedCss('font-size')
const browserHtml = await secondBrowser.eval(
'document.documentElement.innerHTML'
)
expect(editedFontSize).toBe('200px')
expect(browserHtml.includes('font-size:200px')).toBe(true)
expect(browserHtml.includes('font-size:100px')).toBe(false)
const editedHtml = await renderViaHTTP(
next.appPort,
'/hmr/style-dynamic-component'
)
expect(editedHtml.includes('200px')).toBeTruthy()
const $editedHtml = cheerio.load(editedHtml)
const editedServerClassName =
$editedHtml('#dynamic-component').attr('class')
expect(editedClientClassName === editedServerClassName).toBe(true)
} finally {
// Finally is used so that we revert the content back to the original regardless of the test outcome
// restore the about page content.
await next.patchFile(pagePath, originalContent)
if (browser) {
await browser.close()
}
if (secondBrowser) {
secondBrowser.close()
}
}
})
})
})
describe('Error Recovery', () => {
it('should recover from 404 after a page has been added', async () => {
let browser
const newPage = join('pages', 'hmr', 'new-page.js')
try {
const start = next.cliOutput.length
browser = await webdriver(next.appPort, '/hmr/new-page')
expect(await browser.elementByCss('body').text()).toMatch(
/This page could not be found/
)
// Add the page
await next.patchFile(
newPage,
'export default () => (<div id="new-page">the-new-page</div>)'
)
await check(() => getBrowserBodyText(browser), /the-new-page/)
await next.deleteFile(newPage)
await check(
() => getBrowserBodyText(browser),
/This page could not be found/
)
expect(next.cliOutput.slice(start)).toContain(
'compiling /hmr/new-page (client and server)...'
)
expect(next.cliOutput).toContain(
'compiling /_error (client and server)...'
)
} catch (err) {
await next.deleteFile(newPage)
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
it('should detect syntax errors and recover', async () => {
let browser
const aboutPage = join('pages', 'hmr', 'about2.js')
const aboutContent = await next.readFile(aboutPage)
try {
const start = next.cliOutput.length
browser = await webdriver(next.appPort, '/hmr/about2')
await check(() => getBrowserBodyText(browser), /This is the about page/)
await next.patchFile(aboutPage, aboutContent.replace('</div>', 'div'))
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxSource(browser)).toMatch(/Unexpected eof/)
await next.patchFile(aboutPage, aboutContent)
await check(() => getBrowserBodyText(browser), /This is the about page/)
expect(next.cliOutput.slice(start)).toContain(
'compiling /hmr/about2 (client and server)...'
)
expect(next.cliOutput).toContain(
'compiling /_error (client and server)...'
)
} catch (err) {
await next.patchFile(aboutPage, aboutContent)
if (browser) {
await check(
() => getBrowserBodyText(browser),
/This is the about page/
)
}
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
it('should show the error on all pages', async () => {
const aboutPage = join('pages', 'hmr', 'about2.js')
const aboutContent = await next.readFile(aboutPage)
let browser
try {
await renderViaHTTP(next.appPort, '/hmr/about2')
await next.patchFile(aboutPage, aboutContent.replace('</div>', 'div'))
// Ensure dev server has time to break:
await new Promise((resolve) => setTimeout(resolve, 2000))
browser = await webdriver(next.appPort, '/hmr/contact')
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxSource(browser)).toMatch(/Unexpected eof/)
await next.patchFile(aboutPage, aboutContent)
await check(
() => getBrowserBodyText(browser),
/This is the contact page/
)
} catch (err) {
await next.patchFile(aboutPage, aboutContent)
if (browser) {
await check(
() => getBrowserBodyText(browser),
/This is the contact page/
)
}
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
it('should detect runtime errors on the module scope', async () => {
let browser
const aboutPage = join('pages', 'hmr', 'about3.js')
const aboutContent = await next.readFile(aboutPage)
try {
browser = await webdriver(next.appPort, '/hmr/about3')
await check(() => getBrowserBodyText(browser), /This is the about page/)
await next.patchFile(
aboutPage,
aboutContent.replace('export', 'aa=20;\nexport')
)
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(/aa is not defined/)
await next.patchFile(aboutPage, aboutContent)
await check(() => getBrowserBodyText(browser), /This is the about page/)
} finally {
await next.patchFile(aboutPage, aboutContent)
if (browser) {
await browser.close()
}
}
})
it('should recover from errors in the render function', async () => {
let browser
const aboutPage = join('pages', 'hmr', 'about4.js')
const aboutContent = await next.readFile(aboutPage)
try {
browser = await webdriver(next.appPort, '/hmr/about4')
await check(() => getBrowserBodyText(browser), /This is the about page/)
await next.patchFile(
aboutPage,
aboutContent.replace(
'return',
'throw new Error("an-expected-error");\nreturn'
)
)
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxSource(browser)).toMatch(/an-expected-error/)
await next.patchFile(aboutPage, aboutContent)
await check(() => getBrowserBodyText(browser), /This is the about page/)
} catch (err) {
await next.patchFile(aboutPage, aboutContent)
if (browser) {
await check(
() => getBrowserBodyText(browser),
/This is the about page/
)
}
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
it('should recover after exporting an invalid page', async () => {
let browser
const aboutPage = join('pages', 'hmr', 'about5.js')
const aboutContent = await next.readFile(aboutPage)
try {
browser = await webdriver(next.appPort, '/hmr/about5')
await check(() => getBrowserBodyText(browser), /This is the about page/)
await next.patchFile(
aboutPage,
aboutContent.replace(
'export default',
'export default {};\nexport const fn ='
)
)
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(`
" 1 of 1 unhandled error
Server Error
Error: The default export is not a React Component in page: \\"/hmr/about5\\"
This error happened while generating the page. Any console logs will be displayed in the terminal window."
`)
await next.patchFile(aboutPage, aboutContent)
await check(() => getBrowserBodyText(browser), /This is the about page/)
} catch (err) {
await next.patchFile(aboutPage, aboutContent)
if (browser) {
await check(
() => getBrowserBodyText(browser),
/This is the about page/
)
}
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
it('should recover after a bad return from the render function', async () => {
let browser
const aboutPage = join('pages', 'hmr', 'about6.js')
const aboutContent = await next.readFile(aboutPage)
try {
browser = await webdriver(next.appPort, '/hmr/about6')
await check(() => getBrowserBodyText(browser), /This is the about page/)
await next.patchFile(
aboutPage,
aboutContent.replace(
'export default',
'export default () => /search/;\nexport const fn ='
)
)
expect(await hasRedbox(browser)).toBe(true)
// TODO: Replace this when webpack 5 is the default
expect(
(await getRedboxHeader(browser)).replace(
'__WEBPACK_DEFAULT_EXPORT__',
'Unknown'
)
).toMatch(
'Objects are not valid as a React child (found: /search/). If you meant to render a collection of children, use an array instead.'
)
await next.patchFile(aboutPage, aboutContent)
await check(() => getBrowserBodyText(browser), /This is the about page/)
} catch (err) {
await next.patchFile(aboutPage, aboutContent)
if (browser) {
await check(
() => getBrowserBodyText(browser),
/This is the about page/
)
}
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
it('should recover after undefined exported as default', async () => {
let browser
const aboutPage = join('pages', 'hmr', 'about7.js')
const aboutContent = await next.readFile(aboutPage)
try {
browser = await webdriver(next.appPort, '/hmr/about7')
await check(() => getBrowserBodyText(browser), /This is the about page/)
await next.patchFile(
aboutPage,
aboutContent.replace(
'export default',
'export default undefined;\nexport const fn ='
)
)
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(`
" 1 of 1 unhandled error
Server Error
Error: The default export is not a React Component in page: \\"/hmr/about7\\"
This error happened while generating the page. Any console logs will be displayed in the terminal window."
`)
await next.patchFile(aboutPage, aboutContent)
await check(() => getBrowserBodyText(browser), /This is the about page/)
expect(await hasRedbox(browser, false)).toBe(false)
} catch (err) {
await next.patchFile(aboutPage, aboutContent)
if (browser) {
await check(
() => getBrowserBodyText(browser),
/This is the about page/
)
}
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
it('should recover from errors in getInitialProps in client', async () => {
let browser
const erroredPage = join('pages', 'hmr', 'error-in-gip.js')
const errorContent = await next.readFile(erroredPage)
try {
browser = await webdriver(next.appPort, '/hmr')
await browser.elementByCss('#error-in-gip-link').click()
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(`
" 1 of 1 unhandled error
Unhandled Runtime Error
Error: an-expected-error-in-gip"
`)
await next.patchFile(
erroredPage,
errorContent.replace('throw error', 'return {}')
)
await check(() => getBrowserBodyText(browser), /Hello/)
await next.patchFile(erroredPage, errorContent)
await check(async () => {
await browser.refresh()
const text = await browser.elementByCss('body').text()
if (text.includes('Hello')) {
await waitFor(2000)
throw new Error('waiting')
}
return getRedboxSource(browser)
}, /an-expected-error-in-gip/)
} catch (err) {
await next.patchFile(erroredPage, errorContent)
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
it('should recover after an error reported via SSR', async () => {
let browser
const erroredPage = join('pages', 'hmr', 'error-in-gip.js')
const errorContent = await next.readFile(erroredPage)
try {
browser = await webdriver(next.appPort, '/hmr/error-in-gip')
expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(`
" 1 of 1 unhandled error
Server Error
Error: an-expected-error-in-gip
This error happened while generating the page. Any console logs will be displayed in the terminal window."
`)
const erroredPage = join('pages', 'hmr', 'error-in-gip.js')
await next.patchFile(
erroredPage,
errorContent.replace('throw error', 'return {}')
)
await check(() => getBrowserBodyText(browser), /Hello/)
await next.patchFile(erroredPage, errorContent)
await check(async () => {
await browser.refresh()
const text = await getBrowserBodyText(browser)
if (text.includes('Hello')) {
await waitFor(2000)
throw new Error('waiting')
}
return getRedboxSource(browser)
}, /an-expected-error-in-gip/)
} catch (err) {
await next.patchFile(erroredPage, errorContent)
throw err
} finally {
if (browser) {
await browser.close()
}
}
})
})
}) | the_stack |
import { compilerAssert } from "./diagnostics.js";
import { NodeFlags, visitChildren } from "./parser.js";
import { Program } from "./program.js";
import {
AliasStatementNode,
CadlScriptNode,
ContainerNode,
Declaration,
DecoratorSymbol,
EnumStatementNode,
ExportSymbol,
IdentifierNode,
InterfaceStatementNode,
JsSourceFile,
LocalSymbol,
ModelStatementNode,
NamespaceStatementNode,
Node,
OperationStatementNode,
ScopeNode,
Sym,
SymbolTable,
SyntaxKind,
TemplateParameterDeclarationNode,
TypeSymbol,
UnionStatementNode,
UsingStatementNode,
Writable,
} from "./types.js";
// Use a regular expression to define the prefix for Cadl-exposed functions
// defined in JavaScript modules
const DecoratorFunctionPattern = /^\$/;
const SymbolTable = class<T extends Sym> extends Map<string, T> implements SymbolTable<T> {
duplicates = new Map<T, Set<T>>();
// First set for a given key wins, but record all duplicates for diagnostics.
set(key: string, value: T) {
const existing = super.get(key);
if (existing === undefined) {
super.set(key, value);
} else {
if (existing.kind === "using") {
existing.duplicate = true;
}
const duplicateArray = this.duplicates.get(existing);
if (duplicateArray) {
duplicateArray.add(value);
} else {
this.duplicates.set(existing, new Set([existing, value]));
}
}
return this;
}
};
export interface Binder {
bindSourceFile(sourceFile: CadlScriptNode): void;
bindJsSourceFile(sourceFile: JsSourceFile): void;
bindNode(node: Node): void;
}
export function createSymbolTable<T extends Sym>(): SymbolTable<T> {
return new SymbolTable<T>();
}
export interface BinderOptions {
// Configures the initial parent node to use when calling bindNode. This is
// useful for binding Cadl fragments outside the context of a full script node.
initialParentNode?: Node;
}
export function createBinder(program: Program, options: BinderOptions = {}): Binder {
let currentFile: CadlScriptNode;
let parentNode: Node | undefined = options?.initialParentNode;
let fileNamespace: NamespaceStatementNode | CadlScriptNode;
let currentNamespace: ContainerNode;
let isJsFile = false;
// Node where locals go.
let scope: ScopeNode | JsSourceFile;
return {
bindSourceFile,
bindNode,
bindJsSourceFile,
};
function isFunctionName(name: string): boolean {
return DecoratorFunctionPattern.test(name);
}
function getFunctionName(name: string): string {
return name.replace(DecoratorFunctionPattern, "");
}
function bindJsSourceFile(sourceFile: JsSourceFile) {
sourceFile.exports = createSymbolTable();
isJsFile = true;
const rootNs = sourceFile.esmExports["namespace"];
const namespaces = new Set<NamespaceStatementNode>();
for (const [key, member] of Object.entries(sourceFile.esmExports)) {
if (typeof member === "function" && isFunctionName(key)) {
// lots of 'any' casts here because control flow narrowing `member` to Function
// isn't particularly useful it turns out.
const name = getFunctionName(key);
if (name === "onBuild") {
program.onBuild(member as any);
continue;
}
const memberNs: string = (member as any).namespace;
const nsParts = [];
if (rootNs) {
nsParts.push(...rootNs.split("."));
}
if (memberNs) {
nsParts.push(...memberNs.split("."));
}
scope = sourceFile;
for (const part of nsParts) {
const existingBinding = scope.exports!.get(part);
if (
existingBinding &&
existingBinding.kind === "type" &&
namespaces.has(existingBinding.node as NamespaceStatementNode)
) {
// since the namespace was "declared" as part of this source file,
// we can simply re-use it.
scope = existingBinding.node as NamespaceStatementNode;
} else {
// need to synthesize a namespace declaration node
// consider creating a "synthetic" node flag if necessary
const nsNode = createSyntheticNamespace(part);
if (existingBinding && existingBinding.kind === "type") {
nsNode.symbol = existingBinding;
nsNode.exports = (existingBinding.node as NamespaceStatementNode).exports;
} else {
declareSymbol(scope.exports!, nsNode, part);
}
namespaces.add(nsNode);
scope = nsNode;
}
}
const sym = createDecoratorSymbol(name, sourceFile.file.path, member);
scope.exports!.set(sym.name, sym);
}
}
(sourceFile as any).namespaces = Array.from(namespaces);
}
function bindSourceFile(sourceFile: Writable<CadlScriptNode>) {
isJsFile = false;
sourceFile.exports = createSymbolTable();
fileNamespace = currentFile = sourceFile;
currentNamespace = scope = fileNamespace;
bindNode(sourceFile);
}
function bindNode(node: Node) {
if (!node) return;
// set the node's parent since we're going for a walk anyway
node.parent = parentNode;
switch (node.kind) {
case SyntaxKind.ModelStatement:
bindModelStatement(node);
break;
case SyntaxKind.InterfaceStatement:
bindInterfaceStatement(node);
break;
case SyntaxKind.UnionStatement:
bindUnionStatement(node);
break;
case SyntaxKind.AliasStatement:
bindAliasStatement(node);
break;
case SyntaxKind.EnumStatement:
bindEnumStatement(node);
break;
case SyntaxKind.NamespaceStatement:
bindNamespaceStatement(node);
break;
case SyntaxKind.OperationStatement:
bindOperationStatement(node);
break;
case SyntaxKind.TemplateParameterDeclaration:
bindTemplateParameterDeclaration(node);
break;
case SyntaxKind.UsingStatement:
bindUsingStatement(node);
break;
}
const prevParent = parentNode;
// set parent node when we walk into children
parentNode = node;
if (hasScope(node)) {
const prevScope = scope;
const prevNamespace = currentNamespace;
scope = node;
if (node.kind === SyntaxKind.NamespaceStatement) {
currentNamespace = node;
}
visitChildren(node, bindNode);
if (node.kind !== SyntaxKind.NamespaceStatement && node.locals) {
program.reportDuplicateSymbols(node.locals!);
}
scope = prevScope;
currentNamespace = prevNamespace;
} else {
visitChildren(node, bindNode);
}
// restore parent node
parentNode = prevParent;
}
function getContainingSymbolTable() {
switch (scope.kind) {
case SyntaxKind.NamespaceStatement:
return scope.exports!;
case SyntaxKind.CadlScript:
return fileNamespace.exports!;
case "JsSourceFile":
return scope.exports!;
default:
return scope.locals!;
}
}
function bindTemplateParameterDeclaration(node: TemplateParameterDeclarationNode) {
declareSymbol(getContainingSymbolTable(), node, node.id.sv);
}
function bindModelStatement(node: ModelStatementNode) {
declareSymbol(getContainingSymbolTable(), node, node.id.sv);
// Initialize locals for type parameters
node.locals = new SymbolTable<LocalSymbol>();
}
function bindInterfaceStatement(node: InterfaceStatementNode) {
declareSymbol(getContainingSymbolTable(), node, node.id.sv);
node.locals = new SymbolTable<LocalSymbol>();
}
function bindUnionStatement(node: UnionStatementNode) {
declareSymbol(getContainingSymbolTable(), node, node.id.sv);
node.locals = new SymbolTable<LocalSymbol>();
}
function bindAliasStatement(node: AliasStatementNode) {
declareSymbol(getContainingSymbolTable(), node, node.id.sv);
// Initialize locals for type parameters
node.locals = new SymbolTable<LocalSymbol>();
}
function bindEnumStatement(node: EnumStatementNode) {
declareSymbol(getContainingSymbolTable(), node, node.id.sv);
}
function bindNamespaceStatement(statement: Writable<NamespaceStatementNode>) {
// check if there's an existing symbol for this namespace
const existingBinding = currentNamespace.exports!.get(statement.name.sv);
if (existingBinding && existingBinding.kind === "type") {
statement.symbol = existingBinding;
// locals are never shared.
statement.locals = createSymbolTable();
// todo: don't merge exports
statement.exports = (existingBinding.node as NamespaceStatementNode).exports;
} else {
declareSymbol(getContainingSymbolTable(), statement, statement.name.sv);
// Initialize locals for non-exported symbols
statement.locals = createSymbolTable();
// initialize exports for exported symbols
statement.exports = new SymbolTable<ExportSymbol>();
}
currentFile.namespaces.push(statement);
if (statement.statements === undefined) {
scope = currentNamespace = statement;
fileNamespace = statement;
let current: CadlScriptNode | NamespaceStatementNode = statement;
while (current.kind !== SyntaxKind.CadlScript) {
(currentFile.inScopeNamespaces as NamespaceStatementNode[]).push(current);
current = current.parent as CadlScriptNode | NamespaceStatementNode;
}
}
}
function bindUsingStatement(statement: UsingStatementNode) {
(currentFile.usings as UsingStatementNode[]).push(statement);
}
function bindOperationStatement(statement: OperationStatementNode) {
if (scope.kind !== SyntaxKind.InterfaceStatement) {
declareSymbol(getContainingSymbolTable(), statement, statement.id.sv);
}
}
function declareSymbol(table: SymbolTable<Sym>, node: Writable<Declaration>, name: string) {
compilerAssert(table, "Attempted to declare symbol on non-existent table");
const symbol = createTypeSymbol(node, name);
node.symbol = symbol;
if (scope.kind === SyntaxKind.NamespaceStatement) {
compilerAssert(
node.kind !== SyntaxKind.TemplateParameterDeclaration,
"Attempted to declare template parameter in namespace",
node
);
node.namespaceSymbol = scope.symbol;
} else if (scope.kind === SyntaxKind.CadlScript) {
compilerAssert(
node.kind !== SyntaxKind.TemplateParameterDeclaration,
"Attempted to declare template parameter in global scope",
node
);
if (fileNamespace.kind !== SyntaxKind.CadlScript) {
node.namespaceSymbol = fileNamespace.symbol;
}
}
table.set(name, symbol);
}
}
function hasScope(node: Node): node is ScopeNode {
switch (node.kind) {
case SyntaxKind.ModelStatement:
case SyntaxKind.AliasStatement:
return true;
case SyntaxKind.NamespaceStatement:
return node.statements !== undefined;
case SyntaxKind.CadlScript:
return true;
case SyntaxKind.InterfaceStatement:
return true;
case SyntaxKind.UnionStatement:
return true;
default:
return false;
}
}
function createTypeSymbol(node: Node, name: string): TypeSymbol {
return {
kind: "type",
node,
name,
};
}
function createDecoratorSymbol(name: string, path: string, value: any): DecoratorSymbol {
return {
kind: "decorator",
name: `@` + name,
path,
value,
};
}
function createSyntheticNamespace(
name: string
): Writable<NamespaceStatementNode & { flags: NodeFlags }> {
const nsId: IdentifierNode = {
kind: SyntaxKind.Identifier,
pos: 0,
end: 0,
sv: name,
};
return {
kind: SyntaxKind.NamespaceStatement,
decorators: [],
pos: 0,
end: 0,
name: nsId,
symbol: undefined as any,
locals: createSymbolTable(),
exports: createSymbolTable(),
flags: NodeFlags.Synthetic,
};
} | the_stack |
import { FONT_ROW_RATIO } from './config'
import { addTableBorder, getFillStyle } from './common'
import { Cell, Column, Pos, Row, Table } from './models'
import { DocHandler, jsPDFDocument } from './documentHandler'
import { assign } from './polyfills'
import autoTableText from './autoTableText'
import tablePrinter, { ColumnFitInPageResult } from './tablePrinter'
export function drawTable(jsPDFDoc: jsPDFDocument, table: Table): void {
const settings = table.settings
const startY = settings.startY
const margin = settings.margin
const cursor = {
x: margin.left,
y: startY,
}
const sectionsHeight =
table.getHeadHeight(table.columns) + table.getFootHeight(table.columns)
let minTableBottomPos = startY + margin.bottom + sectionsHeight
if (settings.pageBreak === 'avoid') {
const rows = table.allRows()
const tableHeight = rows.reduce((acc, row) => acc + row.height, 0)
minTableBottomPos += tableHeight
}
const doc = new DocHandler(jsPDFDoc)
if (
settings.pageBreak === 'always' ||
(settings.startY != null && minTableBottomPos > doc.pageSize().height)
) {
nextPage(doc)
cursor.y = margin.top
}
const startPos = assign({}, cursor)
table.startPageNumber = doc.pageNumber()
if (settings.horizontalPageBreak === true) {
// managed flow for split columns
printTableWithHorizontalPageBreak(doc, table, startPos, cursor)
} else {
// normal flow
doc.applyStyles(doc.userStyles)
if (
settings.showHead === 'firstPage' ||
settings.showHead === 'everyPage'
) {
table.head.forEach((row) =>
printRow(doc, table, row, cursor, table.columns)
)
}
doc.applyStyles(doc.userStyles)
table.body.forEach((row, index) => {
const isLastRow = index === table.body.length - 1
printFullRow(doc, table, row, isLastRow, startPos, cursor, table.columns)
})
doc.applyStyles(doc.userStyles)
if (settings.showFoot === 'lastPage' || settings.showFoot === 'everyPage') {
table.foot.forEach((row) =>
printRow(doc, table, row, cursor, table.columns)
)
}
}
addTableBorder(doc, table, startPos, cursor)
table.callEndPageHooks(doc, cursor)
table.finalY = cursor.y
jsPDFDoc.lastAutoTable = table
jsPDFDoc.previousAutoTable = table // Deprecated
if (jsPDFDoc.autoTable) jsPDFDoc.autoTable.previous = table // Deprecated
doc.applyStyles(doc.userStyles)
}
function printTableWithHorizontalPageBreak(
doc: DocHandler,
table: Table,
startPos: { x: number; y: number },
cursor: { x: number; y: number }
) {
// calculate width of columns and render only those which can fit into page
const allColumnsCanFitResult: ColumnFitInPageResult[] = tablePrinter.calculateAllColumnsCanFitInPage(
doc,
table
)
allColumnsCanFitResult.map(
(colsAndIndexes: ColumnFitInPageResult, index: number) => {
doc.applyStyles(doc.userStyles)
// add page to print next columns in new page
if (index > 0) {
addPage(doc, table, startPos, cursor, colsAndIndexes.columns)
} else {
// print head for selected columns
printHead(doc, table, cursor, colsAndIndexes.columns)
}
// print body for selected columns
printBody(doc, table, startPos, cursor, colsAndIndexes.columns)
// print foot for selected columns
printFoot(doc, table, cursor, colsAndIndexes.columns)
}
)
}
function printHead(
doc: DocHandler,
table: Table,
cursor: Pos,
columns: Column[]
) {
const settings = table.settings
doc.applyStyles(doc.userStyles)
if (settings.showHead === 'firstPage' || settings.showHead === 'everyPage') {
table.head.forEach((row) => printRow(doc, table, row, cursor, columns))
}
}
function printBody(
doc: DocHandler,
table: Table,
startPos: Pos,
cursor: Pos,
columns: Column[]
) {
doc.applyStyles(doc.userStyles)
table.body.forEach((row, index) => {
const isLastRow = index === table.body.length - 1
printFullRow(doc, table, row, isLastRow, startPos, cursor, columns)
})
}
function printFoot(
doc: DocHandler,
table: Table,
cursor: Pos,
columns: Column[]
) {
const settings = table.settings
doc.applyStyles(doc.userStyles)
if (settings.showFoot === 'lastPage' || settings.showFoot === 'everyPage') {
table.foot.forEach((row) => printRow(doc, table, row, cursor, columns))
}
}
function getRemainingLineCount(
cell: Cell,
remainingPageSpace: number,
doc: DocHandler
) {
const fontHeight = (cell.styles.fontSize / doc.scaleFactor()) * FONT_ROW_RATIO
const vPadding = cell.padding('vertical')
const remainingLines = Math.floor(
(remainingPageSpace - vPadding) / fontHeight
)
return Math.max(0, remainingLines)
}
function modifyRowToFit(
row: Row,
remainingPageSpace: number,
table: Table,
doc: DocHandler
) {
const cells: { [key: string]: Cell } = {}
row.spansMultiplePages = true
row.height = 0
let rowHeight = 0
for (const column of table.columns) {
const cell: Cell = row.cells[column.index]
if (!cell) continue
if (!Array.isArray(cell.text)) {
cell.text = [cell.text]
}
let remainderCell = new Cell(cell.raw, cell.styles, cell.section)
remainderCell = assign(remainderCell, cell)
remainderCell.text = []
const remainingLineCount = getRemainingLineCount(
cell,
remainingPageSpace,
doc
)
if (cell.text.length > remainingLineCount) {
remainderCell.text = cell.text.splice(
remainingLineCount,
cell.text.length
)
}
const scaleFactor = doc.scaleFactor()
cell.contentHeight = cell.getContentHeight(scaleFactor)
if (cell.contentHeight >= remainingPageSpace) {
cell.contentHeight = remainingPageSpace
remainderCell.styles.minCellHeight -= remainingPageSpace
}
if (cell.contentHeight > row.height) {
row.height = cell.contentHeight
}
remainderCell.contentHeight = remainderCell.getContentHeight(scaleFactor)
if (remainderCell.contentHeight > rowHeight) {
rowHeight = remainderCell.contentHeight
}
cells[column.index] = remainderCell
}
const remainderRow = new Row(row.raw, -1, row.section, cells, true)
remainderRow.height = rowHeight
for (const column of table.columns) {
const remainderCell = remainderRow.cells[column.index]
if (remainderCell) {
remainderCell.height = remainderRow.height
}
const cell = row.cells[column.index]
if (cell) {
cell.height = row.height
}
}
return remainderRow
}
function shouldPrintOnCurrentPage(
doc: DocHandler,
row: Row,
remainingPageSpace: number,
table: Table
) {
const pageHeight = doc.pageSize().height
const margin = table.settings.margin
const marginHeight = margin.top + margin.bottom
let maxRowHeight = pageHeight - marginHeight
if (row.section === 'body') {
// Should also take into account that head and foot is not
// on every page with some settings
maxRowHeight -=
table.getHeadHeight(table.columns) + table.getFootHeight(table.columns)
}
const minRowHeight = row.getMinimumRowHeight(table.columns, doc)
const minRowFits = minRowHeight < remainingPageSpace
if (minRowHeight > maxRowHeight) {
console.error(
`Will not be able to print row ${row.index} correctly since it's minimum height is larger than page height`
)
return true
}
if (!minRowFits) {
return false
}
const rowHasRowSpanCell = row.hasRowSpan(table.columns)
const rowHigherThanPage = row.getMaxCellHeight(table.columns) > maxRowHeight
if (rowHigherThanPage) {
if (rowHasRowSpanCell) {
console.error(
`The content of row ${row.index} will not be drawn correctly since drawing rows with a height larger than the page height and has cells with rowspans is not supported.`
)
}
return true
}
if (rowHasRowSpanCell) {
// Currently a new page is required whenever a rowspan row don't fit a page.
return false
}
if (table.settings.rowPageBreak === 'avoid') {
return false
}
// In all other cases print the row on current page
return true
}
function printFullRow(
doc: DocHandler,
table: Table,
row: Row,
isLastRow: boolean,
startPos: Pos,
cursor: Pos,
columns: Column[]
) {
const remainingSpace = getRemainingPageSpace(doc, table, isLastRow, cursor)
if (row.canEntireRowFit(remainingSpace, columns)) {
printRow(doc, table, row, cursor, columns)
} else {
if (shouldPrintOnCurrentPage(doc, row, remainingSpace, table)) {
const remainderRow = modifyRowToFit(row, remainingSpace, table, doc)
printRow(doc, table, row, cursor, columns)
addPage(doc, table, startPos, cursor, columns)
printFullRow(
doc,
table,
remainderRow,
isLastRow,
startPos,
cursor,
columns
)
} else {
addPage(doc, table, startPos, cursor, columns)
printFullRow(doc, table, row, isLastRow, startPos, cursor, columns)
}
}
}
function printRow(
doc: DocHandler,
table: Table,
row: Row,
cursor: Pos,
columns: Column[]
) {
cursor.x = table.settings.margin.left
for (const column of columns) {
const cell = row.cells[column.index]
if (!cell) {
cursor.x += column.width
continue
}
doc.applyStyles(cell.styles)
cell.x = cursor.x
cell.y = cursor.y
const result = table.callCellHooks(
doc,
table.hooks.willDrawCell,
cell,
row,
column,
cursor
)
if (result === false) {
cursor.x += column.width
continue
}
drawCellBorders(doc, cell, cursor)
const textPos = cell.getTextPos()
autoTableText(
cell.text,
textPos.x,
textPos.y,
{
halign: cell.styles.halign,
valign: cell.styles.valign,
maxWidth: Math.ceil(
cell.width - cell.padding('left') - cell.padding('right')
),
},
doc.getDocument()
)
table.callCellHooks(doc, table.hooks.didDrawCell, cell, row, column, cursor)
cursor.x += column.width
}
cursor.y += row.height
}
function drawCellBorders(doc: DocHandler, cell: Cell, cursor: Pos) {
const cellStyles = cell.styles
doc.getDocument().setFillColor(doc.getDocument().getFillColor())
if (typeof cellStyles.lineWidth === 'number') {
// prints normal cell border
const fillStyle = getFillStyle(cellStyles.lineWidth, cellStyles.fillColor)
if (fillStyle) {
doc.rect(cell.x, cursor.y, cell.width, cell.height, fillStyle)
}
} else if (typeof cellStyles.lineWidth === 'object') {
doc.rect(cell.x, cursor.y, cell.width, cell.height, 'F')
const sides = Object.keys(cellStyles.lineWidth)
const lineWidth: any = cellStyles.lineWidth
sides.map((side: string) => {
const fillStyle = getFillStyle(lineWidth[side], cellStyles.fillColor)
drawBorderForSide(
doc,
cell,
cursor,
side,
fillStyle || 'S',
lineWidth[side]
)
})
}
}
function drawBorderForSide(
doc: DocHandler,
cell: Cell,
cursor: Pos,
side: string,
fillStyle: string,
lineWidth: number
) {
let x1, y1, x2, y2
switch (side) {
case 'top':
x1 = cursor.x
y1 = cursor.y
x2 = cursor.x + cell.width
y2 = cursor.y
break
case 'left':
x1 = cursor.x
y1 = cursor.y
x2 = cursor.x
y2 = cursor.y + cell.height
break
case 'right':
x1 = cursor.x + cell.width
y1 = cursor.y
x2 = cursor.x + cell.width
y2 = cursor.y + cell.height
break
default:
// default it will print bottom
x1 = cursor.x
y1 = cursor.y + cell.height - lineWidth
x2 = cursor.x + cell.width
y2 = cursor.y + cell.height - lineWidth
break
}
doc.getDocument().setLineWidth(lineWidth)
doc.getDocument().line(x1, y1, x2, y2, fillStyle)
}
function getRemainingPageSpace(
doc: DocHandler,
table: Table,
isLastRow: boolean,
cursor: Pos
) {
let bottomContentHeight = table.settings.margin.bottom
const showFoot = table.settings.showFoot
if (showFoot === 'everyPage' || (showFoot === 'lastPage' && isLastRow)) {
bottomContentHeight += table.getFootHeight(table.columns)
}
return doc.pageSize().height - cursor.y - bottomContentHeight
}
export function addPage(
doc: DocHandler,
table: Table,
startPos: Pos,
cursor: Pos,
columns: Column[] = []
) {
doc.applyStyles(doc.userStyles)
if (table.settings.showFoot === 'everyPage') {
table.foot.forEach((row: Row) => printRow(doc, table, row, cursor, columns))
}
// Add user content just before adding new page ensure it will
// be drawn above other things on the page
table.callEndPageHooks(doc, cursor)
const margin = table.settings.margin
addTableBorder(doc, table, startPos, cursor)
nextPage(doc)
table.pageNumber++
table.pageCount++
cursor.x = margin.left
cursor.y = margin.top
startPos.y = margin.top
if (table.settings.showHead === 'everyPage') {
table.head.forEach((row: Row) => printRow(doc, table, row, cursor, columns))
}
}
function nextPage(doc: DocHandler) {
const current = doc.pageNumber()
doc.setPage(current + 1)
const newCurrent = doc.pageNumber()
if (newCurrent === current) {
doc.addPage()
}
} | the_stack |
import {
CdmFolder,
ModelJson
} from '.';
import {
AttributeResolutionDirectiveSet,
CdmConstants,
CdmCorpusContext,
CdmCorpusDefinition,
CdmDocumentDefinition,
CdmFolderDefinition,
CdmManifestDefinition,
cdmLogCode,
CdmObject,
cdmObjectType,
copyOptions,
Logger,
resolveOptions,
StorageAdapterBase,
StringUtils
} from '../internal';
import { DocumentPersistence } from './CdmFolder/DocumentPersistence';
import { IPersistence } from './Common/IPersistence';
const PersistenceTypes = {
CdmFolder,
ModelJson
};
export class PersistenceLayer {
private TAG: string = PersistenceLayer.name;
public static cdmFolder: string = 'CdmFolder';
public static modelJson: string = 'ModelJson';
/**
* @internal
*/
public corpus: CdmCorpusDefinition;
/**
* @internal
*/
public ctx: CdmCorpusContext;
// The dictionary of file extension <-> persistence class that handles the file format.
private readonly registeredPersistenceFormats: Map<string, any>;
// The dictionary of persistence class <-> whether the persistence class has async methods.
private readonly isRegisteredPersistenceAsync: Map<any, boolean>;
/**
* Constructs a PersistenceLayer and registers persistence classes to load and save known file formats.
* @param corpus The corpus that owns this persistence layer.
*/
constructor(corpus: CdmCorpusDefinition) {
this.corpus = corpus;
this.ctx = this.corpus.ctx;
this.registeredPersistenceFormats = new Map<string, any>();
this.isRegisteredPersistenceAsync = new Map<any, boolean>();
}
/**
* @param args arguments passed to the persistence class.
* @param objectType any of cdmObjectType.
* @param persistenceType a type supported by the persistence layer. Can by any of PersistenceTypes.
*/
public static fromData<T extends CdmObject>(...args: any[]): T {
const persistenceType: string = args.pop() as string;
const objectType: cdmObjectType = args.pop() as cdmObjectType;
const persistenceClass: IPersistence = PersistenceLayer.fetchPersistenceClass(objectType, persistenceType);
return persistenceClass.fromData.apply(this, arguments) as T;
}
/**
* @param instance the instance that is going to be serialized.
* @param resOpt information about how to resolve the instance.
* @param persistenceType a type supported by the persistence layer. Can by any of PersistenceTypes.
* @param options set of options to specify how the output format.
*/
public static toData<T extends CdmObject, U>(instance: T, resOpt: resolveOptions, options: copyOptions, persistenceType: string): U {
const objectType: cdmObjectType = instance.objectType;
const persistenceClass: IPersistence = PersistenceLayer.fetchPersistenceClass(objectType, persistenceType);
return persistenceClass.toData(instance, resOpt, options);
}
public static fetchPersistenceClass(objectType: cdmObjectType, persistenceType: string): IPersistence {
const persistenceLayer: { [id: string]: IPersistence } = PersistenceTypes[persistenceType] as { [id: string]: IPersistence };
if (persistenceLayer) {
let objectName: string = cdmObjectType[objectType];
// tslint:disable:newline-per-chained-call
objectName = objectName.charAt(0).toUpperCase() + objectName.slice(1);
const defString: string = 'Def';
if (objectName.endsWith(defString)) {
objectName = objectName.slice(0, (defString.length) * -1);
} else if (objectName.endsWith('Ref')) {
objectName += 'erence';
}
const persistenceClassName: string = `${objectName}Persistence`;
const persistenceClass: IPersistence = persistenceLayer[persistenceClassName];
if (!persistenceClass) {
throw new Error(`Persistence class ${persistenceClassName} not implemented in type ${persistenceType}.`);
}
return persistenceClass;
} else {
throw new Error(`Persistence type ${persistenceType} not implemented.`);
}
}
/**
* @internal
* Loads a document from the folder path.
* @param folder The folder that contains the document we want to load.
* @param docName The document name.
* @param docContainer The loaded document, if it was previously loaded.
* @param resOpt Optional parameter. The resolve options.
*/
public async LoadDocumentFromPathAsync(folder: CdmFolderDefinition, docName: string, docContainer: CdmDocumentDefinition, resOpt: resolveOptions = null):
Promise<CdmDocumentDefinition> {
let docContent: CdmDocumentDefinition;
let jsonData: string;
let fsModifiedTime: Date;
const docPath: string = folder.folderPath + docName;
const adapter: StorageAdapterBase = this.corpus.storage.fetchAdapter(folder.namespace);
try {
if (adapter.canRead()) {
// log message used by navigator, do not change or remove
Logger.debug(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, `request file: ${docPath}`);
jsonData = await adapter.readAsync(docPath);
if (StringUtils.isBlankByCdmStandard(jsonData)) {
let errorMsg: string = 'Json data is null or empty.';
Logger.error(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, cdmLogCode.ErrPersistFileReadFailure, docPath, folder.namespace, errorMsg);
return undefined;
}
// log message used by navigator, do not change or remove
Logger.debug(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, `received file: ${docPath}`);
} else {
throw new Error('Storage Adapter is not enabled to read.');
}
} catch (e) {
// log message used by navigator, do not change or remove
Logger.debug(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, `fail file: ${docPath}`);
// When shallow validation is enabled, log messages about being unable to find referenced documents as warnings instead of errors.
if (resOpt && resOpt.shallowValidation) {
Logger.warning(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, cdmLogCode.WarnPersistFileReadFailure, docPath, folder.namespace, e);
} else {
Logger.error(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, cdmLogCode.ErrPersistFileReadFailure, docPath, folder.namespace, e);
}
return undefined;
}
try {
fsModifiedTime = await adapter.computeLastModifiedTimeAsync(docPath);
} catch (e) {
Logger.warning(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, cdmLogCode.WarnPersistFileModTimeFailure, e);
}
if (StringUtils.isBlankByCdmStandard(docName)) {
Logger.error(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, cdmLogCode.ErrPersistNullDocName);
return undefined;
}
// If loading an model.json file, check that it is named correctly.
if (docName.toLowerCase().endsWith(CdmConstants.modelJsonExtension) &&
docName.toLowerCase() !== CdmConstants.modelJsonExtension) {
Logger.error(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, cdmLogCode.ErrPersistDocNameLoadFailure, docName, CdmConstants.modelJsonExtension);
return undefined;
}
const docNameInLowCase: string = docName.toLowerCase();
try {
// Check file extensions, which performs a case-insensitive ordinal string comparison
if (docNameInLowCase.endsWith(CdmConstants.folioExtension) ||
docNameInLowCase.endsWith(CdmConstants.manifestExtension)) {
docContent = CdmFolder.ManifestPersistence.fromObject(
this.ctx,
docName,
folder.namespace,
folder.folderPath,
JSON.parse(jsonData)
) as unknown as CdmDocumentDefinition;
} else if (docNameInLowCase.endsWith(CdmConstants.modelJsonExtension)) {
docContent = await ModelJson.ManifestPersistence.fromObject(
this.ctx,
JSON.parse(jsonData),
folder
) as unknown as CdmDocumentDefinition;
} else if (docNameInLowCase.endsWith(CdmConstants.cdmExtension)) {
docContent = DocumentPersistence.fromObject(this.ctx, docName, folder.namespace, folder.folderPath, JSON.parse(jsonData));
} else {
// Could not find a registered persistence class to handle this document type.
Logger.error(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, docPath, cdmLogCode.ErrPersistClassMissing, docName);
return undefined;
}
} catch (e) {
// Could not find a registered persistence class to handle this document type.
Logger.error(this.ctx, this.TAG, this.LoadDocumentFromPathAsync.name, null, cdmLogCode.ErrPersistDocConversionFailure, docName, e.message);
return undefined;
}
//Add document to the folder, this sets all the folder/path things,
// caches name to content association and may trigger indexing on content
if (docContent) {
if (docContainer) {
// there are situations where a previously loaded document must be re-loaded.
// the end of that chain of work is here where the old version of the document has been removed from
// the corpus and we have created a new document and loaded it from storage and after this call we will probably
// add it to the corpus and index it, etc.
// it would be really rude to just kill that old object and replace it with this replicant, especially because
// the caller has no idea this happened. so... sigh ... instead of returning the new object return the one that
// was just killed off but make it contain everything the new document loaded.
docContent = docContent.copy(new resolveOptions(docContainer, this.ctx.corpus.defaultResolutionDirectives), docContainer) as CdmDocumentDefinition;
}
if (folder.documents.allItems.find((x: CdmDocumentDefinition) => x.ID === docContent.ID) == null) {
folder.documents.push(docContent, docName);
}
docContent._fileSystemModifiedTime = fsModifiedTime;
docContent.isDirty = false;
}
return docContent;
}
/**
* @internal
* a manifest or document can be saved with a new or exisitng name. This function on the corpus does all the actual work
* because the corpus knows about persistence types and about the storage adapters
* if saved with the same name, then consider this document 'clean' from changes. if saved with a back compat model or
* to a different name, then the source object is still 'dirty'
* an option will cause us to also save any linked documents.
*/
public async saveDocumentAsAsync(
doc: CdmDocumentDefinition,
options: copyOptions,
newName: string,
saveReferenced: boolean): Promise<boolean> {
// find out if the storage adapter is able to write.
let ns: string = doc.namespace;
if (StringUtils.isBlankByCdmStandard(ns)) {
ns = this.corpus.storage.defaultNamespace;
}
const adapter: StorageAdapterBase = this.corpus.storage.fetchAdapter(ns);
if (adapter === undefined) {
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistAdapterNotFoundForNamespace, ns);
return false;
} else if (adapter.canWrite() === false) {
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistAdapterWriteFailure, ns);
return false;
} else {
if (StringUtils.isBlankByCdmStandard(newName)) {
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistNullDocName);
return false;
}
// What kind of document is requested?
// Check file extensions using a case-insensitive ordinal string comparison.
const newNameInLowCase: string = newName.toLowerCase();
const persistenceType: string =
newNameInLowCase.endsWith(CdmConstants.modelJsonExtension) ? PersistenceLayer.modelJson : PersistenceLayer.cdmFolder;
if (persistenceType === PersistenceLayer.modelJson && newNameInLowCase !== CdmConstants.modelJsonExtension) {
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistFailure, newName, CdmConstants.modelJsonExtension);
return false;
}
// save the object into a json blob
const resOpt: resolveOptions = new resolveOptions(doc, new AttributeResolutionDirectiveSet());
let persistedDoc: object;
if (newNameInLowCase.endsWith(CdmConstants.modelJsonExtension) ||
newNameInLowCase.endsWith(CdmConstants.manifestExtension)
|| newNameInLowCase.endsWith(CdmConstants.folioExtension)) {
if (persistenceType === 'CdmFolder') {
persistedDoc = CdmFolder.ManifestPersistence.toData(doc as CdmManifestDefinition, resOpt, options);
} else {
if (newNameInLowCase !== CdmConstants.modelJsonExtension) {
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistFailure, newName);
return false;
}
persistedDoc = await ModelJson.ManifestPersistence.toData(doc as CdmManifestDefinition, resOpt, options);
}
} else if (newNameInLowCase.endsWith(CdmConstants.cdmExtension)) {
persistedDoc = CdmFolder.DocumentPersistence.toData(doc as CdmManifestDefinition, resOpt, options);
} else {
// Could not find a registered persistence class to handle this document type.
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistClassMissing, newName);
return false;
}
if (!persistedDoc) {
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistFilePersistFailed, newName);
return false;
}
// turn the name into a path
let newPath: string = `${doc.folderPath}${newName}`;
newPath = this.corpus.storage.createAbsoluteCorpusPath(newPath, doc);
if (newPath.startsWith(`${ns}:`)) {
newPath = newPath.slice(ns.length + 1);
}
// ask the adapter to make it happen
try {
const content: string = JSON.stringify(persistedDoc, undefined, 4);
await adapter.writeAsync(newPath, content);
doc._fileSystemModifiedTime = await adapter.computeLastModifiedTimeAsync(newPath);
// write the adapter's config.
if (options.saveConfigFile !== false && options.isTopLevelDocument) {
await this.corpus.storage.saveAdaptersConfigAsync('/config.json', adapter);
// the next documentwon't be top level, so reset the flag
options.isTopLevelDocument = false;
}
} catch (e) {
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistFilePersistError, newName, e);
}
// if we also want to save referenced docs, then it depends on what kind of thing just got saved
// if a model.json there are none. If a manifest or definition doc then ask the docs to do the right things
// definition will save imports, manifests will save imports, schemas, sub manifests
if (saveReferenced && persistenceType === PersistenceLayer.cdmFolder) {
if (!await doc.saveLinkedDocuments(options)) {
Logger.error(this.ctx, this.TAG, this.saveDocumentAsAsync.name, doc.atCorpusPath, cdmLogCode.ErrPersistSaveLinkedDocs, newName);
}
}
return true;
}
}
private fetchRegisteredPersistenceFormat(docName: string): any {
for (const registeredPersistenceFormat of this.registeredPersistenceFormats.entries()) {
// Find the persistence class to use for this document.
if (docName.toLowerCase().endsWith(registeredPersistenceFormat[0].toLowerCase())) {
return registeredPersistenceFormat[1];
}
}
return undefined;
}
} | the_stack |
import { CodegenFramework, CodegenLanguage, Configuration } from '@neo-one/cli-common';
import { normalizePath } from '@neo-one/utils';
import { cosmiconfig } from 'cosmiconfig';
import * as fs from 'fs-extra';
import _ from 'lodash';
import * as nodePath from 'path';
// tslint:disable-next-line: match-default-export-name
import validate from 'schema-utils';
import { register } from 'ts-node';
import { defaultNetworks } from './networks';
const configurationDefaults = {
artifacts: {
path: nodePath.join('neo-one', 'artifacts'),
},
migration: {
path: nodePath.join('neo-one', 'migration.js'),
},
contracts: {
outDir: nodePath.join('neo-one', 'compiled'),
path: nodePath.join('neo-one', 'contracts'),
},
codegen: {
path: nodePath.join('src', 'neo-one'),
language: 'javascript',
framework: 'none',
browserify: false,
codesandbox: false,
},
network: {
path: nodePath.join('.neo-one', 'network'),
port: 9040,
},
networks: defaultNetworks,
neotracker: {
path: nodePath.join('.neo-one', 'neotracker'),
port: 9041,
skip: true,
},
};
const applyDefaults = (config: any = {}): Configuration => ({
...config,
artifacts: {
...configurationDefaults.artifacts,
...(config.artifacts === undefined ? {} : config.artifacts),
},
migration: {
...configurationDefaults.migration,
...(config.migration === undefined ? {} : config.migration),
},
contracts: {
...configurationDefaults.contracts,
...(config.contracts === undefined ? {} : config.contracts),
},
codegen: {
...configurationDefaults.codegen,
...(config.codegen === undefined ? {} : config.codegen),
},
network: {
...configurationDefaults.network,
...(config.network === undefined ? {} : config.network),
},
networks: config.networks === undefined ? configurationDefaults.networks : config.networks,
neotracker: {
...configurationDefaults.neotracker,
...(config.neotracker === undefined ? {} : config.neotracker),
},
});
const configurationSchema = {
type: 'object',
allRequired: true,
additionalProperties: false,
properties: {
artifacts: {
type: 'object',
allRequired: true,
additionalProperties: false,
properties: {
path: { type: 'string' },
},
},
migration: {
type: 'object',
allRequired: true,
additionalProperties: false,
properties: {
path: { type: 'string' },
},
},
contracts: {
type: 'object',
allRequired: false,
additionalProperties: false,
properties: {
outDir: { type: 'string' },
path: { type: 'string' },
json: { type: 'boolean' },
nef: { type: 'boolean' },
debug: { type: 'boolean' },
opcodes: { type: 'boolean' },
},
},
codegen: {
type: 'object',
allRequired: true,
additionalProperties: false,
properties: {
path: { type: 'string' },
language: { type: 'string', enum: ['javascript', 'typescript'] },
framework: { type: 'string', enum: ['none', 'react', 'vue', 'angular'] },
browserify: { type: 'boolean' },
codesandbox: { type: 'boolean' },
},
},
network: {
type: 'object',
allRequired: true,
additionalProperties: false,
properties: {
path: { type: 'string' },
port: { type: 'number', multipleOf: 1.0, minimum: 0 },
},
},
networks: {
type: 'object',
additionalProperties: {
type: 'object',
allRequired: true,
additionalProperties: false,
properties: {
userAccountProvider: {
instanceof: 'Function',
},
},
},
},
neotracker: {
type: 'object',
allRequired: true,
additionalProperties: false,
properties: {
path: { type: 'string' },
port: { type: 'number', multipleOf: 1.0, minimum: 0 },
skip: { type: 'boolean' },
},
},
},
};
const relativizePaths = (config: Configuration) => ({
...config,
artifacts: {
...config.artifacts,
path: normalizePath(nodePath.relative(process.cwd(), config.artifacts.path)),
},
migration: {
...config.migration,
path: normalizePath(nodePath.relative(process.cwd(), config.migration.path)),
},
contracts: {
...config.contracts,
outDir: normalizePath(nodePath.relative(process.cwd(), config.contracts.outDir)),
path: normalizePath(nodePath.relative(process.cwd(), config.contracts.path)),
},
codegen: {
...config.codegen,
path: normalizePath(nodePath.relative(process.cwd(), config.codegen.path)),
},
network: {
...config.network,
path: normalizePath(nodePath.relative(process.cwd(), config.network.path)),
},
neotracker: {
...config.neotracker,
path: normalizePath(nodePath.relative(process.cwd(), config.neotracker.path)),
},
});
const createDefaultConfiguration = (configIn: Configuration, importDefaultNetworks: string, exportConfig: string) => {
const config = relativizePaths(configIn);
return `${importDefaultNetworks}
${exportConfig} {
contracts: {
// The NEO•ONE compile command will output the compile results in this directory.
outDir: '${config.contracts.outDir}',
// NEO•ONE will look for smart contracts in this directory.
path: '${config.contracts.path}',
// Set this to true if you want the compile command to output JSON.
json: ${true},
// Set this to true if you want the compile command to output a Nef (Neo Executable Format 3) file.
nef: ${false},
// Set this to true if you want the compile command to output additional debug information.
debug: ${false},
// Set this to true if you want the compile command to output the contract's script in a human-readable format for debugging (requires debug: true).
opcodes: ${false},
},
artifacts: {
// NEO•ONE will store build and deployment artifacts that should be checked in to vcs in this directory.
path: '${config.artifacts.path}',
},
migration: {
// NEO•ONE will load the deployment migration from this path.
path: '${config.migration.path}',
},
codegen: {
// NEO•ONE will write source artifacts to this directory. This directory should be committed.
path: '${config.codegen.path}',
// NEO•ONE will generate code in the language specified here. Can be one of 'javascript' or 'typescript'.
language: '${config.codegen.language}',
// NEO•ONE will generate client helpers for the framework specified here. Can be one of 'react', 'angular', 'vue' or 'none'.
framework: '${config.codegen.framework}',
// Set this to true if you're using an environment like Expo that doesn't handle browserifying dependencies automatically.
browserify: ${config.codegen.browserify},
// Set this to true if you're running in codesandbox to workaround certain limitations of codesandbox.
codesandbox: ${config.codegen.codesandbox},
},
network: {
// NEO•ONE will store network data here. This path should be ignored by your vcs, e.g. by specifiying it in a .gitignore file.
path: '${config.network.path}',
// NEO•ONE will start the network on this port.
port: ${config.network.port},
},
// NEO•ONE will configure various parts of the CLI that require network accounts using the value provided here, for example, when deploying contracts.
// Refer to the documentation at https://neo-one.io/docs/config-options for more information.
networks: defaultNetworks,
neotracker: {
// NEO•ONE will start an instance of NEO Tracker using this path for local data. This directory should not be committed.
path: '${config.neotracker.path}',
// NEO•ONE will start an instance of NEO Tracker using this port.
port: 9041,
// Set to false if you'd like NEO•ONE to start an instance of NEO Tracker when running 'neo-one build'. You will need @neotracker/core installed as a dependency for this to work.
skip: true,
}
};
`;
};
export const createDefaultConfigurationJavaScript = (config: Configuration) =>
createDefaultConfiguration(config, "const { defaultNetworks } = require('@neo-one/cli');", 'module.exports =');
export const createDefaultConfigurationTypeScript = (config: Configuration) =>
createDefaultConfiguration(config, "import { defaultNetworks } from '@neo-one/cli';", 'export default');
// tslint:disable-next-line: no-any
const getPkgDependencies = (pkg: any): Set<string> => {
const dependencies = pkg.dependencies === undefined ? [] : Object.keys(pkg.dependencies);
const devDependencies = pkg.devDependencies === undefined ? [] : Object.keys(pkg.devDependencies);
return new Set(dependencies.concat(devDependencies));
};
const getProjectFramework = async (rootDir: string): Promise<CodegenFramework> => {
// tslint:disable-next-line no-any
let pkg: any;
try {
const contents = await fs.readFile(nodePath.resolve(rootDir, 'package.json'), 'utf8');
pkg = JSON.parse(contents);
} catch (err) {
if (err.code === 'ENOENT') {
return 'none';
}
throw err;
}
const dependencies = getPkgDependencies(pkg);
if (dependencies.has('react') || dependencies.has('react-dom')) {
return 'react';
}
if (dependencies.has('@angular/core') || dependencies.has('@angular/cli')) {
return 'angular';
}
if (dependencies.has('vue') || dependencies.has('@vue/cli-service')) {
return 'vue';
}
return 'none';
};
const getProjectLanguage = async (rootDir: string): Promise<CodegenLanguage> => {
const exists = await fs.pathExists(nodePath.resolve(rootDir, 'tsconfig.json'));
return exists ? 'typescript' : 'javascript';
};
const validateConfig = async (rootDir: string, configIn: any): Promise<Configuration> => {
const config = applyDefaults(configIn);
validate(configurationSchema, configIn, { name: 'NEO•ONE' } as any);
let newFramework: CodegenFramework | undefined;
let newLanguage: CodegenLanguage | undefined;
if (Object.keys(configIn).length === 0) {
[newFramework, newLanguage] = await Promise.all([getProjectFramework(rootDir), getProjectLanguage(rootDir)]);
}
return {
artifacts: {
...config.artifacts,
path: nodePath.resolve(rootDir, config.artifacts.path),
},
migration: {
...config.migration,
path: nodePath.resolve(
rootDir,
newLanguage === undefined || newLanguage === 'javascript'
? config.migration.path
: config.migration.path.slice(0, -3).concat('.ts'),
),
},
contracts: {
...config.contracts,
outDir: nodePath.resolve(rootDir, config.contracts.outDir),
path: nodePath.resolve(rootDir, config.contracts.path),
},
codegen: {
...config.codegen,
path: nodePath.resolve(rootDir, config.codegen.path),
language: newLanguage === undefined ? config.codegen.language : newLanguage,
framework: newFramework === undefined ? config.codegen.framework : newFramework,
},
network: {
...config.network,
path: nodePath.resolve(rootDir, config.network.path),
},
networks: config.networks,
neotracker: {
...config.neotracker,
path: nodePath.resolve(rootDir, config.neotracker.path),
},
};
};
// tslint:disable-next-line no-let
let cachedConfig: Configuration | undefined;
export const loadConfiguration = async (optionalConfigPath?: string): Promise<Configuration> => {
if (cachedConfig === undefined && optionalConfigPath !== undefined) {
register({
compilerOptions: {
module: 'commonjs',
allowJs: true,
},
});
const obj = await import(optionalConfigPath);
const output = obj.default === undefined ? obj : obj.default;
cachedConfig = await validateConfig(nodePath.dirname(optionalConfigPath), output === null ? {} : output);
}
if (cachedConfig === undefined) {
const explorer = cosmiconfig('neo-one', {
loaders: {
'.ts': async (filePath: string): Promise<object> => {
register({
compilerOptions: {
module: 'commonjs',
},
});
const obj = await import(filePath);
return obj.default === undefined ? obj : obj.default;
},
},
searchPlaces: ['.neo-one.config.js', '.neo-one.config.ts'],
});
const result = await explorer.search();
cachedConfig = await validateConfig(
result === null ? process.cwd() : nodePath.dirname(result.filepath),
result === null ? {} : result.config,
);
}
return cachedConfig;
};
export const configToSerializable = (config: Configuration) => ({
...config,
networks: _.fromPairs(
Object.entries(config.networks).map(([key, value]) => [
key,
{
...value,
userAccountProvider: 'omitted',
},
]),
),
}); | the_stack |
import 'mocha'
import HttpStatus from '@xpring-eng/http-status'
import { assert } from 'chai'
import * as request from 'supertest'
import App from '../../../../src/app'
import {
PaymentInformation,
AddressDetailsType,
} from '../../../../src/types/protocol'
import { appSetup, appCleanup } from '../../../helpers/helpers'
let app: App
describe('E2E - publicAPIRouter - Verifiable PayID', function (): void {
// Boot up Express application and initialize DB connection pool
before(async function () {
app = await appSetup()
})
it('Returns the correct MAINNET address for a known PayID', function (done): void {
// GIVEN a PayID known to have an associated xrpl-mainnet address
const payId = '/johnwick'
const acceptHeader = 'application/xrpl-mainnet+json'
const expectedResponse: PaymentInformation = {
addresses: [],
payId: 'johnwick$127.0.0.1',
version: '1.1',
verifiedAddresses: [
{
payload: JSON.stringify({
payId: 'johnwick$127.0.0.1',
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'MAINNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rDk7FQvkQxQQNGTtfM2Fr66s7Nm3k87vdS',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'aGV0IG1lIHNlZSB0aGVtIGNvcmdpcyBOT1cgb3IgcGF5IHRoZSBwcmljZQ==',
signature:
'TG9vayBhdCBtZSEgd29vIEknbSB0ZXN0aW5nIHRoaW5ncyBhbmQgdGhpcyBpcyBhIHNpZ25hdHVyZQ==',
},
],
},
],
}
// WHEN we make a GET request to the public endpoint to retrieve payment info with an Accept header specifying xrpl-mainnet
request(app.publicApiExpress)
.get(payId)
.set('PayID-Version', '1.1')
.set('Accept', acceptHeader)
// THEN we get back our Accept header as the Content-Type
.expect((res) => {
assert.strictEqual(res.get('Content-Type').split('; ')[0], acceptHeader)
})
// AND we get back the XRP address associated with that PayID for xrpl-mainnet.
.expect(HttpStatus.OK, expectedResponse, done)
})
it('Returns the correct TESTNET address for a known PayID', function (done): void {
// GIVEN a PayID known to have an associated xrpl-testnet address
const payId = '/johnwick'
const acceptHeader = 'application/xrpl-testnet+json'
const expectedResponse: PaymentInformation = {
addresses: [],
payId: 'johnwick$127.0.0.1',
version: '1.1',
verifiedAddresses: [
{
payload: JSON.stringify({
payId: 'johnwick$127.0.0.1',
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'TESTNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rDk7FQvkQxQQNGTtfM2Fr66s7Nm3k87vdS',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'aGV0IG1lIHNlZSB0aGVtIGNvcmdpcyBOT1cgb3IgcGF5IHRoZSBwcmljZQ==',
signature:
'TG9vayBhdCBtZSEgd29vIEknbSB0ZXN0aW5nIHRoaW5ncyBhbmQgdGhpcyBpcyBhIHNpZ25hdHVyZQ==',
},
],
},
],
}
// WHEN we make a GET request to the public endpoint to retrieve payment info with an Accept header specifying xrpl-testnet
request(app.publicApiExpress)
.get(payId)
.set('PayID-Version', '1.1')
.set('Accept', acceptHeader)
// THEN we get back our Accept header as the Content-Type
.expect((res) => {
assert.strictEqual(res.get('Content-Type').split('; ')[0], acceptHeader)
})
// AND we get back the XRP address associated with that PayID for xrpl-testnet.
.expect(HttpStatus.OK, expectedResponse, done)
})
it('Returns the correct address for a known PayID and a non-XRPL header', function (done): void {
// GIVEN a PayID known to have an associated btc-testnet address
const payId = '/johnwick'
const acceptHeader = 'application/btc-testnet+json'
const expectedResponse: PaymentInformation = {
addresses: [],
payId: 'johnwick$127.0.0.1',
version: '1.1',
verifiedAddresses: [
{
payload: JSON.stringify({
payId: 'johnwick$127.0.0.1',
payIdAddress: {
paymentNetwork: 'BTC',
environment: 'TESTNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: '2NGZrVvZG92qGYqzTLjCAewvPZ7JE8S8VxE',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'aGV0IG1lIHNlZSB0aGVtIGNvcmdpcyBOT1cgb3IgcGF5IHRoZSBwcmljZQ==',
signature:
'TG9vayBhdCBtZSEgd29vIEknbSB0ZXN0aW5nIHRoaW5ncyBhbmQgdGhpcyBpcyBhIHNpZ25hdHVyZQ==',
},
],
},
],
}
// WHEN we make a GET request to the public endpoint to retrieve payment info with an Accept header specifying btc-testnet
request(app.publicApiExpress)
.get(payId)
.set('PayID-Version', '1.1')
.set('Accept', acceptHeader)
// THEN we get back our Accept header as the Content-Type
.expect((res) => {
assert.strictEqual(res.get('Content-Type').split('; ')[0], acceptHeader)
})
// AND we get back the BTC address associated with that PayID for btc-testnet.
.expect(HttpStatus.OK, expectedResponse, done)
})
it('Returns the correct address for a known PayID and an ACH header (no environment)', function (done): void {
// GIVEN a PayID known to have an associated ACH address
const payId = '/johnwick'
const acceptHeader = 'application/ach+json'
const expectedResponse: PaymentInformation = {
addresses: [],
payId: 'johnwick$127.0.0.1',
version: '1.1',
verifiedAddresses: [
{
payload: JSON.stringify({
payId: 'johnwick$127.0.0.1',
payIdAddress: {
paymentNetwork: 'ACH',
addressDetailsType: AddressDetailsType.FiatAddress,
addressDetails: {
accountNumber: '000123456789',
routingNumber: '123456789',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'aGV0IG1lIHNlZSB0aGVtIGNvcmdpcyBOT1cgb3IgcGF5IHRoZSBwcmljZQ==',
signature:
'TG9vayBhdCBtZSEgd29vIEknbSB0ZXN0aW5nIHRoaW5ncyBhbmQgdGhpcyBpcyBhIHNpZ25hdHVyZQ==',
},
],
},
],
}
// WHEN we make a GET request to the public endpoint to retrieve payment info with an Accept header specifying ACH
request(app.publicApiExpress)
.get(payId)
.set('PayID-Version', '1.1')
.set('Accept', acceptHeader)
// THEN we get back our Accept header as the Content-Type
.expect((res) => {
assert.strictEqual(res.get('Content-Type').split('; ')[0], acceptHeader)
})
// AND we get back the ACH account information associated with that PayID for ACH.
.expect(HttpStatus.OK, expectedResponse, done)
})
it('Returns all unverified & verified addresses for a known PayID and an all addresses header', function (done): void {
// GIVEN a PayID known to have an associated btc-testnet address
const payId = '/johnwick'
const acceptHeader = 'application/payid+json'
const expectedResponse: PaymentInformation = {
payId: 'johnwick$127.0.0.1',
version: '1.1',
addresses: [
{
paymentNetwork: 'BTC',
environment: 'MAINNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: '2NGZrVvZG92qGYqzTLjCAewvPZ7JE8S8VxE',
},
},
],
verifiedAddresses: [
{
payload: JSON.stringify({
payId: 'johnwick$127.0.0.1',
payIdAddress: {
paymentNetwork: 'BTC',
environment: 'TESTNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: '2NGZrVvZG92qGYqzTLjCAewvPZ7JE8S8VxE',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'aGV0IG1lIHNlZSB0aGVtIGNvcmdpcyBOT1cgb3IgcGF5IHRoZSBwcmljZQ==',
signature:
'TG9vayBhdCBtZSEgd29vIEknbSB0ZXN0aW5nIHRoaW5ncyBhbmQgdGhpcyBpcyBhIHNpZ25hdHVyZQ==',
},
],
},
{
payload: JSON.stringify({
payId: 'johnwick$127.0.0.1',
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'TESTNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rDk7FQvkQxQQNGTtfM2Fr66s7Nm3k87vdS',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'aGV0IG1lIHNlZSB0aGVtIGNvcmdpcyBOT1cgb3IgcGF5IHRoZSBwcmljZQ==',
signature:
'TG9vayBhdCBtZSEgd29vIEknbSB0ZXN0aW5nIHRoaW5ncyBhbmQgdGhpcyBpcyBhIHNpZ25hdHVyZQ==',
},
],
},
{
payload: JSON.stringify({
payId: 'johnwick$127.0.0.1',
payIdAddress: {
paymentNetwork: 'XRPL',
environment: 'MAINNET',
addressDetailsType: AddressDetailsType.CryptoAddress,
addressDetails: {
address: 'rDk7FQvkQxQQNGTtfM2Fr66s7Nm3k87vdS',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'aGV0IG1lIHNlZSB0aGVtIGNvcmdpcyBOT1cgb3IgcGF5IHRoZSBwcmljZQ==',
signature:
'TG9vayBhdCBtZSEgd29vIEknbSB0ZXN0aW5nIHRoaW5ncyBhbmQgdGhpcyBpcyBhIHNpZ25hdHVyZQ==',
},
],
},
{
payload: JSON.stringify({
payId: 'johnwick$127.0.0.1',
payIdAddress: {
paymentNetwork: 'ACH',
addressDetailsType: AddressDetailsType.FiatAddress,
addressDetails: {
accountNumber: '000123456789',
routingNumber: '123456789',
},
},
}),
signatures: [
{
name: 'identityKey',
protected:
'aGV0IG1lIHNlZSB0aGVtIGNvcmdpcyBOT1cgb3IgcGF5IHRoZSBwcmljZQ==',
signature:
'TG9vayBhdCBtZSEgd29vIEknbSB0ZXN0aW5nIHRoaW5ncyBhbmQgdGhpcyBpcyBhIHNpZ25hdHVyZQ==',
},
],
},
],
}
// WHEN we make a GET request to the public endpoint to retrieve payment info with an Accept header specifying btc-testnet
request(app.publicApiExpress)
.get(payId)
.set('PayID-Version', '1.1')
.set('Accept', acceptHeader)
// THEN we get back our Accept header as the Content-Type
.expect((res) => {
assert.strictEqual(res.get('Content-Type').split('; ')[0], acceptHeader)
})
// AND we get back the BTC address associated with that PayID for btc-testnet.
.expect(HttpStatus.OK, expectedResponse, done)
})
it('Returns a 404 for a PayID without the relevant associated address', function (done): void {
// GIVEN a known PayID that exists but does not have an associated devnet XRP address
const payId = '/johnwick'
const acceptHeader = 'application/xrpl-devnet+json'
const expectedErrorResponse = {
statusCode: 404,
error: 'Not Found',
message: 'Payment information for johnwick$127.0.0.1 could not be found.',
}
// WHEN we make a GET request to the public endpoint to retrieve payment info with an Accept header specifying xrpl-devnet
request(app.publicApiExpress)
.get(payId)
.set('PayID-Version', '1.1')
.set('Accept', acceptHeader)
.expect('Content-Type', /application\/json/u)
// THEN we get back a 404 with the expected error response.
.expect(HttpStatus.NotFound, expectedErrorResponse, done)
})
// Shut down Express application and close DB connections
after(function () {
appCleanup(app)
})
}) | the_stack |
import {
attr,
DOM,
html,
HTMLView,
observable,
ref,
RepeatBehavior,
RepeatDirective,
ViewTemplate,
} from "@microsoft/fast-element";
import {
keyArrowDown,
keyArrowLeft,
keyArrowRight,
keyArrowUp,
keyBackspace,
keyDelete,
keyEnter,
keyEscape,
uniqueId,
} from "@microsoft/fast-web-utilities";
import {
AnchoredRegion,
AnchoredRegionConfig,
FlyoutPosBottom,
FlyoutPosBottomFill,
FlyoutPosTallest,
FlyoutPosTallestFill,
FlyoutPosTop,
FlyoutPosTopFill,
} from "../anchored-region/index.js";
import type { PickerMenu } from "./picker-menu.js";
import { PickerMenuOption } from "./picker-menu-option.js";
import { PickerListItem } from "./picker-list-item.js";
import { FormAssociatedPicker } from "./picker.form-associated.js";
import type { PickerList } from "./picker-list.js";
const pickerInputTemplate: ViewTemplate = html<Picker>`
<input
slot="input-region"
role="combobox"
type="text"
autocapitalize="off"
autocomplete="off"
haspopup="list"
aria-label="${x => x.label}"
aria-labelledby="${x => x.labelledBy}"
placeholder="${x => x.placeholder}"
${ref("inputElement")}
></input>
`;
/**
* Defines the vertical positioning options for an anchored region
*
* @beta
*/
export type menuConfigs =
| "bottom"
| "bottom-fill"
| "tallest"
| "tallest-fill"
| "top"
| "top-fill";
/**
* A Picker Custom HTML Element. This is an early "alpha" version of the component.
* Developers should expect the api to evolve, breaking changes are possible.
*
* @alpha
*/
export class Picker extends FormAssociatedPicker {
/**
* Currently selected items. Comma delineated string ie. "apples,oranges".
*
* @alpha
* @remarks
* HTML Attribute: selection
*/
@attr({ attribute: "selection" })
public selection: string = "";
private selectionChanged(): void {
if (this.$fastController.isConnected) {
this.handleSelectionChange();
if (this.proxy instanceof HTMLInputElement) {
this.proxy.value = this.selection;
this.validate();
}
}
}
/**
* Currently available options. Comma delineated string ie. "apples,oranges".
*
* @alpha
* @remarks
* HTML Attribute: options
*/
@attr({ attribute: "options" })
public options: string;
private optionsChanged(): void {
this.optionsList = this.options
.split(",")
.map(opt => opt.trim())
.filter(opt => opt !== "");
}
/**
* Whether the component should remove an option from the list when it is in the selection
*
* @alpha
* @remarks
* HTML Attribute: filter-selected
*/
@attr({ attribute: "filter-selected", mode: "boolean" })
public filterSelected: boolean = true;
/**
* Whether the component should remove options based on the current query
*
* @alpha
* @remarks
* HTML Attribute: filter-query
*/
@attr({ attribute: "filter-query", mode: "boolean" })
public filterQuery: boolean = true;
/**
* The maximum number of items that can be selected.
*
* @alpha
* @remarks
* HTML Attribute: max-selected
*/
@attr({ attribute: "max-selected" })
public maxSelected: number | undefined;
/**
* The text to present to assistive technolgies when no suggestions are available.
*
* @alpha
* @remarks
* HTML Attribute: no-suggestions-text
*/
@attr({ attribute: "no-suggestions-text" })
public noSuggestionsText: string = "No suggestions available";
/**
* The text to present to assistive technolgies when suggestions are available.
*
* @alpha
* @remarks
* HTML Attribute: suggestions-available-text
*/
@attr({ attribute: "suggestions-available-text" })
public suggestionsAvailableText: string = "Suggestions available";
/**
* The text to present to assistive technologies when suggestions are loading.
*
* @alpha
* @remarks
* HTML Attribute: loading-text
*/
@attr({ attribute: "loading-text" })
public loadingText: string = "Loading suggestions";
/**
* Applied to the aria-label attribute of the input element
*
* @alpha
* @remarks
* HTML Attribute: label
*/
@attr({ attribute: "label" })
public label: string;
/**
* Applied to the aria-labelledby attribute of the input element
*
* @alpha
* @remarks
* HTML Attribute: labelledby
*/
@attr({ attribute: "labelledby" })
public labelledBy: string;
/**
* Applied to the placeholder attribute of the input element
*
* @alpha
* @remarks
* HTML Attribute: placholder
*/
@attr({ attribute: "placeholder" })
public placeholder: string;
/**
* Controls menu placement
*
* @alpha
* @remarks
* HTML Attribute: menu-placement
*/
@attr({ attribute: "menu-placement" })
public menuPlacement: menuConfigs = "bottom-fill";
private menuPlacementChanged(): void {
if (this.$fastController.isConnected) {
this.updateMenuConfig();
}
}
/**
* Whether to display a loading state if the menu is opened.
*
* @alpha
*/
@observable
public showLoading: boolean = false;
private showLoadingChanged(): void {
if (this.$fastController.isConnected) {
DOM.queueUpdate(() => {
this.setFocusedOption(0);
});
}
}
/**
* Template used to generate selected items.
* This is used in a repeat directive.
*
* @alpha
*/
@observable
public listItemTemplate: ViewTemplate;
private listItemTemplateChanged(): void {
this.updateListItemTemplate();
}
/**
* Default template to use for selected items (usually specified in the component template).
* This is used in a repeat directive.
*
* @alpha
*/
@observable
public defaultListItemTemplate?: ViewTemplate;
private defaultListItemTemplateChanged(): void {
this.updateListItemTemplate();
}
/**
* The item template currently in use.
*
* @internal
*/
@observable
public activeListItemTemplate?: ViewTemplate;
/**
* Template to use for available options.
* This is used in a repeat directive.
*
* @alpha
*/
@observable
public menuOptionTemplate: ViewTemplate;
private menuOptionTemplateChanged(): void {
this.updateOptionTemplate();
}
/**
* Default template to use for available options (usually specified in the template).
* This is used in a repeat directive.
*
* @alpha
*/
@observable
public defaultMenuOptionTemplate?: ViewTemplate;
private defaultMenuOptionTemplateChanged(): void {
this.updateOptionTemplate();
}
/**
* The option template currently in use.
*
* @internal
*/
@observable
public activeMenuOptionTemplate?: ViewTemplate;
/**
* Template to use for the contents of a selected list item
*
* @alpha
*/
@observable
public listItemContentsTemplate: ViewTemplate;
/**
* Template to use for the contents of menu options
*
* @alpha
*/
@observable
public menuOptionContentsTemplate: ViewTemplate;
/**
* Current list of options in array form
*
* @alpha
*/
@observable
public optionsList: string[] = [];
private optionsListChanged(): void {
this.updateFilteredOptions();
}
/**
* The text value currently in the input field
*
* @alpha
*/
@observable
public query: string;
private queryChanged(): void {
if (this.$fastController.isConnected) {
if (this.inputElement.value !== this.query) {
this.inputElement.value = this.query;
}
this.updateFilteredOptions();
this.$emit("querychange", { bubbles: false });
}
}
/**
* Current list of filtered options in array form
*
* @internal
*/
@observable
public filteredOptionsList: string[] = [];
private filteredOptionsListChanged(): void {
if (this.$fastController.isConnected) {
this.showNoOptions =
this.filteredOptionsList.length === 0 &&
this.menuElement.querySelectorAll('[role="listitem"]').length === 0;
this.setFocusedOption(this.showNoOptions ? -1 : 0);
}
}
/**
* Indicates if the flyout menu is open or not
*
* @internal
*/
@observable
public flyoutOpen: boolean = false;
private flyoutOpenChanged(): void {
if (this.flyoutOpen) {
DOM.queueUpdate(this.setRegionProps);
this.$emit("menuopening", { bubbles: false });
} else {
this.$emit("menuclosing", { bubbles: false });
}
}
/**
* The id of the menu element
*
* @internal
*/
@observable
public menuId: string;
/**
* The tag for the selected list element (ie. "fast-picker-list" vs. "fluent-picker-list")
*
* @internal
*/
@observable
public selectedListTag: string;
/**
* The tag for the menu element (ie. "fast-picker-menu" vs. "fluent-picker-menu")
*
* @internal
*/
@observable
public menuTag: string;
/**
* Index of currently active menu option
*
* @internal
*/
@observable
public menuFocusIndex: number = -1;
/**
* Id of currently active menu option.
*
* @internal
*/
@observable
public menuFocusOptionId: string | undefined;
/**
* Internal flag to indicate no options available display should be shown.
*
* @internal
*/
@observable
public showNoOptions: boolean = false;
private showNoOptionsChanged(): void {
if (this.$fastController.isConnected) {
DOM.queueUpdate(() => {
this.setFocusedOption(0);
});
}
}
/**
* The anchored region config to apply.
*
* @internal
*/
@observable
public menuConfig: AnchoredRegionConfig;
/**
* Reference to the placeholder element for the repeat directive
*
* @alpha
*/
public itemsPlaceholderElement: Node;
/**
* reference to the input element
*
* @internal
*/
public inputElement: HTMLInputElement;
/**
* reference to the selected list element
*
* @internal
*/
public listElement: PickerList;
/**
* reference to the menu element
*
* @internal
*/
public menuElement: PickerMenu;
/**
* reference to the anchored region element
*
* @internal
*/
public region: AnchoredRegion;
/**
*
*
* @internal
*/
@observable
public selectedItems: string[] = [];
private itemsRepeatBehavior: RepeatBehavior | null;
private optionsRepeatBehavior: RepeatBehavior | null;
private optionsPlaceholder: Node;
private inputElementView: HTMLView | null = null;
/**
* @internal
*/
public connectedCallback(): void {
super.connectedCallback();
this.listElement = document.createElement(this.selectedListTag) as PickerList;
this.appendChild(this.listElement);
this.itemsPlaceholderElement = document.createComment("");
this.listElement.append(this.itemsPlaceholderElement);
this.inputElementView = pickerInputTemplate.render(this, this.listElement);
const match: string = this.menuTag.toUpperCase();
this.menuElement = Array.from(this.children).find((element: HTMLElement) => {
return element.tagName === match;
}) as PickerMenu;
if (this.menuElement === undefined) {
this.menuElement = document.createElement(this.menuTag) as PickerMenu;
this.appendChild(this.menuElement);
}
if (this.menuElement.id === "") {
this.menuElement.id = uniqueId("listbox-");
}
this.menuId = this.menuElement.id;
this.optionsPlaceholder = document.createComment("");
this.menuElement.append(this.optionsPlaceholder);
this.updateMenuConfig();
DOM.queueUpdate(() => this.initialize());
}
public disconnectedCallback() {
super.disconnectedCallback();
this.toggleFlyout(false);
this.inputElement.removeEventListener("input", this.handleTextInput);
this.inputElement.removeEventListener("click", this.handleInputClick);
if (this.inputElementView !== null) {
this.inputElementView.dispose();
this.inputElementView = null;
}
}
/**
* Move focus to the input element
* @public
*/
public focus() {
this.inputElement.focus();
}
/**
* Initialize the component. This is delayed a frame to ensure children are connected as well.
*/
private initialize(): void {
this.updateListItemTemplate();
this.updateOptionTemplate();
this.itemsRepeatBehavior = new RepeatDirective(
x => x.selectedItems,
x => x.activeListItemTemplate,
{ positioning: true }
).createBehavior(this.itemsPlaceholderElement);
this.inputElement.addEventListener("input", this.handleTextInput);
this.inputElement.addEventListener("click", this.handleInputClick);
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
this.$fastController.addBehaviors([this.itemsRepeatBehavior!]);
this.menuElement.suggestionsAvailableText = this.suggestionsAvailableText;
this.menuElement.addEventListener(
"optionsupdated",
this.handleMenuOptionsUpdated
);
this.optionsRepeatBehavior = new RepeatDirective(
x => x.filteredOptionsList,
x => x.activeMenuOptionTemplate,
{ positioning: true }
).createBehavior(this.optionsPlaceholder);
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
this.$fastController.addBehaviors([this.optionsRepeatBehavior!]);
this.handleSelectionChange();
}
/**
* Toggles the menu flyout
*/
private toggleFlyout(open: boolean): void {
if (this.flyoutOpen === open) {
return;
}
if (open && document.activeElement === this.inputElement) {
this.flyoutOpen = open;
DOM.queueUpdate(() => {
if (this.menuElement !== undefined) {
this.setFocusedOption(0);
} else {
this.disableMenu();
}
});
return;
}
this.flyoutOpen = false;
this.disableMenu();
return;
}
/**
* Handle input event from input element
*/
private handleTextInput = (e: InputEvent): void => {
this.query = this.inputElement.value;
};
/**
* Handle click event from input element
*/
private handleInputClick = (e: MouseEvent): void => {
e.preventDefault();
this.toggleFlyout(true);
};
/**
* Handle the menu options updated event from the child menu
*/
private handleMenuOptionsUpdated(e: Event): void {
e.preventDefault();
if (this.flyoutOpen) {
this.setFocusedOption(0);
}
}
/**
* Handle key down events.
*/
public handleKeyDown(e: KeyboardEvent): boolean {
if (e.defaultPrevented) {
return false;
}
switch (e.key) {
// TODO: what should "home" and "end" keys do, exactly?
//
// case keyHome: {
// if (!this.flyoutOpen) {
// this.toggleFlyout(true);
// } else {
// if (this.menuElement.optionElements.length > 0) {
// this.setFocusedOption(0);
// }
// }
// return false;
// }
// case keyEnd: {
// if (!this.flyoutOpen) {
// this.toggleFlyout(true);
// } else {
// if (this.menuElement.optionElements.length > 0) {
// this.toggleFlyout(true);
// this.setFocusedOption(this.menuElement.optionElements.length - 1);
// }
// }
// return false;
// }
case keyArrowDown: {
if (!this.flyoutOpen) {
this.toggleFlyout(true);
} else {
const nextFocusOptionIndex = this.flyoutOpen
? Math.min(
this.menuFocusIndex + 1,
this.menuElement.optionElements.length - 1
)
: 0;
this.setFocusedOption(nextFocusOptionIndex);
}
return false;
}
case keyArrowUp: {
if (!this.flyoutOpen) {
this.toggleFlyout(true);
} else {
const previousFocusOptionIndex = this.flyoutOpen
? Math.max(this.menuFocusIndex - 1, 0)
: 0;
this.setFocusedOption(previousFocusOptionIndex);
}
return false;
}
case keyEscape: {
this.toggleFlyout(false);
return false;
}
case keyEnter: {
if (
this.menuFocusIndex !== -1 &&
this.menuElement.optionElements.length > this.menuFocusIndex
) {
this.menuElement.optionElements[this.menuFocusIndex].click();
}
return false;
}
case keyArrowRight: {
if (document.activeElement !== this.inputElement) {
this.incrementFocusedItem(1);
return false;
}
// don't block if arrow keys moving caret in input element
return true;
}
case keyArrowLeft: {
if (this.inputElement.selectionStart === 0) {
this.incrementFocusedItem(-1);
return false;
}
// don't block if arrow keys moving caret in input element
return true;
}
case keyDelete:
case keyBackspace: {
if (document.activeElement === null) {
return true;
}
if (document.activeElement === this.inputElement) {
if (this.inputElement.selectionStart === 0) {
this.selection = this.selectedItems
.slice(0, this.selectedItems.length - 1)
.toString();
this.toggleFlyout(false);
return false;
}
// let text deletion proceed
return true;
}
const selectedItems: Element[] = Array.from(this.listElement.children);
const currentFocusedItemIndex: number = selectedItems.indexOf(
document.activeElement
);
if (currentFocusedItemIndex > -1) {
// delete currently focused item
this.selection = this.selectedItems
.splice(currentFocusedItemIndex, 1)
.toString();
DOM.queueUpdate(() => {
(selectedItems[
Math.min(selectedItems.length, currentFocusedItemIndex)
] as HTMLElement).focus();
});
return false;
}
return true;
}
}
this.toggleFlyout(true);
return true;
}
/**
* Handle focus in events.
*/
public handleFocusIn(e: FocusEvent): boolean {
return false;
}
/**
* Handle focus out events.
*/
public handleFocusOut(e: FocusEvent): boolean {
if (
this.menuElement === undefined ||
!this.menuElement.contains(e.relatedTarget as Element)
) {
this.toggleFlyout(false);
}
return false;
}
/**
* The list of selected items has changed
*/
public handleSelectionChange(): void {
if (this.selectedItems.toString() === this.selection) {
return;
}
this.selectedItems = this.selection === "" ? [] : this.selection.split(",");
this.updateFilteredOptions();
DOM.queueUpdate(() => {
this.checkMaxItems();
});
this.$emit("selectionchange", { bubbles: false });
}
/**
* Anchored region is loaded, menu and options exist in the DOM.
*/
public handleRegionLoaded(e: Event): void {
DOM.queueUpdate(() => {
this.setFocusedOption(0);
this.$emit("menuloaded", { bubbles: false });
});
}
/**
* Sets properties on the anchored region once it is instanciated.
*/
private setRegionProps = (): void => {
if (!this.flyoutOpen) {
return;
}
if (this.region === null || this.region === undefined) {
// TODO: limit this
DOM.queueUpdate(this.setRegionProps);
return;
}
this.region.anchorElement = this.inputElement;
};
/**
* Checks if the maximum number of items has been chosen and updates the ui.
*/
private checkMaxItems(): void {
if (this.inputElement === undefined) {
return;
}
if (
this.maxSelected !== undefined &&
this.selectedItems.length >= this.maxSelected
) {
if (document.activeElement === this.inputElement) {
const selectedItemInstances: Element[] = Array.from(
this.listElement.querySelectorAll("[role='listitem']")
);
(selectedItemInstances[
selectedItemInstances.length - 1
] as HTMLElement).focus();
}
this.inputElement.hidden = true;
} else {
this.inputElement.hidden = false;
}
}
/**
* A list item has been invoked.
*/
public handleItemInvoke(e: Event): boolean {
if (e.defaultPrevented) {
return false;
}
if (e.target instanceof PickerListItem) {
const listItems: Element[] = Array.from(
this.listElement.querySelectorAll("[role='listitem']")
);
const itemIndex: number = listItems.indexOf(e.target as Element);
if (itemIndex !== -1) {
const newSelection: string[] = this.selectedItems.slice();
newSelection.splice(itemIndex, 1);
this.selection = newSelection.toString();
DOM.queueUpdate(() => this.incrementFocusedItem(0));
}
return false;
}
return true;
}
/**
* A menu option has been invoked.
*/
public handleOptionInvoke(e: Event): boolean {
if (e.defaultPrevented) {
return false;
}
if (e.target instanceof PickerMenuOption) {
if (e.target.value !== undefined) {
this.selection = `${this.selection}${this.selection === "" ? "" : ","}${
e.target.value
}`;
}
this.inputElement.value = "";
this.query = "";
this.inputElement.focus();
this.toggleFlyout(false);
return false;
}
// const value: string = (e.target as PickerMenuOption).value;
return true;
}
/**
* Increments the focused list item by the specified amount
*/
private incrementFocusedItem(increment: number) {
if (this.selectedItems.length === 0) {
this.inputElement.focus();
return;
}
const selectedItemsAsElements: Element[] = Array.from(
this.listElement.querySelectorAll("[role='listitem']")
);
if (document.activeElement !== null) {
let currentFocusedItemIndex: number = selectedItemsAsElements.indexOf(
document.activeElement
);
if (currentFocusedItemIndex === -1) {
// use the input element
currentFocusedItemIndex = selectedItemsAsElements.length;
}
const newFocusedItemIndex = Math.min(
selectedItemsAsElements.length,
Math.max(0, currentFocusedItemIndex + increment)
);
if (newFocusedItemIndex === selectedItemsAsElements.length) {
if (
this.maxSelected !== undefined &&
this.selectedItems.length >= this.maxSelected
) {
(selectedItemsAsElements[
newFocusedItemIndex - 1
] as HTMLElement).focus();
} else {
this.inputElement.focus();
}
} else {
(selectedItemsAsElements[newFocusedItemIndex] as HTMLElement).focus();
}
}
}
/**
* Disables the menu. Note that the menu can be open, just doens't have any valid options on display.
*/
private disableMenu(): void {
this.menuFocusIndex = -1;
this.menuFocusOptionId = undefined;
this.inputElement?.removeAttribute("aria-activedescendant");
this.inputElement?.removeAttribute("aria-owns");
this.inputElement?.removeAttribute("aria-expanded");
}
/**
* Sets the currently focused menu option by index
*/
private setFocusedOption(optionIndex: number): void {
if (
!this.flyoutOpen ||
optionIndex === -1 ||
this.showNoOptions ||
this.showLoading
) {
this.disableMenu();
return;
}
if (this.menuElement.optionElements.length === 0) {
return;
}
this.menuElement.optionElements.forEach((element: HTMLElement) => {
element.setAttribute("aria-selected", "false");
});
this.menuFocusIndex = optionIndex;
if (this.menuFocusIndex > this.menuElement.optionElements.length - 1) {
this.menuFocusIndex = this.menuElement.optionElements.length - 1;
}
this.menuFocusOptionId = this.menuElement.optionElements[this.menuFocusIndex].id;
this.inputElement.setAttribute("aria-owns", this.menuId);
this.inputElement.setAttribute("aria-expanded", "true");
this.inputElement.setAttribute("aria-activedescendant", this.menuFocusOptionId);
const focusedOption = this.menuElement.optionElements[this.menuFocusIndex];
focusedOption.setAttribute("aria-selected", "true");
this.menuElement.scrollTo(0, focusedOption.offsetTop);
}
/**
* Updates the template used for the list item repeat behavior
*/
private updateListItemTemplate(): void {
this.activeListItemTemplate =
this.listItemTemplate ?? this.defaultListItemTemplate;
}
/**
* Updates the template used for the menu option repeat behavior
*/
private updateOptionTemplate(): void {
this.activeMenuOptionTemplate =
this.menuOptionTemplate ?? this.defaultMenuOptionTemplate;
}
/**
* Updates the filtered options array
*/
private updateFilteredOptions(): void {
this.filteredOptionsList = this.optionsList.slice(0);
if (this.filterSelected) {
this.filteredOptionsList = this.filteredOptionsList.filter(
el => this.selectedItems.indexOf(el) === -1
);
}
if (this.filterQuery && this.query !== "" && this.query !== undefined) {
this.filteredOptionsList = this.filteredOptionsList.filter(
el => el.indexOf(this.query) !== -1
);
}
}
/**
* Updates the menu configuration
*/
private updateMenuConfig(): void {
let newConfig = this.configLookup[this.menuPlacement];
if (newConfig === null) {
newConfig = FlyoutPosBottomFill;
}
this.menuConfig = {
...newConfig,
autoUpdateMode: "auto",
fixedPlacement: true,
horizontalViewportLock: false,
verticalViewportLock: false,
};
}
/**
* matches menu placement values with the associated menu config
*/
private configLookup: object = {
top: FlyoutPosTop,
bottom: FlyoutPosBottom,
tallest: FlyoutPosTallest,
"top-fill": FlyoutPosTopFill,
"bottom-fill": FlyoutPosBottomFill,
"tallest-fill": FlyoutPosTallestFill,
};
} | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the SubscriptionClient.
*/
export interface Operations {
/**
* Lists all of the available Microsoft.Subscription API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available Microsoft.Subscription API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
list(callback: ServiceCallback<models.OperationListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
}
/**
* @class
* SubscriptionOperations
* __NOTE__: An instance of this class is automatically created for an
* instance of the SubscriptionClient.
*/
export interface SubscriptionOperations {
/**
* Lists all of the available pending Microsoft.Subscription API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubscriptionOperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SubscriptionOperationListResult>>;
/**
* Lists all of the available pending Microsoft.Subscription API operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SubscriptionOperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SubscriptionOperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link SubscriptionOperationListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SubscriptionOperationListResult>;
list(callback: ServiceCallback<models.SubscriptionOperationListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SubscriptionOperationListResult>): void;
}
/**
* @class
* SubscriptionFactory
* __NOTE__: An instance of this class is automatically created for an
* instance of the SubscriptionClient.
*/
export interface SubscriptionFactory {
/**
* Creates an Azure subscription
*
* @param {string} enrollmentAccountName The name of the enrollment account to
* which the subscription will be billed.
*
* @param {object} body The subscription creation parameters.
*
* @param {string} [body.displayName] The display name of the subscription.
*
* @param {array} [body.owners] The list of principals that should be granted
* Owner access on the subscription. Principals should be of type User, Service
* Principal or Security Group.
*
* @param {string} [body.offerType] The offer type of the subscription. For
* example, MS-AZR-0017P (EnterpriseAgreement) and MS-AZR-0148P
* (EnterpriseAgreement devTest) are available. Only valid when creating a
* subscription in a enrollment account scope. Possible values include:
* 'MS-AZR-0017P', 'MS-AZR-0148P'
*
* @param {object} [body.additionalParameters] Additional, untyped parameters
* to support custom subscription creation scenarios.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubscriptionCreationResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createSubscriptionInEnrollmentAccountWithHttpOperationResponse(enrollmentAccountName: string, body: models.SubscriptionCreationParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SubscriptionCreationResult>>;
/**
* Creates an Azure subscription
*
* @param {string} enrollmentAccountName The name of the enrollment account to
* which the subscription will be billed.
*
* @param {object} body The subscription creation parameters.
*
* @param {string} [body.displayName] The display name of the subscription.
*
* @param {array} [body.owners] The list of principals that should be granted
* Owner access on the subscription. Principals should be of type User, Service
* Principal or Security Group.
*
* @param {string} [body.offerType] The offer type of the subscription. For
* example, MS-AZR-0017P (EnterpriseAgreement) and MS-AZR-0148P
* (EnterpriseAgreement devTest) are available. Only valid when creating a
* subscription in a enrollment account scope. Possible values include:
* 'MS-AZR-0017P', 'MS-AZR-0148P'
*
* @param {object} [body.additionalParameters] Additional, untyped parameters
* to support custom subscription creation scenarios.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SubscriptionCreationResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SubscriptionCreationResult} [result] - The deserialized result object if an error did not occur.
* See {@link SubscriptionCreationResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createSubscriptionInEnrollmentAccount(enrollmentAccountName: string, body: models.SubscriptionCreationParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SubscriptionCreationResult>;
createSubscriptionInEnrollmentAccount(enrollmentAccountName: string, body: models.SubscriptionCreationParameters, callback: ServiceCallback<models.SubscriptionCreationResult>): void;
createSubscriptionInEnrollmentAccount(enrollmentAccountName: string, body: models.SubscriptionCreationParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SubscriptionCreationResult>): void;
/**
* Creates an Azure subscription
*
* @param {string} enrollmentAccountName The name of the enrollment account to
* which the subscription will be billed.
*
* @param {object} body The subscription creation parameters.
*
* @param {string} [body.displayName] The display name of the subscription.
*
* @param {array} [body.owners] The list of principals that should be granted
* Owner access on the subscription. Principals should be of type User, Service
* Principal or Security Group.
*
* @param {string} [body.offerType] The offer type of the subscription. For
* example, MS-AZR-0017P (EnterpriseAgreement) and MS-AZR-0148P
* (EnterpriseAgreement devTest) are available. Only valid when creating a
* subscription in a enrollment account scope. Possible values include:
* 'MS-AZR-0017P', 'MS-AZR-0148P'
*
* @param {object} [body.additionalParameters] Additional, untyped parameters
* to support custom subscription creation scenarios.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubscriptionCreationResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginCreateSubscriptionInEnrollmentAccountWithHttpOperationResponse(enrollmentAccountName: string, body: models.SubscriptionCreationParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SubscriptionCreationResult>>;
/**
* Creates an Azure subscription
*
* @param {string} enrollmentAccountName The name of the enrollment account to
* which the subscription will be billed.
*
* @param {object} body The subscription creation parameters.
*
* @param {string} [body.displayName] The display name of the subscription.
*
* @param {array} [body.owners] The list of principals that should be granted
* Owner access on the subscription. Principals should be of type User, Service
* Principal or Security Group.
*
* @param {string} [body.offerType] The offer type of the subscription. For
* example, MS-AZR-0017P (EnterpriseAgreement) and MS-AZR-0148P
* (EnterpriseAgreement devTest) are available. Only valid when creating a
* subscription in a enrollment account scope. Possible values include:
* 'MS-AZR-0017P', 'MS-AZR-0148P'
*
* @param {object} [body.additionalParameters] Additional, untyped parameters
* to support custom subscription creation scenarios.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SubscriptionCreationResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SubscriptionCreationResult} [result] - The deserialized result object if an error did not occur.
* See {@link SubscriptionCreationResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginCreateSubscriptionInEnrollmentAccount(enrollmentAccountName: string, body: models.SubscriptionCreationParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SubscriptionCreationResult>;
beginCreateSubscriptionInEnrollmentAccount(enrollmentAccountName: string, body: models.SubscriptionCreationParameters, callback: ServiceCallback<models.SubscriptionCreationResult>): void;
beginCreateSubscriptionInEnrollmentAccount(enrollmentAccountName: string, body: models.SubscriptionCreationParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SubscriptionCreationResult>): void;
}
/**
* @class
* Subscriptions
* __NOTE__: An instance of this class is automatically created for an
* instance of the SubscriptionClient.
*/
export interface Subscriptions {
/**
* @summary Gets all available geo-locations.
*
* This operation provides all the locations that are available for resource
* providers; however, each resource provider may support a subset of this
* list.
*
* @param {string} subscriptionId The ID of the target subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<LocationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listLocationsWithHttpOperationResponse(subscriptionId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationListResult>>;
/**
* @summary Gets all available geo-locations.
*
* This operation provides all the locations that are available for resource
* providers; however, each resource provider may support a subset of this
* list.
*
* @param {string} subscriptionId The ID of the target subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {LocationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {LocationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link LocationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listLocations(subscriptionId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationListResult>;
listLocations(subscriptionId: string, callback: ServiceCallback<models.LocationListResult>): void;
listLocations(subscriptionId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationListResult>): void;
/**
* Gets details about a specified subscription.
*
* @param {string} subscriptionId The ID of the target subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Subscription>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(subscriptionId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Subscription>>;
/**
* Gets details about a specified subscription.
*
* @param {string} subscriptionId The ID of the target subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Subscription} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Subscription} [result] - The deserialized result object if an error did not occur.
* See {@link Subscription} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(subscriptionId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Subscription>;
get(subscriptionId: string, callback: ServiceCallback<models.Subscription>): void;
get(subscriptionId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Subscription>): void;
/**
* Gets all subscriptions for a tenant.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubscriptionListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SubscriptionListResult>>;
/**
* Gets all subscriptions for a tenant.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SubscriptionListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SubscriptionListResult} [result] - The deserialized result object if an error did not occur.
* See {@link SubscriptionListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SubscriptionListResult>;
list(callback: ServiceCallback<models.SubscriptionListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SubscriptionListResult>): void;
/**
* Gets all subscriptions for a tenant.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SubscriptionListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SubscriptionListResult>>;
/**
* Gets all subscriptions for a tenant.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {SubscriptionListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {SubscriptionListResult} [result] - The deserialized result object if an error did not occur.
* See {@link SubscriptionListResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SubscriptionListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.SubscriptionListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SubscriptionListResult>): void;
}
/**
* @class
* Tenants
* __NOTE__: An instance of this class is automatically created for an
* instance of the SubscriptionClient.
*/
export interface Tenants {
/**
* Gets the tenants for your account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TenantListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TenantListResult>>;
/**
* Gets the tenants for your account.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TenantListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TenantListResult} [result] - The deserialized result object if an error did not occur.
* See {@link TenantListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TenantListResult>;
list(callback: ServiceCallback<models.TenantListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TenantListResult>): void;
/**
* Gets the tenants for your account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<TenantListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TenantListResult>>;
/**
* Gets the tenants for your account.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {TenantListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {TenantListResult} [result] - The deserialized result object if an error did not occur.
* See {@link TenantListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TenantListResult>;
listNext(nextPageLink: string, callback: ServiceCallback<models.TenantListResult>): void;
listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TenantListResult>): void;
} | the_stack |
import { cache } from "decorator-cache-getter";
import { readGString } from "../utils";
import { raise } from "../../utils/console";
import { NonNullNativeStruct } from "../../utils/native-struct";
import { cacheInstances, getOrNull, IterableRecord, makeRecordFromNativeIterator } from "../../utils/utils";
/** Represents a `Il2CppClass`. */
@cacheInstances
class Il2CppClass extends NonNullNativeStruct {
/** Gets the array class which encompass the current class. */
@cache
get arrayClass(): Il2Cpp.Class {
return new Il2Cpp.Class(Il2Cpp.Api._classGetArrayClass(this, 1));
}
/** Gets the size of the object encompassed by the current array class. */
@cache
get arrayElementSize(): number {
return Il2Cpp.Api._classGetArrayElementSize(this);
}
/** Gets the name of the assembly in which the current class is defined. */
@cache
get assemblyName(): string {
return Il2Cpp.Api._classGetAssemblyName(this).readUtf8String()!;
}
/** Gets the class that declares the current nested class. */
@cache
get declaringClass(): Il2Cpp.Class | null {
return getOrNull(Il2Cpp.Api._classGetDeclaringType(this), Il2Cpp.Class);
}
/** Gets the encompassed type of this array, reference, pointer or enum type. */
@cache
get baseType(): Il2Cpp.Type | null {
return getOrNull(Il2Cpp.Api._classGetBaseType(this), Il2Cpp.Type);
}
/** Gets the class of the object encompassed or referred to by the current array, pointer or reference class. */
@cache
get elementClass(): Il2Cpp.Class | null {
return getOrNull(Il2Cpp.Api._classGetElementClass(this), Il2Cpp.Class);
}
/** Gets the amount of the fields of the current class. */
@cache
get fieldCount(): UInt64 {
return Il2Cpp.Api._classGetFieldCount(this);
}
/** Gets the fields of the current class. */
@cache
get fields(): IterableRecord<Il2Cpp.Field> {
return makeRecordFromNativeIterator(this, Il2Cpp.Api._classGetFields, Il2Cpp.Field, field => field.name);
}
/** Gets the flags of the current class. */
@cache
get flags(): number {
return Il2Cpp.Api._classGetFlags(this);
}
/** Gets the amount of generic parameters of this generic class. */
@cache
get genericParameterCount(): number {
if (!this.isGeneric) {
return 0;
}
return this.type.object.methods.GetGenericArguments.invoke<Il2Cpp.Array>().length;
}
/** Determines whether the GC has tracking references to the current class instances. */
@cache
get hasReferences(): boolean {
return !!Il2Cpp.Api._classHasReferences(this);
}
/** Determines whether ther current class has a valid static constructor. */
@cache
get hasStaticConstructor(): boolean {
return ".cctor" in this.methods && !this.methods[".cctor"].virtualAddress.isNull();
}
/** Gets the image in which the current class is defined. */
@cache
get image(): Il2Cpp.Image {
return new Il2Cpp.Image(Il2Cpp.Api._classGetImage(this));
}
/** Gets the size of the instance of the current class. */
@cache
get instanceSize(): number {
return Il2Cpp.Api._classGetInstanceSize(this);
}
/** Determines whether the current class is abstract. */
@cache
get isAbstract(): boolean {
return !!Il2Cpp.Api._classIsAbstract(this);
}
/** Determines whether the current class is blittable. */
@cache
get isBlittable(): boolean {
return !!Il2Cpp.Api._classIsBlittable(this);
}
/** Determines whether the current class is an enumeration. */
@cache
get isEnum(): boolean {
return !!Il2Cpp.Api._classIsEnum(this);
}
/** Determines whether the current class is a generic one. */
@cache
get isGeneric(): boolean {
return !!Il2Cpp.Api._classIsGeneric(this);
}
/** Determines whether the current class is inflated. */
@cache
get isInflated(): boolean {
return !!Il2Cpp.Api._classIsInflated(this);
}
/** Determines whether the current class is an interface. */
@cache
get isInterface(): boolean {
return !!Il2Cpp.Api._classIsInterface(this);
}
/** Determines whether the current class is a value type. */
@cache
get isValueType(): boolean {
return !!Il2Cpp.Api._classIsValueType(this);
}
/** Gets the amount of the implemented or inherited interfaces by the current class. */
@cache
get interfaceCount(): number {
return Il2Cpp.Api._classGetInterfaceCount(this);
}
/** Gets the interfaces implemented or inherited by the current class. */
@cache
get interfaces(): IterableRecord<Il2Cpp.Class> {
return makeRecordFromNativeIterator(this, Il2Cpp.Api._classGetInterfaces, Il2Cpp.Class, klass => klass.type.name);
}
/** Gets the amount of the implemented methods by the current class. */
@cache
get methodCount(): number {
return Il2Cpp.Api._classGetMethodCount(this);
}
/** Gets the methods implemented by the current class. */
@cache
get methods(): IterableRecord<Il2Cpp.Method> {
return makeRecordFromNativeIterator(this, Il2Cpp.Api._classGetMethods, Il2Cpp.Method, method => method.name, true);
}
/** Gets the name of the current class. */
@cache
get name(): string {
return Il2Cpp.Api._classGetName(this).readUtf8String()!;
}
/** Gets the namespace of the current class. */
@cache
get namespace(): string {
return Il2Cpp.Api._classGetNamespace(this).readUtf8String()!;
}
/** Gets the classes nested inside the current class. */
@cache
get nestedClasses(): IterableRecord<Il2Cpp.Class> {
return makeRecordFromNativeIterator(this, Il2Cpp.Api._classGetNestedClasses, Il2Cpp.Class, klass => klass.name, true);
}
/** Gets the class from which the current class directly inherits. */
@cache
get parent(): Il2Cpp.Class | null {
return getOrNull(Il2Cpp.Api._classGetParent(this), Il2Cpp.Class);
}
/** Gets the rank (number of dimensions) of the current array class. */
@cache
get rank(): number {
return Il2Cpp.Api._classGetRank(this);
}
/** Gets a pointer to the static fields of the current class. */
@cache
get staticFieldsData(): NativePointer {
return Il2Cpp.Api._classGetStaticFieldData(this);
}
/** Gets the size of the instance - as a value type - of the current class. */
@cache
get valueSize(): number {
return Il2Cpp.Api._classGetValueSize(this, NULL);
}
/** Gets the type of the current class. */
@cache
get type(): Il2Cpp.Type {
return new Il2Cpp.Type(Il2Cpp.Api._classGetType(this));
}
/** Allocates a new object of the current class. */
alloc(): Il2Cpp.Object {
return new Il2Cpp.Object(Il2Cpp.Api._objectNew(this));
}
/** Gets the field identified by the given name. */
getField(name: string): Il2Cpp.Field | null {
return getOrNull(Il2Cpp.Api._classGetFieldFromName(this, Memory.allocUtf8String(name)), Il2Cpp.Field);
}
/** Gets the method identified by the given name and parameter count. */
getMethod(name: string, parameterCount: number = -1): Il2Cpp.Method | null {
return getOrNull(Il2Cpp.Api._classGetMethodFromName(this, Memory.allocUtf8String(name), parameterCount), Il2Cpp.Method);
}
/** Builds a generic instance of the current generic class. */
inflate(...classes: Il2Cpp.Class[]): Il2Cpp.Class {
if (!this.isGeneric) {
raise(`Cannot inflate ${this.type.name} because it's not generic.`);
}
const types = classes.map(klass => klass.type.object);
const typeArray = Il2Cpp.Array.from(Il2Cpp.Image.corlib.classes["System.Type"], types);
// TODO: typeArray leaks
return this.inflateRaw(typeArray);
}
/** @internal */
inflateRaw(typeArray: Il2Cpp.Array<Il2Cpp.Object>): Il2Cpp.Class {
const MakeGenericType = this.type.object.class.getMethod("MakeGenericType", 1)!;
let object = this.type.object;
while (!object.class.equals(MakeGenericType.class)) object = object.base;
const inflatedType = MakeGenericType.invokeRaw(object, typeArray);
return new Il2Cpp.Class(Il2Cpp.Api._classFromSystemType(inflatedType as Il2Cpp.Object));
}
/** Calls the static constructor of the current class. */
initialize(): void {
Il2Cpp.try(() => Il2Cpp.Api._classInit(this));
}
/** Determines whether an instance of `other` class can be assigned to a variable of the current type. */
isAssignableFrom(other: Il2Cpp.Class): boolean {
return !!Il2Cpp.Api._classIsAssignableFrom(this, other);
}
/** Determines whether the current class derives from `other` class. */
isSubclassOf(other: Il2Cpp.Class, checkInterfaces: boolean): boolean {
return !!Il2Cpp.Api._classIsSubclassOf(this, other, +checkInterfaces);
}
/** Allocates a new object of the current class and calls its default constructor. */
new(): Il2Cpp.Object {
const object = this.alloc();
const exceptionArray = Memory.alloc(Process.pointerSize);
Il2Cpp.Api._objectInit(object, exceptionArray);
const exception = exceptionArray.readPointer();
if (!exception.isNull()) {
raise(new Il2Cpp.Object(exception).toString()!);
}
return object;
}
override toString(): string {
return readGString(Il2Cpp.Api._toString(this, Il2Cpp.Api._classToString))!;
}
/** Executes a callback for every defined class. */
static enumerate(block: (klass: Il2Cpp.Class) => void): void {
const callback = new NativeCallback(
function (klass: NativePointer, _: NativePointer): void {
block(new Il2Cpp.Class(klass));
},
"void",
["pointer", "pointer"]
);
return Il2Cpp.Api._classForEach(callback, NULL);
}
}
Il2Cpp.Class = Il2CppClass;
declare global {
namespace Il2Cpp {
class Class extends Il2CppClass {}
}
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
currentTank?: string;
blunt: { [playerName: string]: boolean };
slashing: { [playerName: string]: boolean };
soonAfterWeaponChange: boolean;
seenDiamondDust: boolean;
}
// TODO: some sort of warning about extra tank damage during bow phase?
// TODO: should the post-staff "spread" happen unconditionally prior to marker?
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheAkhAfahAmphitheatreExtreme,
timelineFile: 'shiva-ex.txt',
initData: () => {
return {
blunt: {},
slashing: {},
soonAfterWeaponChange: false,
seenDiamondDust: false,
};
},
timelineTriggers: [
{
id: 'ShivaEx Absolute Zero',
regex: /Absolute Zero/,
beforeSeconds: 5,
// These are usually doubled, so avoid spamming.
suppressSeconds: 10,
response: Responses.aoe(),
},
{
id: 'ShivaEx Icebrand',
regex: /Icebrand/,
beforeSeconds: 5,
suppressSeconds: 1,
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Party Share Tankbuster',
de: 'Tankbuster mit der Gruppe Teilen',
fr: 'Partagez le Tank buster avec le groupe',
ja: '頭割りタンクバスター',
cn: '团队分摊死刑',
ko: '파티 쉐어 탱버',
},
},
},
{
// Heavenly Strike is knockback only when unshielded, so use "info" here.
id: 'ShivaEx Heavenly Strike',
regex: /Heavenly Strike/,
beforeSeconds: 5,
suppressSeconds: 1,
response: Responses.knockback('info'),
},
],
triggers: [
{
id: 'ShivaEx Staff Phase',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Shiva', id: '995', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Shiva', id: '995', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Shiva', id: '995', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'シヴァ', id: '995', capture: false }),
netRegexCn: NetRegexes.ability({ source: '希瓦', id: '995', capture: false }),
netRegexKo: NetRegexes.ability({ source: '시바', id: '995', capture: false }),
response: (data, _matches, output) => {
// cactbot-builtin-response
output.responseOutputStrings = {
staffTankSwap: {
en: 'Staff (Tank Swap)',
de: 'Stab (Tankwechsel)',
fr: 'Bâton (Tank Swap)',
ja: '杖 (スイッチ)',
cn: '权杖(换T)',
ko: '지팡이 (탱커 교대)',
},
staff: {
en: 'Staff',
de: 'Stab',
fr: 'Bâton',
ja: '杖',
cn: '权杖',
ko: '지팡이',
},
};
if (data.role === 'tank') {
if (data.currentTank && data.blunt[data.currentTank])
return { alertText: output.staffTankSwap!() };
}
return { infoText: output.staff!() };
},
run: (data) => data.soonAfterWeaponChange = true,
},
{
id: 'ShivaEx Sword Phase',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Shiva', id: '993', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Shiva', id: '993', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Shiva', id: '993', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'シヴァ', id: '993', capture: false }),
netRegexCn: NetRegexes.ability({ source: '希瓦', id: '993', capture: false }),
netRegexKo: NetRegexes.ability({ source: '시바', id: '993', capture: false }),
response: (data, _matches, output) => {
// cactbot-builtin-response
output.responseOutputStrings = {
swordTankSwap: {
en: 'Sword (Tank Swap)',
de: 'Schwert (Tankwechsel)',
fr: 'Épée (Tank Swap)',
ja: '剣 (スイッチ)',
cn: '剑(换T)',
ko: '검 (탱커 교대)',
},
sword: {
en: 'Sword',
de: 'Schwert',
fr: 'Épée',
ja: '剣',
cn: '剑',
ko: '검',
},
};
if (data.role === 'tank') {
if (data.currentTank && data.slashing[data.currentTank])
return { alertText: output.swordTankSwap!() };
}
return { infoText: output.sword!() };
},
run: (data) => data.soonAfterWeaponChange = true,
},
{
id: 'ShivaEx Weapon Change Delayed',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Shiva', id: ['993', '995'], capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Shiva', id: ['993', '995'], capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Shiva', id: ['993', '995'], capture: false }),
netRegexJa: NetRegexes.ability({ source: 'シヴァ', id: ['993', '995'], capture: false }),
netRegexCn: NetRegexes.ability({ source: '希瓦', id: ['993', '995'], capture: false }),
netRegexKo: NetRegexes.ability({ source: '시바', id: ['993', '995'], capture: false }),
delaySeconds: 30,
run: (data) => data.soonAfterWeaponChange = false,
},
{
id: 'ShivaEx Slashing Resistance Down Gain',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '23C' }),
run: (data, matches) => data.slashing[matches.target] = true,
},
{
id: 'ShivaEx Slashing Resistance Down Lose',
type: 'LosesEffect',
netRegex: NetRegexes.losesEffect({ effectId: '23C' }),
run: (data, matches) => data.slashing[matches.target] = false,
},
{
id: 'ShivaEx Blunt Resistance Down Gain',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '23D' }),
run: (data, matches) => data.blunt[matches.target] = true,
},
{
id: 'ShivaEx Blunt Resistance Down Lose',
type: 'LosesEffect',
netRegex: NetRegexes.losesEffect({ effectId: '23D' }),
run: (data, matches) => data.blunt[matches.target] = false,
},
{
id: 'ShivaEx Current Tank',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Shiva', id: 'BE5' }),
netRegexDe: NetRegexes.ability({ source: 'Shiva', id: 'BE5' }),
netRegexFr: NetRegexes.ability({ source: 'Shiva', id: 'BE5' }),
netRegexJa: NetRegexes.ability({ source: 'シヴァ', id: 'BE5' }),
netRegexCn: NetRegexes.ability({ source: '希瓦', id: 'BE5' }),
netRegexKo: NetRegexes.ability({ source: '시바', id: 'BE5' }),
run: (data, matches) => data.currentTank = matches.target,
},
{
id: 'ShivaEx Hailstorm Marker',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '001D' }),
condition: Conditions.targetIsYou(),
response: Responses.spread('alert'),
},
{
id: 'ShivaEx Glacier Bash',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: 'BE9', capture: false }),
response: Responses.getBehind('info'),
},
{
id: 'ShivaEx Whiteout',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: 'BEC', capture: false }),
response: Responses.getIn(),
},
{
id: 'ShivaEx Diamond Dust',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Shiva', id: '98A', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Shiva', id: '98A', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Shiva', id: '98A', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'シヴァ', id: '98A', capture: false }),
netRegexCn: NetRegexes.ability({ source: '希瓦', id: '98A', capture: false }),
netRegexKo: NetRegexes.ability({ source: '시바', id: '98A', capture: false }),
run: (data) => data.seenDiamondDust = true,
},
{
id: 'ShivaEx Frost Bow',
type: 'Ability',
netRegex: NetRegexes.ability({ source: 'Shiva', id: 'BDD', capture: false }),
netRegexDe: NetRegexes.ability({ source: 'Shiva', id: 'BDD', capture: false }),
netRegexFr: NetRegexes.ability({ source: 'Shiva', id: 'BDD', capture: false }),
netRegexJa: NetRegexes.ability({ source: 'シヴァ', id: 'BDD', capture: false }),
netRegexCn: NetRegexes.ability({ source: '希瓦', id: 'BDD', capture: false }),
netRegexKo: NetRegexes.ability({ source: '시바', id: 'BDD', capture: false }),
response: Responses.getBehind('alarm'),
run: (data) => {
// Just in case ACT has crashed or something, make sure this state is correct.
data.seenDiamondDust = true;
},
},
{
id: 'ShivaEx Avalanche Marker Me',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '001A' }),
condition: Conditions.targetIsYou(),
// Responses.knockback does not quite give the 'laser cleave' aspect here.
alarmText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Knockback Laser on YOU',
de: 'Rückstoß-Laser auf DIR',
fr: 'Poussée-Laser sur VOUS',
ja: '自分にアバランチ',
cn: '击退激光点名',
ko: '넉백 레이저 대상자',
},
},
},
{
id: 'ShivaEx Avalanche Marker Other',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '001A' }),
condition: Conditions.targetIsNotYou(),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Avoid Laser',
de: 'Laser ausweichen',
fr: 'Évitez le laser',
ja: 'アバランチを避ける',
cn: '躲避击退激光',
ko: '레이저 피하기',
},
},
},
{
id: 'ShivaEx Shiva Circles',
type: 'Ability',
netRegex: NetRegexes.abilityFull({ source: 'Shiva', id: 'BEB' }),
netRegexDe: NetRegexes.abilityFull({ source: 'Shiva', id: 'BEB' }),
netRegexFr: NetRegexes.abilityFull({ source: 'Shiva', id: 'BEB' }),
netRegexJa: NetRegexes.abilityFull({ source: 'シヴァ', id: 'BEB' }),
netRegexCn: NetRegexes.abilityFull({ source: '希瓦', id: 'BEB' }),
netRegexKo: NetRegexes.abilityFull({ source: '시바', id: 'BEB' }),
condition: (data, matches) => {
// Ignore other middle circles and try to only target the Icicle Impact x9.
if (!data.seenDiamondDust || data.soonAfterWeaponChange)
return false;
const x = parseFloat(matches.x);
const y = parseFloat(matches.y);
return Math.abs(x) < 0.1 && Math.abs(y) < 0.1;
},
// This can hit multiple people.
suppressSeconds: 10,
response: Responses.goMiddle('info'),
},
{
id: 'ShivaEx Permafrost',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: 'BE3', capture: false }),
response: Responses.stopMoving('alert'),
},
{
id: 'ShivaEx Ice Boulder',
type: 'Ability',
netRegex: NetRegexes.ability({ id: 'C8A' }),
condition: Conditions.targetIsNotYou(),
infoText: (data, matches, output) => output.text!({ player: data.ShortName(matches.target) }),
outputStrings: {
text: {
en: 'Free ${player}',
de: 'Befreie ${player}',
fr: 'Libérez ${player}',
ja: '${player}を救って',
cn: '解救${player}',
ko: '${player}감옥 해제',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Ice Soldier': 'Eissoldat',
'Shiva': 'Shiva',
},
'replaceText': {
'\\(circle\\)': '(Kreis)',
'\\(cross\\)': '(Kreuz)',
'Absolute Zero': 'Absoluter Nullpunkt',
'Avalanche': 'Lawine',
'Diamond Dust': 'Diamantenstaub',
'Dreams Of Ice': 'Eisige Träume',
'Frost Blade': 'Frostklinge',
'Frost Bow': 'Frostbogen',
'Frost Staff': 'Froststab',
'Glacier Bash': 'Gletscherlauf',
'Glass Dance': 'Gläserner Tanz',
'Hailstorm': 'Hagelsturm',
'Heavenly Strike': 'Himmelszorn',
'Icebrand': 'Eisbrand',
'Icicle Impact': 'Eiszapfen-Schlag',
'Melt': 'Schmelzen',
'Permafrost': 'Permafrost',
'Whiteout': 'Schneeblindheit',
},
},
{
'locale': 'fr',
'replaceSync': {
'Ice Soldier': 'soldat de glace',
'Shiva': 'Shiva',
},
'replaceText': {
'\\?': ' ?',
'\\(circle\\)': '(cercle)',
'\\(cross\\)': '(croix)',
'Absolute Zero': 'Zéro absolu',
'Avalanche': 'Avalanche',
'Diamond Dust': 'Poussière de diamant',
'Dreams Of Ice': 'Illusions glacées',
'Frost Blade': 'Lame glaciale',
'Frost Bow': 'Arc glacial',
'Frost Staff': 'Bâton glacial',
'Glacier Bash': 'Effondrement de glacier',
'Glass Dance': 'Danse de glace',
'Hailstorm': 'Averse de grêle',
'Heavenly Strike': 'Frappe céleste',
'Icebrand': 'Épée de glace',
'Icicle Impact': 'Impact de stalactite',
'Melt': 'Fonte',
'Permafrost': 'Permafrost',
'Whiteout': 'Fusion Glaciation',
},
},
{
'locale': 'ja',
'replaceSync': {
'Ice Soldier': 'アイスソルジャー',
'Shiva': 'シヴァ',
},
'replaceText': {
'\\?': ' ?',
'\\(circle\\)': '(輪)',
'\\(cross\\)': '(十字)',
'Absolute Zero': '絶対零度',
'Avalanche': 'アバランチ',
'Diamond Dust': 'ダイアモンドダスト',
'Dreams Of Ice': '氷結の幻想',
'Frost Blade': '凍てつく剣',
'Frost Bow': '凍てつく弓',
'Frost Staff': '凍てつく杖',
'Glacier Bash': 'グレイシャーバッシュ',
'Glass Dance': '氷雪乱舞',
'Hailstorm': 'ヘイルストーム',
'Heavenly Strike': 'ヘヴンリーストライク',
'Icebrand': 'アイスブランド',
'Icicle Impact': 'アイシクルインパクト',
'Melt': 'ウェポンメルト',
'Permafrost': 'パーマフロスト',
'Whiteout': 'ホワイトアウト',
},
},
{
'locale': 'cn',
'replaceSync': {
'Ice Soldier': '寒冰士兵',
'Shiva': '希瓦',
},
'replaceText': {
'\\(circle\\)': '(圆)',
'\\(cross\\)': '(十字)',
'Absolute Zero': '绝对零度',
'Avalanche': '雪崩',
'Diamond Dust': '钻石星尘',
'Dreams Of Ice': '寒冰的幻想',
'Frost Blade': '冰霜之剑',
'Frost Bow': '冰霜之弓',
'Frost Staff': '冰霜之杖',
'Glacier Bash': '冰河怒击',
'Glass Dance': '冰雪乱舞',
'Hailstorm': '冰雹',
'Heavenly Strike': '天降一击',
'Icebrand': '冰印剑',
'Icicle Impact': '冰柱冲击',
'Melt': '武器融化',
'Permafrost': '永久冻土',
'Whiteout': '白化视界',
},
},
{
'locale': 'ko',
'replaceSync': {
'Ice Soldier': '얼음 병사',
'Shiva': '시바',
},
'replaceText': {
'\\(circle\\)': '(원형)',
'\\(cross\\)': '(십자)',
'Absolute Zero': '절대영도',
'Avalanche': '눈사태',
'Diamond Dust': '다이아몬드 더스트',
'Dreams Of Ice': '빙결의 환상',
'Frost Blade': '얼어붙은 검',
'Frost Bow': '얼어붙은 활',
'Frost Staff': '얼어붙은 지팡이',
'Glacier Bash': '빙하 강타',
'Glass Dance': '빙설난무',
'Hailstorm': '우박 폭풍',
'Heavenly Strike': '천상의 일격',
'Icebrand': '얼음의 낙인',
'Icicle Impact': '고드름 낙하',
'Melt': '무기 용해',
'Permafrost': '영구동토',
'Whiteout': '폭설',
},
},
],
};
export default triggerSet; | the_stack |
import utils from './utils.js';
import sinon from 'sinon';
import expect from 'expect';
import {
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
itFailsFirefox,
} from './mocha-utils'; // eslint-disable-line import/extensions
describe('waittask specs', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.waitFor', function () {
/* This method is deprecated but we don't want the warnings showing up in
* tests. Until we remove this method we still want to ensure we don't break
* it.
*/
beforeEach(() => sinon.stub(console, 'warn').callsFake(() => {}));
it('should wait for selector', async () => {
const { page, server } = getTestState();
let found = false;
const waitFor = page.waitFor('div').then(() => (found = true));
await page.goto(server.EMPTY_PAGE);
expect(found).toBe(false);
await page.goto(server.PREFIX + '/grid.html');
await waitFor;
expect(found).toBe(true);
});
it('should wait for an xpath', async () => {
const { page, server } = getTestState();
let found = false;
const waitFor = page.waitFor('//div').then(() => (found = true));
await page.goto(server.EMPTY_PAGE);
expect(found).toBe(false);
await page.goto(server.PREFIX + '/grid.html');
await waitFor;
expect(found).toBe(true);
});
it('should allow you to select an element with parenthesis-starting xpath', async () => {
const { page, server } = getTestState();
let found = false;
const waitFor = page.waitFor('(//img)[200]').then(() => {
found = true;
});
await page.goto(server.EMPTY_PAGE);
expect(found).toBe(false);
await page.goto(server.PREFIX + '/grid.html');
await waitFor;
expect(found).toBe(true);
});
it('should not allow you to select an element with single slash xpath', async () => {
const { page } = getTestState();
await page.setContent(`<div>some text</div>`);
let error = null;
await page.waitFor('/html/body/div').catch((error_) => (error = error_));
expect(error).toBeTruthy();
});
it('should timeout', async () => {
const { page } = getTestState();
const startTime = Date.now();
const timeout = 42;
await page.waitFor(timeout);
expect(Date.now() - startTime).not.toBeLessThan(timeout / 2);
});
it('should work with multiline body', async () => {
const { page } = getTestState();
const result = await page.waitForFunction(`
(() => true)()
`);
expect(await result.jsonValue()).toBe(true);
});
it('should wait for predicate', async () => {
const { page } = getTestState();
await Promise.all([
page.waitFor(() => window.innerWidth < 100),
page.setViewport({ width: 10, height: 10 }),
]);
});
it('should throw when unknown type', async () => {
const { page } = getTestState();
let error = null;
// @ts-expect-error purposefully passing bad type for test
await page.waitFor({ foo: 'bar' }).catch((error_) => (error = error_));
expect(error.message).toContain('Unsupported target type');
});
it('should wait for predicate with arguments', async () => {
const { page } = getTestState();
await page.waitFor((arg1, arg2) => arg1 !== arg2, {}, 1, 2);
});
it('should log a deprecation warning', async () => {
const { page } = getTestState();
await page.waitFor(() => true);
const consoleWarnStub = console.warn as sinon.SinonSpy;
expect(consoleWarnStub.calledOnce).toBe(true);
expect(
consoleWarnStub.firstCall.calledWith(
'waitFor is deprecated and will be removed in a future release. See https://github.com/puppeteer/puppeteer/issues/6214 for details and how to migrate your code.'
)
).toBe(true);
expect((console.warn as sinon.SinonSpy).calledOnce).toBe(true);
});
});
describe('Frame.waitForFunction', function () {
it('should accept a string', async () => {
const { page } = getTestState();
const watchdog = page.waitForFunction('window.__FOO === 1');
await page.evaluate(() => (globalThis.__FOO = 1));
await watchdog;
});
it('should work when resolved right before execution context disposal', async () => {
const { page } = getTestState();
await page.evaluateOnNewDocument(() => (globalThis.__RELOADED = true));
await page.waitForFunction(() => {
if (!globalThis.__RELOADED) window.location.reload();
return true;
});
});
it('should poll on interval', async () => {
const { page } = getTestState();
let success = false;
const startTime = Date.now();
const polling = 100;
const watchdog = page
.waitForFunction(() => globalThis.__FOO === 'hit', { polling })
.then(() => (success = true));
await page.evaluate(() => (globalThis.__FOO = 'hit'));
expect(success).toBe(false);
await page.evaluate(() =>
document.body.appendChild(document.createElement('div'))
);
await watchdog;
expect(Date.now() - startTime).not.toBeLessThan(polling / 2);
});
it('should poll on interval async', async () => {
const { page } = getTestState();
let success = false;
const startTime = Date.now();
const polling = 100;
const watchdog = page
.waitForFunction(async () => globalThis.__FOO === 'hit', { polling })
.then(() => (success = true));
await page.evaluate(async () => (globalThis.__FOO = 'hit'));
expect(success).toBe(false);
await page.evaluate(async () =>
document.body.appendChild(document.createElement('div'))
);
await watchdog;
expect(Date.now() - startTime).not.toBeLessThan(polling / 2);
});
it('should poll on mutation', async () => {
const { page } = getTestState();
let success = false;
const watchdog = page
.waitForFunction(() => globalThis.__FOO === 'hit', {
polling: 'mutation',
})
.then(() => (success = true));
await page.evaluate(() => (globalThis.__FOO = 'hit'));
expect(success).toBe(false);
await page.evaluate(() =>
document.body.appendChild(document.createElement('div'))
);
await watchdog;
});
it('should poll on mutation async', async () => {
const { page } = getTestState();
let success = false;
const watchdog = page
.waitForFunction(async () => globalThis.__FOO === 'hit', {
polling: 'mutation',
})
.then(() => (success = true));
await page.evaluate(async () => (globalThis.__FOO = 'hit'));
expect(success).toBe(false);
await page.evaluate(async () =>
document.body.appendChild(document.createElement('div'))
);
await watchdog;
});
it('should poll on raf', async () => {
const { page } = getTestState();
const watchdog = page.waitForFunction(() => globalThis.__FOO === 'hit', {
polling: 'raf',
});
await page.evaluate(() => (globalThis.__FOO = 'hit'));
await watchdog;
});
it('should poll on raf async', async () => {
const { page } = getTestState();
const watchdog = page.waitForFunction(
async () => globalThis.__FOO === 'hit',
{
polling: 'raf',
}
);
await page.evaluate(async () => (globalThis.__FOO = 'hit'));
await watchdog;
});
itFailsFirefox('should work with strict CSP policy', async () => {
const { page, server } = getTestState();
server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.goto(server.EMPTY_PAGE);
let error = null;
await Promise.all([
page
.waitForFunction(() => globalThis.__FOO === 'hit', { polling: 'raf' })
.catch((error_) => (error = error_)),
page.evaluate(() => (globalThis.__FOO = 'hit')),
]);
expect(error).toBe(null);
});
it('should throw on bad polling value', async () => {
const { page } = getTestState();
let error = null;
try {
await page.waitForFunction(() => !!document.body, {
polling: 'unknown',
});
} catch (error_) {
error = error_;
}
expect(error).toBeTruthy();
expect(error.message).toContain('polling');
});
it('should throw negative polling interval', async () => {
const { page } = getTestState();
let error = null;
try {
await page.waitForFunction(() => !!document.body, { polling: -10 });
} catch (error_) {
error = error_;
}
expect(error).toBeTruthy();
expect(error.message).toContain('Cannot poll with non-positive interval');
});
it('should return the success value as a JSHandle', async () => {
const { page } = getTestState();
expect(await (await page.waitForFunction(() => 5)).jsonValue()).toBe(5);
});
it('should return the window as a success value', async () => {
const { page } = getTestState();
expect(await page.waitForFunction(() => window)).toBeTruthy();
});
it('should accept ElementHandle arguments', async () => {
const { page } = getTestState();
await page.setContent('<div></div>');
const div = await page.$('div');
let resolved = false;
const waitForFunction = page
.waitForFunction((element) => !element.parentElement, {}, div)
.then(() => (resolved = true));
expect(resolved).toBe(false);
await page.evaluate((element: HTMLElement) => element.remove(), div);
await waitForFunction;
});
it('should respect timeout', async () => {
const { page, puppeteer } = getTestState();
let error = null;
await page
.waitForFunction('false', { timeout: 10 })
.catch((error_) => (error = error_));
expect(error).toBeTruthy();
expect(error.message).toContain('waiting for function failed: timeout');
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
});
it('should respect default timeout', async () => {
const { page, puppeteer } = getTestState();
page.setDefaultTimeout(1);
let error = null;
await page.waitForFunction('false').catch((error_) => (error = error_));
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
expect(error.message).toContain('waiting for function failed: timeout');
});
it('should disable timeout when its set to 0', async () => {
const { page } = getTestState();
const watchdog = page.waitForFunction(
() => {
globalThis.__counter = (globalThis.__counter || 0) + 1;
return globalThis.__injected;
},
{ timeout: 0, polling: 10 }
);
await page.waitForFunction(() => globalThis.__counter > 10);
await page.evaluate(() => (globalThis.__injected = true));
await watchdog;
});
it('should survive cross-process navigation', async () => {
const { page, server } = getTestState();
let fooFound = false;
const waitForFunction = page
.waitForFunction('globalThis.__FOO === 1')
.then(() => (fooFound = true));
await page.goto(server.EMPTY_PAGE);
expect(fooFound).toBe(false);
await page.reload();
expect(fooFound).toBe(false);
await page.goto(server.CROSS_PROCESS_PREFIX + '/grid.html');
expect(fooFound).toBe(false);
await page.evaluate(() => (globalThis.__FOO = 1));
await waitForFunction;
expect(fooFound).toBe(true);
});
it('should survive navigations', async () => {
const { page, server } = getTestState();
const watchdog = page.waitForFunction(() => globalThis.__done);
await page.goto(server.EMPTY_PAGE);
await page.goto(server.PREFIX + '/consolelog.html');
await page.evaluate(() => (globalThis.__done = true));
await watchdog;
});
});
describe('Page.waitForTimeout', () => {
it('waits for the given timeout before resolving', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
const startTime = Date.now();
await page.waitForTimeout(1000);
const endTime = Date.now();
/* In a perfect world endTime - startTime would be exactly 1000 but we
* expect some fluctuations and for it to be off by a little bit. So to
* avoid a flaky test we'll make sure it waited for roughly 1 second.
*/
expect(endTime - startTime).toBeGreaterThan(700);
expect(endTime - startTime).toBeLessThan(1300);
});
});
describe('Frame.waitForTimeout', () => {
it('waits for the given timeout before resolving', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
const frame = page.mainFrame();
const startTime = Date.now();
await frame.waitForTimeout(1000);
const endTime = Date.now();
/* In a perfect world endTime - startTime would be exactly 1000 but we
* expect some fluctuations and for it to be off by a little bit. So to
* avoid a flaky test we'll make sure it waited for roughly 1 second
*/
expect(endTime - startTime).toBeGreaterThan(700);
expect(endTime - startTime).toBeLessThan(1300);
});
});
describe('Frame.waitForSelector', function () {
const addElement = (tag) =>
document.body.appendChild(document.createElement(tag));
it('should immediately resolve promise if node exists', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
const frame = page.mainFrame();
await frame.waitForSelector('*');
await frame.evaluate(addElement, 'div');
await frame.waitForSelector('div');
});
itFailsFirefox('should work with removed MutationObserver', async () => {
const { page } = getTestState();
await page.evaluate(() => delete window.MutationObserver);
const [handle] = await Promise.all([
page.waitForSelector('.zombo'),
page.setContent(`<div class='zombo'>anything</div>`),
]);
expect(
await page.evaluate((x: HTMLElement) => x.textContent, handle)
).toBe('anything');
});
it('should resolve promise when node is added', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
const frame = page.mainFrame();
const watchdog = frame.waitForSelector('div');
await frame.evaluate(addElement, 'br');
await frame.evaluate(addElement, 'div');
const eHandle = await watchdog;
const tagName = await eHandle
.getProperty('tagName')
.then((e) => e.jsonValue());
expect(tagName).toBe('DIV');
});
it('should work when node is added through innerHTML', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
const watchdog = page.waitForSelector('h3 div');
await page.evaluate(addElement, 'span');
await page.evaluate(
() =>
(document.querySelector('span').innerHTML = '<h3><div></div></h3>')
);
await watchdog;
});
itFailsFirefox(
'Page.waitForSelector is shortcut for main frame',
async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const otherFrame = page.frames()[1];
const watchdog = page.waitForSelector('div');
await otherFrame.evaluate(addElement, 'div');
await page.evaluate(addElement, 'div');
const eHandle = await watchdog;
expect(eHandle.executionContext().frame()).toBe(page.mainFrame());
}
);
itFailsFirefox('should run in specified frame', async () => {
const { page, server } = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
const frame1 = page.frames()[1];
const frame2 = page.frames()[2];
const waitForSelectorPromise = frame2.waitForSelector('div');
await frame1.evaluate(addElement, 'div');
await frame2.evaluate(addElement, 'div');
const eHandle = await waitForSelectorPromise;
expect(eHandle.executionContext().frame()).toBe(frame2);
});
itFailsFirefox('should throw when frame is detached', async () => {
const { page, server } = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
let waitError = null;
const waitPromise = frame
.waitForSelector('.box')
.catch((error) => (waitError = error));
await utils.detachFrame(page, 'frame1');
await waitPromise;
expect(waitError).toBeTruthy();
expect(waitError.message).toContain(
'waitForFunction failed: frame got detached.'
);
});
it('should survive cross-process navigation', async () => {
const { page, server } = getTestState();
let boxFound = false;
const waitForSelector = page
.waitForSelector('.box')
.then(() => (boxFound = true));
await page.goto(server.EMPTY_PAGE);
expect(boxFound).toBe(false);
await page.reload();
expect(boxFound).toBe(false);
await page.goto(server.CROSS_PROCESS_PREFIX + '/grid.html');
await waitForSelector;
expect(boxFound).toBe(true);
});
it('should wait for visible', async () => {
const { page } = getTestState();
let divFound = false;
const waitForSelector = page
.waitForSelector('div', { visible: true })
.then(() => (divFound = true));
await page.setContent(
`<div style='display: none; visibility: hidden;'>1</div>`
);
expect(divFound).toBe(false);
await page.evaluate(() =>
document.querySelector('div').style.removeProperty('display')
);
expect(divFound).toBe(false);
await page.evaluate(() =>
document.querySelector('div').style.removeProperty('visibility')
);
expect(await waitForSelector).toBe(true);
expect(divFound).toBe(true);
});
it('should wait for visible recursively', async () => {
const { page } = getTestState();
let divVisible = false;
const waitForSelector = page
.waitForSelector('div#inner', { visible: true })
.then(() => (divVisible = true));
await page.setContent(
`<div style='display: none; visibility: hidden;'><div id="inner">hi</div></div>`
);
expect(divVisible).toBe(false);
await page.evaluate(() =>
document.querySelector('div').style.removeProperty('display')
);
expect(divVisible).toBe(false);
await page.evaluate(() =>
document.querySelector('div').style.removeProperty('visibility')
);
expect(await waitForSelector).toBe(true);
expect(divVisible).toBe(true);
});
it('hidden should wait for visibility: hidden', async () => {
const { page } = getTestState();
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForSelector = page
.waitForSelector('div', { hidden: true })
.then(() => (divHidden = true));
await page.waitForSelector('div'); // do a round trip
expect(divHidden).toBe(false);
await page.evaluate(() =>
document.querySelector('div').style.setProperty('visibility', 'hidden')
);
expect(await waitForSelector).toBe(true);
expect(divHidden).toBe(true);
});
it('hidden should wait for display: none', async () => {
const { page } = getTestState();
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForSelector = page
.waitForSelector('div', { hidden: true })
.then(() => (divHidden = true));
await page.waitForSelector('div'); // do a round trip
expect(divHidden).toBe(false);
await page.evaluate(() =>
document.querySelector('div').style.setProperty('display', 'none')
);
expect(await waitForSelector).toBe(true);
expect(divHidden).toBe(true);
});
it('hidden should wait for removal', async () => {
const { page } = getTestState();
await page.setContent(`<div></div>`);
let divRemoved = false;
const waitForSelector = page
.waitForSelector('div', { hidden: true })
.then(() => (divRemoved = true));
await page.waitForSelector('div'); // do a round trip
expect(divRemoved).toBe(false);
await page.evaluate(() => document.querySelector('div').remove());
expect(await waitForSelector).toBe(true);
expect(divRemoved).toBe(true);
});
it('should return null if waiting to hide non-existing element', async () => {
const { page } = getTestState();
const handle = await page.waitForSelector('non-existing', {
hidden: true,
});
expect(handle).toBe(null);
});
it('should respect timeout', async () => {
const { page, puppeteer } = getTestState();
let error = null;
await page
.waitForSelector('div', { timeout: 10 })
.catch((error_) => (error = error_));
expect(error).toBeTruthy();
expect(error.message).toContain(
'waiting for selector `div` failed: timeout'
);
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
});
it('should have an error message specifically for awaiting an element to be hidden', async () => {
const { page } = getTestState();
await page.setContent(`<div></div>`);
let error = null;
await page
.waitForSelector('div', { hidden: true, timeout: 10 })
.catch((error_) => (error = error_));
expect(error).toBeTruthy();
expect(error.message).toContain(
'waiting for selector `div` to be hidden failed: timeout'
);
});
it('should respond to node attribute mutation', async () => {
const { page } = getTestState();
let divFound = false;
const waitForSelector = page
.waitForSelector('.zombo')
.then(() => (divFound = true));
await page.setContent(`<div class='notZombo'></div>`);
expect(divFound).toBe(false);
await page.evaluate(
() => (document.querySelector('div').className = 'zombo')
);
expect(await waitForSelector).toBe(true);
});
it('should return the element handle', async () => {
const { page } = getTestState();
const waitForSelector = page.waitForSelector('.zombo');
await page.setContent(`<div class='zombo'>anything</div>`);
expect(
await page.evaluate(
(x: HTMLElement) => x.textContent,
await waitForSelector
)
).toBe('anything');
});
it('should have correct stack trace for timeout', async () => {
const { page } = getTestState();
let error;
await page
.waitForSelector('.zombo', { timeout: 10 })
.catch((error_) => (error = error_));
expect(error.stack).toContain('waiting for selector `.zombo` failed');
// The extension is ts here as Mocha maps back via sourcemaps.
expect(error.stack).toContain('waittask.spec.ts');
});
});
describe('Frame.waitForXPath', function () {
const addElement = (tag) =>
document.body.appendChild(document.createElement(tag));
it('should support some fancy xpath', async () => {
const { page } = getTestState();
await page.setContent(`<p>red herring</p><p>hello world </p>`);
const waitForXPath = page.waitForXPath(
'//p[normalize-space(.)="hello world"]'
);
expect(
await page.evaluate(
(x: HTMLElement) => x.textContent,
await waitForXPath
)
).toBe('hello world ');
});
it('should respect timeout', async () => {
const { page, puppeteer } = getTestState();
let error = null;
await page
.waitForXPath('//div', { timeout: 10 })
.catch((error_) => (error = error_));
expect(error).toBeTruthy();
expect(error.message).toContain(
'waiting for XPath `//div` failed: timeout'
);
expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
});
itFailsFirefox('should run in specified frame', async () => {
const { page, server } = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
const frame1 = page.frames()[1];
const frame2 = page.frames()[2];
const waitForXPathPromise = frame2.waitForXPath('//div');
await frame1.evaluate(addElement, 'div');
await frame2.evaluate(addElement, 'div');
const eHandle = await waitForXPathPromise;
expect(eHandle.executionContext().frame()).toBe(frame2);
});
itFailsFirefox('should throw when frame is detached', async () => {
const { page, server } = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
let waitError = null;
const waitPromise = frame
.waitForXPath('//*[@class="box"]')
.catch((error) => (waitError = error));
await utils.detachFrame(page, 'frame1');
await waitPromise;
expect(waitError).toBeTruthy();
expect(waitError.message).toContain(
'waitForFunction failed: frame got detached.'
);
});
it('hidden should wait for display: none', async () => {
const { page } = getTestState();
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForXPath = page
.waitForXPath('//div', { hidden: true })
.then(() => (divHidden = true));
await page.waitForXPath('//div'); // do a round trip
expect(divHidden).toBe(false);
await page.evaluate(() =>
document.querySelector('div').style.setProperty('display', 'none')
);
expect(await waitForXPath).toBe(true);
expect(divHidden).toBe(true);
});
it('should return the element handle', async () => {
const { page } = getTestState();
const waitForXPath = page.waitForXPath('//*[@class="zombo"]');
await page.setContent(`<div class='zombo'>anything</div>`);
expect(
await page.evaluate(
(x: HTMLElement) => x.textContent,
await waitForXPath
)
).toBe('anything');
});
it('should allow you to select a text node', async () => {
const { page } = getTestState();
await page.setContent(`<div>some text</div>`);
const text = await page.waitForXPath('//div/text()');
expect(await (await text.getProperty('nodeType')).jsonValue()).toBe(
3 /* Node.TEXT_NODE */
);
});
it('should allow you to select an element with single slash', async () => {
const { page } = getTestState();
await page.setContent(`<div>some text</div>`);
const waitForXPath = page.waitForXPath('/html/body/div');
expect(
await page.evaluate(
(x: HTMLElement) => x.textContent,
await waitForXPath
)
).toBe('some text');
});
});
}); | the_stack |
import * as React from 'react';
import * as Utils from '../lib/Utils';
import RecurringRunList, { RecurringRunListProps } from './RecurringRunList';
import TestUtils from '../TestUtils';
import produce from 'immer';
import { ApiJob, ApiResourceType } from '../apis/job';
import { Apis, JobSortKeys, ListRequest } from '../lib/Apis';
import { ReactWrapper, ShallowWrapper, shallow } from 'enzyme';
import { range } from 'lodash';
class RecurringRunListTest extends RecurringRunList {
public _loadRecurringRuns(request: ListRequest): Promise<string> {
return super._loadRecurringRuns(request);
}
}
describe('RecurringRunList', () => {
let tree: ShallowWrapper | ReactWrapper;
const onErrorSpy = jest.fn();
const listJobsSpy = jest.spyOn(Apis.jobServiceApi, 'listJobs');
const getJobSpy = jest.spyOn(Apis.jobServiceApi, 'getJob');
const getExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'getExperiment');
// We mock this because it uses toLocaleDateString, which causes mismatches between local and CI
// test environments
const formatDateStringSpy = jest.spyOn(Utils, 'formatDateString');
function generateProps(): RecurringRunListProps {
return {
history: {} as any,
location: { search: '' } as any,
match: '' as any,
onError: onErrorSpy,
refreshCount: 1,
};
}
function mockNJobs(n: number, jobTemplate: Partial<ApiJob>): void {
getJobSpy.mockImplementation(id =>
Promise.resolve(
produce(jobTemplate, draft => {
draft.id = id;
draft.name = 'job with id: ' + id;
}),
),
);
listJobsSpy.mockImplementation(() =>
Promise.resolve({
jobs: range(1, n + 1).map(i => {
if (jobTemplate) {
return produce(jobTemplate as Partial<ApiJob>, draft => {
draft.id = 'testjob' + i;
draft.name = 'job with id: testjob' + i;
});
}
return {
id: 'testjob' + i,
name: 'job with id: testjob' + i,
} as ApiJob;
}),
}),
);
getExperimentSpy.mockImplementation(() => ({ name: 'some experiment' }));
}
function getMountedInstance(): RecurringRunList {
tree = TestUtils.mountWithRouter(<RecurringRunList {...generateProps()} />);
return tree.instance() as RecurringRunList;
}
beforeEach(() => {
formatDateStringSpy.mockImplementation((date?: Date) => {
return date ? '1/2/2019, 12:34:56 PM' : '-';
});
onErrorSpy.mockClear();
listJobsSpy.mockClear();
getJobSpy.mockClear();
getExperimentSpy.mockClear();
});
afterEach(async () => {
// unmount() should be called before resetAllMocks() in case any part of the unmount life cycle
// depends on mocks/spies
if (tree) {
await tree.unmount();
}
jest.resetAllMocks();
});
it('renders the empty experience', () => {
expect(shallow(<RecurringRunList {...generateProps()} />)).toMatchInlineSnapshot(`
<div>
<CustomTable
columns={
Array [
Object {
"customRenderer": [Function],
"flex": 1.5,
"label": "Recurring Run Name",
"sortKey": "name",
},
Object {
"customRenderer": [Function],
"flex": 0.5,
"label": "Status",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Trigger",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Experiment",
},
Object {
"flex": 1,
"label": "Created at",
"sortKey": "created_at",
},
]
}
emptyMessage="No available recurring runs found."
filterLabel="Filter recurring runs"
initialSortColumn="created_at"
reload={[Function]}
rows={Array []}
/>
</div>
`);
});
it('loads one job', async () => {
mockNJobs(1, {});
const props = generateProps();
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(Apis.jobServiceApi.listJobs).toHaveBeenLastCalledWith(
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
);
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchInlineSnapshot(`
<div>
<CustomTable
columns={
Array [
Object {
"customRenderer": [Function],
"flex": 1.5,
"label": "Recurring Run Name",
"sortKey": "name",
},
Object {
"customRenderer": [Function],
"flex": 0.5,
"label": "Status",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Trigger",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Experiment",
},
Object {
"flex": 1,
"label": "Created at",
"sortKey": "created_at",
},
]
}
emptyMessage="No available recurring runs found."
filterLabel="Filter recurring runs"
initialSortColumn="created_at"
reload={[Function]}
rows={
Array [
Object {
"error": undefined,
"id": "testjob1",
"otherFields": Array [
"job with id: testjob1",
undefined,
undefined,
undefined,
"-",
],
},
]
}
/>
</div>
`);
});
it('reloads the job when refresh is called', async () => {
mockNJobs(0, {});
const props = generateProps();
tree = TestUtils.mountWithRouter(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunList).refresh();
tree.update();
expect(Apis.jobServiceApi.listJobs).toHaveBeenCalledTimes(2);
expect(Apis.jobServiceApi.listJobs).toHaveBeenLastCalledWith(
'',
10,
JobSortKeys.CREATED_AT + ' desc',
undefined,
undefined,
'',
);
expect(props.onError).not.toHaveBeenCalled();
});
it('loads multiple jobs', async () => {
mockNJobs(5, {});
const props = generateProps();
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchInlineSnapshot(`
<div>
<CustomTable
columns={
Array [
Object {
"customRenderer": [Function],
"flex": 1.5,
"label": "Recurring Run Name",
"sortKey": "name",
},
Object {
"customRenderer": [Function],
"flex": 0.5,
"label": "Status",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Trigger",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Experiment",
},
Object {
"flex": 1,
"label": "Created at",
"sortKey": "created_at",
},
]
}
emptyMessage="No available recurring runs found."
filterLabel="Filter recurring runs"
initialSortColumn="created_at"
reload={[Function]}
rows={
Array [
Object {
"error": undefined,
"id": "testjob1",
"otherFields": Array [
"job with id: testjob1",
undefined,
undefined,
undefined,
"-",
],
},
Object {
"error": undefined,
"id": "testjob2",
"otherFields": Array [
"job with id: testjob2",
undefined,
undefined,
undefined,
"-",
],
},
Object {
"error": undefined,
"id": "testjob3",
"otherFields": Array [
"job with id: testjob3",
undefined,
undefined,
undefined,
"-",
],
},
Object {
"error": undefined,
"id": "testjob4",
"otherFields": Array [
"job with id: testjob4",
undefined,
undefined,
undefined,
"-",
],
},
Object {
"error": undefined,
"id": "testjob5",
"otherFields": Array [
"job with id: testjob5",
undefined,
undefined,
undefined,
"-",
],
},
]
}
/>
</div>
`);
});
it('calls error callback when loading jobs fails', async () => {
TestUtils.makeErrorResponseOnce(
jest.spyOn(Apis.jobServiceApi, 'listJobs'),
'bad stuff happened',
);
const props = generateProps();
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).toHaveBeenLastCalledWith(
'Error: failed to fetch recurring runs.',
new Error('bad stuff happened'),
);
});
it('loads jobs for a given experiment id', async () => {
mockNJobs(1, {});
const props = generateProps();
props.experimentIdMask = 'experiment1';
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(Apis.jobServiceApi.listJobs).toHaveBeenLastCalledWith(
undefined,
undefined,
undefined,
'EXPERIMENT',
'experiment1',
undefined,
);
});
it('loads jobs for a given namespace', async () => {
mockNJobs(1, {});
const props = generateProps();
props.namespaceMask = 'namespace1';
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(Apis.jobServiceApi.listJobs).toHaveBeenLastCalledWith(
undefined,
undefined,
undefined,
'NAMESPACE',
'namespace1',
undefined,
);
});
it('loads given list of jobs only', async () => {
mockNJobs(5, {});
const props = generateProps();
props.recurringRunIdListMask = ['job1', 'job2'];
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(Apis.jobServiceApi.listJobs).not.toHaveBeenCalled();
expect(Apis.jobServiceApi.getJob).toHaveBeenCalledTimes(2);
expect(Apis.jobServiceApi.getJob).toHaveBeenCalledWith('job1');
expect(Apis.jobServiceApi.getJob).toHaveBeenCalledWith('job2');
});
it('shows job status', async () => {
mockNJobs(1, {
status: 'ENABLED',
});
const props = generateProps();
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchInlineSnapshot(`
<div>
<CustomTable
columns={
Array [
Object {
"customRenderer": [Function],
"flex": 1.5,
"label": "Recurring Run Name",
"sortKey": "name",
},
Object {
"customRenderer": [Function],
"flex": 0.5,
"label": "Status",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Trigger",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Experiment",
},
Object {
"flex": 1,
"label": "Created at",
"sortKey": "created_at",
},
]
}
emptyMessage="No available recurring runs found."
filterLabel="Filter recurring runs"
initialSortColumn="created_at"
reload={[Function]}
rows={
Array [
Object {
"error": undefined,
"id": "testjob1",
"otherFields": Array [
"job with id: testjob1",
"ENABLED",
undefined,
undefined,
"-",
],
},
]
}
/>
</div>
`);
});
it('shows trigger periodic', async () => {
mockNJobs(1, {
trigger: { periodic_schedule: { interval_second: '3600' } },
});
const props = generateProps();
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchInlineSnapshot(`
<div>
<CustomTable
columns={
Array [
Object {
"customRenderer": [Function],
"flex": 1.5,
"label": "Recurring Run Name",
"sortKey": "name",
},
Object {
"customRenderer": [Function],
"flex": 0.5,
"label": "Status",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Trigger",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Experiment",
},
Object {
"flex": 1,
"label": "Created at",
"sortKey": "created_at",
},
]
}
emptyMessage="No available recurring runs found."
filterLabel="Filter recurring runs"
initialSortColumn="created_at"
reload={[Function]}
rows={
Array [
Object {
"error": undefined,
"id": "testjob1",
"otherFields": Array [
"job with id: testjob1",
undefined,
Object {
"periodic_schedule": Object {
"interval_second": "3600",
},
},
undefined,
"-",
],
},
]
}
/>
</div>
`);
});
it('shows trigger cron', async () => {
mockNJobs(1, {
trigger: { cron_schedule: { cron: '0 * * * * ?' } },
});
const props = generateProps();
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchInlineSnapshot(`
<div>
<CustomTable
columns={
Array [
Object {
"customRenderer": [Function],
"flex": 1.5,
"label": "Recurring Run Name",
"sortKey": "name",
},
Object {
"customRenderer": [Function],
"flex": 0.5,
"label": "Status",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Trigger",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Experiment",
},
Object {
"flex": 1,
"label": "Created at",
"sortKey": "created_at",
},
]
}
emptyMessage="No available recurring runs found."
filterLabel="Filter recurring runs"
initialSortColumn="created_at"
reload={[Function]}
rows={
Array [
Object {
"error": undefined,
"id": "testjob1",
"otherFields": Array [
"job with id: testjob1",
undefined,
Object {
"cron_schedule": Object {
"cron": "0 * * * * ?",
},
},
undefined,
"-",
],
},
]
}
/>
</div>
`);
});
it('shows experiment name', async () => {
mockNJobs(1, {
resource_references: [
{
key: { id: 'test-experiment-id', type: ApiResourceType.EXPERIMENT },
},
],
});
getExperimentSpy.mockImplementationOnce(() => ({ name: 'test experiment' }));
const props = generateProps();
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchInlineSnapshot(`
<div>
<CustomTable
columns={
Array [
Object {
"customRenderer": [Function],
"flex": 1.5,
"label": "Recurring Run Name",
"sortKey": "name",
},
Object {
"customRenderer": [Function],
"flex": 0.5,
"label": "Status",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Trigger",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Experiment",
},
Object {
"flex": 1,
"label": "Created at",
"sortKey": "created_at",
},
]
}
emptyMessage="No available recurring runs found."
filterLabel="Filter recurring runs"
initialSortColumn="created_at"
reload={[Function]}
rows={
Array [
Object {
"error": undefined,
"id": "testjob1",
"otherFields": Array [
"job with id: testjob1",
undefined,
undefined,
Object {
"displayName": "test experiment",
"id": "test-experiment-id",
},
"-",
],
},
]
}
/>
</div>
`);
});
it('hides experiment name if instructed', async () => {
mockNJobs(1, {
resource_references: [
{
key: { id: 'test-experiment-id', type: ApiResourceType.EXPERIMENT },
},
],
});
getExperimentSpy.mockImplementationOnce(() => ({ name: 'test experiment' }));
const props = generateProps();
props.hideExperimentColumn = true;
tree = shallow(<RecurringRunList {...props} />);
await (tree.instance() as RecurringRunListTest)._loadRecurringRuns({});
expect(props.onError).not.toHaveBeenCalled();
expect(tree).toMatchInlineSnapshot(`
<div>
<CustomTable
columns={
Array [
Object {
"customRenderer": [Function],
"flex": 1.5,
"label": "Recurring Run Name",
"sortKey": "name",
},
Object {
"customRenderer": [Function],
"flex": 0.5,
"label": "Status",
},
Object {
"customRenderer": [Function],
"flex": 1,
"label": "Trigger",
},
Object {
"flex": 1,
"label": "Created at",
"sortKey": "created_at",
},
]
}
emptyMessage="No available recurring runs found."
filterLabel="Filter recurring runs"
initialSortColumn="created_at"
reload={[Function]}
rows={
Array [
Object {
"error": undefined,
"id": "testjob1",
"otherFields": Array [
"job with id: testjob1",
undefined,
undefined,
"-",
],
},
]
}
/>
</div>
`);
});
it('renders job trigger in seconds', () => {
expect(
getMountedInstance()._triggerCustomRenderer({
value: { periodic_schedule: { interval_second: '42' } },
id: 'job-id',
}),
).toMatchInlineSnapshot(`
<div>
Every
42
seconds
</div>
`);
});
it('renders job trigger in minutes', () => {
expect(
getMountedInstance()._triggerCustomRenderer({
value: { periodic_schedule: { interval_second: '120' } },
id: 'job-id',
}),
).toMatchInlineSnapshot(`
<div>
Every
2
minutes
</div>
`);
});
it('renders job trigger in hours', () => {
expect(
getMountedInstance()._triggerCustomRenderer({
value: { periodic_schedule: { interval_second: '7200' } },
id: 'job-id',
}),
).toMatchInlineSnapshot(`
<div>
Every
2
hours
</div>
`);
});
it('renders job trigger in days', () => {
expect(
getMountedInstance()._triggerCustomRenderer({
value: { periodic_schedule: { interval_second: '86400' } },
id: 'job-id',
}),
).toMatchInlineSnapshot(`
<div>
Every
1
days
</div>
`);
});
it('renders job trigger as cron', () => {
expect(
getMountedInstance()._triggerCustomRenderer({
value: { cron_schedule: { cron: '0 * * * * ?' } },
id: 'job-id',
}),
).toMatchInlineSnapshot(`
<div>
Cron:
0 * * * * ?
</div>
`);
});
it('renders status enabled', () => {
expect(
getMountedInstance()._statusCustomRenderer({
value: 'Enabled',
id: 'job-id',
}),
).toMatchInlineSnapshot(`
<div
style={
Object {
"color": "#34a853",
}
}
>
Enabled
</div>
`);
});
it('renders status disabled', () => {
expect(
getMountedInstance()._statusCustomRenderer({
value: 'Disabled',
id: 'job-id',
}),
).toMatchInlineSnapshot(`
<div
style={
Object {
"color": "#5f6368",
}
}
>
Disabled
</div>
`);
});
it('renders status unknown', () => {
expect(
getMountedInstance()._statusCustomRenderer({
value: 'Unknown Status',
id: 'job-id',
}),
).toMatchInlineSnapshot(`
<div
style={
Object {
"color": "#d50000",
}
}
>
Unknown Status
</div>
`);
});
}); | the_stack |
import { loadScript } from '../lib/load-script';
export interface ReadyToPayChangeResponse {
isButtonVisible: boolean;
isReadyToPay: boolean;
paymentMethodPresent?: boolean;
}
export interface Config {
environment: google.payments.api.Environment;
existingPaymentMethodRequired?: boolean;
paymentRequest: google.payments.api.PaymentDataRequest;
onPaymentDataChanged?: google.payments.api.PaymentDataChangedHandler;
onPaymentAuthorized?: google.payments.api.PaymentAuthorizedHandler;
onLoadPaymentData?: (paymentData: google.payments.api.PaymentData) => void;
onCancel?: (reason: google.payments.api.PaymentsError) => void;
onError?: (error: Error | google.payments.api.PaymentsError) => void;
onReadyToPayChange?: (result: ReadyToPayChangeResponse) => void;
onClick?: (event: Event) => void;
buttonColor?: google.payments.api.ButtonColor;
buttonType?: google.payments.api.ButtonType;
buttonSizeMode?: google.payments.api.ButtonSizeMode;
buttonLocale?: string;
}
interface ButtonManagerOptions {
cssSelector: string;
softwareInfoId: string;
softwareInfoVersion: string;
}
/**
* Manages the lifecycle of the Google Pay button.
*
* Includes lifecycle management of the `PaymentsClient` instance,
* `isReadyToPay`, `onClick`, `loadPaymentData`, and other callback methods.
*/
export class ButtonManager {
private client?: google.payments.api.PaymentsClient;
private config?: Config;
private element?: Element;
private options: ButtonManagerOptions;
private oldInvalidationValues?: any[];
isReadyToPay?: boolean;
paymentMethodPresent?: boolean;
constructor(options: ButtonManagerOptions) {
this.options = options;
}
getElement(): Element | undefined {
return this.element;
}
private isGooglePayLoaded(): boolean {
return 'google' in (window || global) && !!google?.payments?.api?.PaymentsClient;
}
async mount(element: Element): Promise<void> {
if (!this.isGooglePayLoaded()) {
await loadScript('https://pay.google.com/gp/p/js/pay.js');
}
this.element = element;
if (element) {
this.appendStyles();
if (this.config) {
this.updateElement();
}
}
}
unmount(): void {
this.element = undefined;
}
configure(newConfig: Config): Promise<void> {
let promise: Promise<void> | undefined = undefined;
this.config = newConfig;
if (!this.oldInvalidationValues || this.isClientInvalidated(newConfig)) {
promise = this.updateElement();
}
this.oldInvalidationValues = this.getInvalidationValues(newConfig);
return promise ?? Promise.resolve();
}
/**
* Creates client configuration options based on button configuration
* options.
*
* This method would normally be private but has been made public for
* testing purposes.
*
* @private
*/
createClientOptions(config: Config): google.payments.api.PaymentOptions {
const clientConfig: google.payments.api.PaymentOptions = {
environment: config.environment,
merchantInfo: this.createMerchantInfo(config),
};
if (config.onPaymentDataChanged || config.onPaymentAuthorized) {
clientConfig.paymentDataCallbacks = {};
if (config.onPaymentDataChanged) {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
clientConfig.paymentDataCallbacks.onPaymentDataChanged = paymentData => {
const result = config.onPaymentDataChanged!(paymentData);
return result || ({} as google.payments.api.PaymentDataRequestUpdate);
};
}
if (config.onPaymentAuthorized) {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
clientConfig.paymentDataCallbacks.onPaymentAuthorized = paymentData => {
const result = config.onPaymentAuthorized!(paymentData);
return result || ({} as google.payments.api.PaymentAuthorizationResult);
};
}
}
return clientConfig;
}
private createIsReadyToPayRequest(config: Config): google.payments.api.IsReadyToPayRequest {
const paymentRequest = config.paymentRequest;
const request: google.payments.api.IsReadyToPayRequest = {
apiVersion: paymentRequest.apiVersion,
apiVersionMinor: paymentRequest.apiVersionMinor,
allowedPaymentMethods: paymentRequest.allowedPaymentMethods,
existingPaymentMethodRequired: config.existingPaymentMethodRequired,
};
return request;
}
/**
* Constructs `loadPaymentData` request object based on button configuration.
*
* It infers request properties like `shippingAddressRequired`,
* `shippingOptionRequired`, and `billingAddressRequired` if not already set
* based on the presence of their associated options and parameters. It also
* infers `callbackIntents` based on the callback methods defined in button
* configuration.
*
* This method would normally be private but has been made public for
* testing purposes.
*
* @private
*/
createLoadPaymentDataRequest(config: Config): google.payments.api.PaymentDataRequest {
const request = {
...config.paymentRequest,
merchantInfo: this.createMerchantInfo(config),
};
// TODO: #13 re-enable inferrence if/when we agree as a team
return request;
}
private createMerchantInfo(config: Config): google.payments.api.MerchantInfo {
const merchantInfo: google.payments.api.MerchantInfo = {
...config.paymentRequest.merchantInfo,
};
// apply softwareInfo if not set
if (!merchantInfo.softwareInfo) {
merchantInfo.softwareInfo = {
id: this.options.softwareInfoId,
version: this.options.softwareInfoVersion,
};
}
return merchantInfo;
}
private isMounted(): boolean {
return this.element != null && this.element.isConnected !== false;
}
private removeButton(): void {
if (this.element instanceof ShadowRoot || this.element instanceof Element) {
for (const child of Array.from(this.element.children)) {
if (child.tagName !== 'STYLE') {
child.remove();
}
}
}
}
private async updateElement(): Promise<void> {
if (!this.isMounted()) return;
const element = this.getElement()!;
if (!this.config) {
throw new Error('google-pay-button: Missing configuration');
}
// remove existing button
this.removeButton();
this.client = new google.payments.api.PaymentsClient(this.createClientOptions(this.config));
const buttonOptions: google.payments.api.ButtonOptions = {
buttonType: this.config.buttonType,
buttonColor: this.config.buttonColor,
buttonSizeMode: this.config.buttonSizeMode,
buttonLocale: this.config.buttonLocale,
onClick: this.handleClick,
allowedPaymentMethods: this.config.paymentRequest.allowedPaymentMethods,
};
const rootNode = element.getRootNode();
if (rootNode instanceof ShadowRoot) {
buttonOptions.buttonRootNode = rootNode;
}
// pre-create button
const button = this.client.createButton(buttonOptions);
this.setClassName(element, [element.className, 'not-ready']);
element.appendChild(button);
let showButton = false;
let readyToPay: google.payments.api.IsReadyToPayResponse | undefined;
try {
readyToPay = await this.client.isReadyToPay(this.createIsReadyToPayRequest(this.config));
showButton =
(readyToPay.result && !this.config.existingPaymentMethodRequired)
|| (readyToPay.result && readyToPay.paymentMethodPresent && this.config.existingPaymentMethodRequired)
|| false;
} catch (err) {
if (this.config.onError) {
this.config.onError(err as Error);
} else {
console.error(err);
}
}
if (!this.isMounted()) return;
if (showButton) {
try {
this.client.prefetchPaymentData(this.createLoadPaymentDataRequest(this.config));
} catch (err) {
console.log('Error with prefetch', err);
}
// remove hidden className
this.setClassName(
element,
(element.className || '').split(' ').filter(className => className && className !== 'not-ready'),
);
}
if (this.isReadyToPay !== readyToPay?.result || this.paymentMethodPresent !== readyToPay?.paymentMethodPresent) {
this.isReadyToPay = !!readyToPay?.result;
this.paymentMethodPresent = readyToPay?.paymentMethodPresent;
if (this.config.onReadyToPayChange) {
const readyToPayResponse: ReadyToPayChangeResponse = {
isButtonVisible: showButton,
isReadyToPay: this.isReadyToPay,
};
if (this.paymentMethodPresent) {
readyToPayResponse.paymentMethodPresent = this.paymentMethodPresent;
}
this.config.onReadyToPayChange(readyToPayResponse);
}
}
}
/**
* Handles the click event of the Google Pay button.
*
* This method would normally be private but has been made public for
* testing purposes.
*
* @private
*/
handleClick = async (event: Event): Promise<void> => {
const config = this.config;
if (!config) {
throw new Error('google-pay-button: Missing configuration');
}
const request = this.createLoadPaymentDataRequest(config);
try {
if (config.onClick) {
config.onClick(event);
}
if (event.defaultPrevented) {
return;
}
const result = await this.client!.loadPaymentData(request);
if (config.onLoadPaymentData) {
config.onLoadPaymentData(result);
}
} catch (err) {
if ((err as google.payments.api.PaymentsError).statusCode === 'CANCELED') {
if (config.onCancel) {
config.onCancel(err as google.payments.api.PaymentsError);
}
} else if (config.onError) {
config.onError(err as google.payments.api.PaymentsError);
} else {
console.error(err);
}
}
};
private setClassName(element: Element, classNames: string[]): void {
const className = classNames.filter(name => name).join(' ');
if (className) {
element.className = className;
} else {
element.removeAttribute('class');
}
}
private appendStyles(): void {
if (typeof document === 'undefined') return;
const rootNode = this.element?.getRootNode() as Document | ShadowRoot | undefined;
const styleId = `default-google-style-${this.options.cssSelector.replace(/[^\w-]+/g, '')}-${
this.config?.buttonLocale
}`;
// initialize styles if rendering on the client:
if (rootNode) {
if (!rootNode.getElementById?.(styleId)) {
const style = document.createElement('style');
style.id = styleId;
style.type = 'text/css';
style.innerHTML = `
${this.options.cssSelector} {
display: inline-block;
}
${this.options.cssSelector}.not-ready {
width: 0;
height: 0;
overflow: hidden;
}
`;
if (rootNode instanceof Document && rootNode.head) {
rootNode.head.appendChild(style);
} else {
rootNode.appendChild(style);
}
}
}
}
private isClientInvalidated(newConfig: Config): boolean {
if (!this.oldInvalidationValues) return true;
const newValues = this.getInvalidationValues(newConfig);
return newValues.some((value, index) => value !== this.oldInvalidationValues![index]);
}
private getInvalidationValues(config: Config): any[] {
return [
config.environment,
config.existingPaymentMethodRequired,
!!config.onPaymentDataChanged,
!!config.onPaymentAuthorized,
config.buttonColor,
config.buttonType,
config.buttonLocale,
config.buttonSizeMode,
config.paymentRequest.merchantInfo.merchantId,
config.paymentRequest.merchantInfo.merchantName,
config.paymentRequest.merchantInfo.softwareInfo?.id,
config.paymentRequest.merchantInfo.softwareInfo?.version,
config.paymentRequest.allowedPaymentMethods,
];
}
} | the_stack |
import { Convert } from "../ExtensionMethods";
import { DateTime } from "../DateTime";
import { EwsServiceJsonReader } from "../Core/EwsServiceJsonReader";
import { ExchangeService } from "../Core/ExchangeService";
import { ExtendedPropertyCollection } from "../ComplexProperties/ExtendedPropertyCollection";
import { FailedSearchMailbox } from "./FailedSearchMailbox";
import { Importance } from "../Enumerations/Importance";
import { ItemId } from "../ComplexProperties/ItemId";
import { KeywordStatisticsSearchResult } from "./KeywordStatisticsSearchResult";
import { MailboxQuery } from "./MailboxQuery";
import { MailboxSearchLocation } from "../Enumerations/MailboxSearchLocation";
import { MailboxSearchScope } from "./MailboxSearchScope";
import { MailboxStatisticsItem } from "./MailboxStatisticsItem";
import { PreviewItemMailbox } from "./PreviewItemMailbox";
import { SearchPreviewItem } from "./SearchPreviewItem";
import { SearchRefinerItem } from "./SearchRefinerItem";
import { SearchResultType } from "../Enumerations/SearchResultType";
import { XmlElementNames } from "../Core/XmlElementNames";
/**
* Represents search mailbox result.
*
* @sealed
*/
export class SearchMailboxesResult {
/**
* Search queries
*/
SearchQueries: MailboxQuery[] = null;
/**
* Result type
*/
ResultType: SearchResultType = SearchResultType.StatisticsOnly;
/**
* Item count
*/
ItemCount: number = 0;
/**
* Total size
* [CLSCompliant(false)]
*/
Size: number = 0;
/**
* Page item count
*/
PageItemCount: number = 0;
/**
* Total page item size
* [CLSCompliant(false)]
*/
PageItemSize: number = 0;
/**
* Keyword statistics search result
*/
KeywordStats: KeywordStatisticsSearchResult[] = null;
/**
* Search preview items
*/
PreviewItems: SearchPreviewItem[] = null;
/**
* Failed mailboxes
*/
FailedMailboxes: FailedSearchMailbox[] = null;
/**
* Refiners
*/
Refiners: SearchRefinerItem[] = null;
/**
* Mailbox statistics
*/
MailboxStats: MailboxStatisticsItem[] = null;
/**
* Get collection of recipients
*
* @param {any} jsObject Json Object converted from XML.
* @return {string[]} Array of recipients
*/
private static GetRecipients(jsObject: any): string[] {
let recipients: string[] = EwsServiceJsonReader.ReadAsArray(jsObject, XmlElementNames.SmtpAddress)
return recipients.length === 0 ? null : recipients;
}
/**
* Load extended properties from XML.
*
* @param {any} jsObject Json Object converted from XML.
* @param {ExchangeService} service The service.
* @return {ExtendedPropertyCollection} Extended properties collection
*/
private static LoadExtendedPropertiesXmlJsObject(jsObject: any, service: ExchangeService): ExtendedPropertyCollection {
let extendedProperties: ExtendedPropertyCollection = new ExtendedPropertyCollection();
for (let extendedProperty of EwsServiceJsonReader.ReadAsArray(jsObject, XmlElementNames.ExtendedProperty)) {
extendedProperties.LoadFromXmlJsObject(extendedProperty, service);
}
return extendedProperties.Count === 0 ? null : extendedProperties;
}
/**
* Loads service object from XML.
*
* @param {any} jsObject Json Object converted from XML.
* @param {ExchangeService} service The service.
* @return {SearchMailboxesResult} Search result object
*/
static LoadFromXmlJsObject(jsObject: any, service: ExchangeService): SearchMailboxesResult {
let searchResult: SearchMailboxesResult = new SearchMailboxesResult();
if (jsObject[XmlElementNames.SearchQueries]) {
searchResult.SearchQueries = [];
for (let searchQuery of EwsServiceJsonReader.ReadAsArray(jsObject[XmlElementNames.SearchQueries], XmlElementNames.SearchQuery)) {
let query: string = searchQuery[XmlElementNames.Query];
let mailboxSearchScopes: MailboxSearchScope[] = [];
if (searchQuery[XmlElementNames.MailboxSearchScopes]) {
for (let mailboxSearchScope of EwsServiceJsonReader.ReadAsArray(searchQuery[XmlElementNames.MailboxSearchScopes], XmlElementNames.MailboxSearchScope)) {
let mailbox: string = mailboxSearchScope[XmlElementNames.Mailbox];
let searchScope: MailboxSearchLocation = MailboxSearchLocation[<string>mailboxSearchScope[XmlElementNames.SearchScope]];
mailboxSearchScopes.push(new MailboxSearchScope(mailbox, searchScope));
}
}
searchResult.SearchQueries.push(new MailboxQuery(query, mailboxSearchScopes));
}
}
if (jsObject[XmlElementNames.ResultType]) {
searchResult.ResultType = SearchResultType[<string>jsObject[XmlElementNames.ResultType]]
}
if (jsObject[XmlElementNames.ItemCount]) {
searchResult.ItemCount = Convert.toNumber(jsObject[XmlElementNames.ItemCount]);
}
if (jsObject[XmlElementNames.Size]) {
searchResult.Size = Convert.toNumber(jsObject[XmlElementNames.Size]);
}
if (jsObject[XmlElementNames.PageItemCount]) {
searchResult.PageItemCount = Convert.toNumber(jsObject[XmlElementNames.PageItemCount]);
}
if (jsObject[XmlElementNames.PageItemSize]) {
searchResult.PageItemSize = Convert.toNumber(jsObject[XmlElementNames.PageItemSize]);
}
if (jsObject[XmlElementNames.KeywordStats]) {
searchResult.KeywordStats = this.LoadKeywordStatsXmlJsObject(jsObject[XmlElementNames.KeywordStats]);
}
if (jsObject[XmlElementNames.Items]) {
searchResult.PreviewItems = this.LoadPreviewItemsXmlJsObject(jsObject[XmlElementNames.Items], service);
}
if (jsObject[XmlElementNames.FailedMailboxes]) {
searchResult.FailedMailboxes = FailedSearchMailbox.LoadFromXmlJsObject(jsObject[XmlElementNames.FailedMailboxes], service);
}
if (jsObject[XmlElementNames.Refiners]) {
let refiners: SearchRefinerItem[] = [];
for (let refiner of EwsServiceJsonReader.ReadAsArray(jsObject[XmlElementNames.Refiners], XmlElementNames.Refiner)) {
refiners.push(SearchRefinerItem.LoadFromXmlJsObject(refiner, service));
}
if (refiners.length > 0) {
searchResult.Refiners = refiners;
}
}
if (jsObject[XmlElementNames.MailboxStats]) {
let mailboxStats: MailboxStatisticsItem[] = [];
for (let mailboxStat of EwsServiceJsonReader.ReadAsArray(jsObject[XmlElementNames.MailboxStats], XmlElementNames.MailboxStat)) {
mailboxStats.push(MailboxStatisticsItem.LoadFromXmlJsObject(mailboxStat, service));
}
if (mailboxStats.length > 0) {
searchResult.MailboxStats = mailboxStats;
}
}
return searchResult;
}
/**
* Load keyword stats from XML.
*
* @param {any} jsObject Json Object converted from XML.
* @return {KeywordStatisticsSearchResult[]} Array of keyword statistics
*/
private static LoadKeywordStatsXmlJsObject(jsObject: any): KeywordStatisticsSearchResult[] {
let keywordStats: KeywordStatisticsSearchResult[] = [];
for (let keywordStatObj of EwsServiceJsonReader.ReadAsArray(jsObject, XmlElementNames.KeywordStat)) {
let keywordStat: KeywordStatisticsSearchResult = new KeywordStatisticsSearchResult();
keywordStat.Keyword = jsObject[XmlElementNames.Keyword];
keywordStat.ItemHits = Convert.toNumber(jsObject[XmlElementNames.ItemHits]);
keywordStat.Size = Convert.toNumber(jsObject[XmlElementNames.Size]);
keywordStats.push(keywordStat);
}
return keywordStats.length === 0 ? null : keywordStats;
}
/**
* Load preview items from XML.
*
* @param {any} jsObject Json Object converted from XML.
* @param {ExchangeService} service The service.
* @return {SearchPreviewItem[]} Array of preview items
*/
private static LoadPreviewItemsXmlJsObject(jsObject: any, service: ExchangeService): SearchPreviewItem[] {
let previewItems: SearchPreviewItem[] = [];
for (let searchPreviewItem of EwsServiceJsonReader.ReadAsArray(jsObject, XmlElementNames.SearchPreviewItem)) {
let previewItem: SearchPreviewItem = new SearchPreviewItem();
if (searchPreviewItem[XmlElementNames.Id]) {
previewItem.Id = new ItemId();
previewItem.Id.LoadFromXmlJsObject(searchPreviewItem[XmlElementNames.Id], service);
}
if (searchPreviewItem[XmlElementNames.ParentId]) {
previewItem.ParentId = new ItemId();
previewItem.ParentId.LoadFromXmlJsObject(searchPreviewItem[XmlElementNames.ParentId], service);
}
if (searchPreviewItem[XmlElementNames.Mailbox]) {
previewItem.Mailbox = new PreviewItemMailbox();
previewItem.Mailbox.MailboxId = searchPreviewItem[XmlElementNames.Mailbox][XmlElementNames.MailboxId];
previewItem.Mailbox.PrimarySmtpAddress = searchPreviewItem[XmlElementNames.Mailbox][XmlElementNames.PrimarySmtpAddress];
}
//missing in official repo
if (searchPreviewItem[XmlElementNames.ItemClass]) {
previewItem.ItemClass = searchPreviewItem[XmlElementNames.ItemClass];
}
if (searchPreviewItem[XmlElementNames.UniqueHash]) {
previewItem.UniqueHash = searchPreviewItem[XmlElementNames.UniqueHash];
}
if (searchPreviewItem[XmlElementNames.SortValue]) {
previewItem.SortValue = searchPreviewItem[XmlElementNames.SortValue];
}
if (searchPreviewItem[XmlElementNames.OwaLink]) {
previewItem.OwaLink = searchPreviewItem[XmlElementNames.OwaLink];
}
if (searchPreviewItem[XmlElementNames.Sender]) {
previewItem.Sender = searchPreviewItem[XmlElementNames.Sender];
}
if (searchPreviewItem[XmlElementNames.ToRecipients]) {
previewItem.ToRecipients = this.GetRecipients(searchPreviewItem[XmlElementNames.ToRecipients]);
}
if (searchPreviewItem[XmlElementNames.CcRecipients]) {
previewItem.CcRecipients = this.GetRecipients(searchPreviewItem[XmlElementNames.CcRecipients]);
}
if (searchPreviewItem[XmlElementNames.BccRecipients]) {
previewItem.BccRecipients = this.GetRecipients(searchPreviewItem[XmlElementNames.BccRecipients]);
}
if (searchPreviewItem[XmlElementNames.CreatedTime]) {
previewItem.CreatedTime = DateTime.Parse(searchPreviewItem[XmlElementNames.CreatedTime]);
}
if (searchPreviewItem[XmlElementNames.ReceivedTime]) {
previewItem.ReceivedTime = DateTime.Parse(searchPreviewItem[XmlElementNames.ReceivedTime]);
}
if (searchPreviewItem[XmlElementNames.SentTime]) {
previewItem.SentTime = DateTime.Parse(searchPreviewItem[XmlElementNames.SentTime]);
}
if (searchPreviewItem[XmlElementNames.Subject]) {
previewItem.Subject = searchPreviewItem[XmlElementNames.Subject];
}
if (searchPreviewItem[XmlElementNames.Preview]) {
previewItem.Preview = searchPreviewItem[XmlElementNames.Preview];
}
if (searchPreviewItem[XmlElementNames.Size]) {
previewItem.Size = Convert.toNumber(searchPreviewItem[XmlElementNames.Size]);
}
if (searchPreviewItem[XmlElementNames.Importance]) {
previewItem.Importance = Importance[<string>searchPreviewItem[XmlElementNames.Importance]];
}
if (searchPreviewItem[XmlElementNames.Read]) {
previewItem.Read = Convert.toBool(searchPreviewItem[XmlElementNames.Read]);
}
if (searchPreviewItem[XmlElementNames.HasAttachment]) {
previewItem.HasAttachment = Convert.toBool(searchPreviewItem[XmlElementNames.HasAttachment]);
}
if (searchPreviewItem[XmlElementNames.ExtendedProperties]) {
previewItem.ExtendedProperties = this.LoadExtendedPropertiesXmlJsObject(searchPreviewItem[XmlElementNames.ExtendedProperties], service);
}
previewItems.push(previewItem);
}
return previewItems.length === 0 ? null : previewItems;
}
} | the_stack |
import * as dagre from 'dagre';
import { Template, Workflow } from '../../third_party/argo-ui/argo_template';
import { color } from '../Css';
import { Constants } from './Constants';
import { logger } from './Utils';
import { parseTaskDisplayName } from './ParserUtils';
import { graphlib } from 'dagre';
export type nodeType = 'container' | 'resource' | 'dag' | 'unknown';
export interface KeyValue<T> extends Array<any> {
0?: string | JSX.Element;
1?: T;
}
export class SelectedNodeInfo {
public args: string[];
public command: string[];
public condition: string;
public image: string;
public inputs: Array<KeyValue<string>>;
public nodeType: nodeType;
public outputs: Array<KeyValue<string>>;
public volumeMounts: Array<KeyValue<string>>;
public resource: Array<KeyValue<string>>;
constructor() {
this.args = [];
this.command = [];
this.condition = '';
this.image = '';
this.inputs = [[]];
this.nodeType = 'unknown';
this.outputs = [[]];
this.volumeMounts = [[]];
this.resource = [[]];
}
}
export function _populateInfoFromTemplate(
info: SelectedNodeInfo,
template?: Template,
): SelectedNodeInfo {
if (!template || (!template.container && !template.resource)) {
return info;
}
if (template.container) {
info.nodeType = 'container';
info.args = template.container.args || [];
info.command = template.container.command || [];
info.image = template.container.image || '';
info.volumeMounts = (template.container.volumeMounts || []).map(v => [v.mountPath, v.name]);
} else {
info.nodeType = 'resource';
if (template.resource && template.resource.action && template.resource.manifest) {
info.resource = [[template.resource.action, template.resource.manifest]];
} else {
info.resource = [[]];
}
}
if (template.inputs) {
info.inputs = (template.inputs.parameters || []).map(p => [p.name, p.value || '']);
}
if (template.outputs) {
info.outputs = (template.outputs.parameters || []).map(p => {
let value = '';
if (p.value) {
value = p.value;
} else if (p.valueFrom) {
value =
p.valueFrom.jqFilter ||
p.valueFrom.jsonPath ||
p.valueFrom.parameter ||
p.valueFrom.path ||
'';
}
return [p.name, value];
});
}
return info;
}
/**
* Recursively construct the static graph of the Pipeline.
*
* @param graph The dagre graph object
* @param rootTemplateId The current template being explored at this level of recursion
* @param templates An unchanging map of template name to template and type
* @param parentFullPath The task that was being examined when the function recursed. This string
* includes all of the nodes above it. For example, with a graph such as:
* A
* / \
* B C
* / \
* D E
* where A and C are DAGs, the parentFullPath when rootTemplateId is C would be: /A/C
*/
function buildDag(
graph: dagre.graphlib.Graph,
rootTemplateId: string,
templates: Map<string, { nodeType: nodeType; template: Template }>,
alreadyVisited: Map<string, string>,
parentFullPath: string,
): void {
const root = templates.get(rootTemplateId);
if (root && root.nodeType === 'dag') {
// Mark that we have visited this DAG, and save the original qualified path to it.
alreadyVisited.set(rootTemplateId, parentFullPath || '/' + rootTemplateId);
const template = root.template;
if (!template || !template.dag) {
throw new Error("Graph template or DAG object doesn't exist.");
}
(template.dag.tasks || []).forEach(task => {
const nodeId = parentFullPath + '/' + task.name;
// If the user specifies an exit handler, then the compiler will wrap the entire Pipeline
// within an additional DAG template prefixed with "exit-handler".
// If this is the case, we simply treat it as the root of the graph and work from there
if (task.name.startsWith('exit-handler')) {
buildDag(graph, task.template, templates, alreadyVisited, '');
return;
}
// If this task has already been visited, retrieve the qualified path name that was assigned
// to it, add an edge, and move on to the next task
if (alreadyVisited.has(task.name)) {
graph.setEdge(parentFullPath, alreadyVisited.get(task.name)!);
return;
}
// Parent here will be the task that pointed to this DAG template.
// Within a DAG template, tasks can have dependencies on one another, and long chains of
// dependencies can be present within a single DAG. In these cases, we choose not to draw an
// edge from the DAG node itself to these tasks with dependencies because such an edge would
// not be meaningful to the user. For example, consider a DAG A with two tasks, B and C, where
// task C depends on the output of task B. C is a task of A, but it's much more semantically
// important that C depends on B, so to avoid cluttering the graph, we simply omit the edge
// between A and C:
// A A
// / \ becomes /
// B <-- C B
// /
// C
if (parentFullPath && !task.dependencies) {
graph.setEdge(parentFullPath, nodeId);
}
// This object contains information about the node that we display to the user when they
// click on a node in the graph
const info = new SelectedNodeInfo();
if (task.when) {
info.condition = task.when;
}
// "Child" here is the template that this task points to. This template should either be a
// DAG, in which case we recurse, or a container/resource which can be thought of as a
// leaf node
const child = templates.get(task.template);
let nodeLabel = task.template;
if (child) {
if (child.nodeType === 'dag') {
buildDag(graph, task.template, templates, alreadyVisited, nodeId);
} else if (child.nodeType === 'container' || child.nodeType === 'resource') {
nodeLabel = parseTaskDisplayName(child.template.metadata) || nodeLabel;
_populateInfoFromTemplate(info, child.template);
} else {
throw new Error(
`Unknown nodetype: ${child.nodeType} on workflow template: ${child.template}`,
);
}
}
graph.setNode(nodeId, {
bgColor: task.when ? 'cornsilk' : undefined,
height: Constants.NODE_HEIGHT,
info,
label: nodeLabel,
width: Constants.NODE_WIDTH,
});
// DAG tasks can indicate dependencies which are graphically shown as parents with edges
// pointing to their children (the task(s)).
// TODO: The addition of the parent prefix to the dependency here is only valid if nodes only
// ever directly depend on their siblings. This is true now but may change in the future, and
// this will need to be updated.
(task.dependencies || []).forEach(dep => graph.setEdge(parentFullPath + '/' + dep, nodeId));
});
}
}
export function createGraph(workflow: Workflow): dagre.graphlib.Graph {
const graph = new dagre.graphlib.Graph();
graph.setGraph({});
graph.setDefaultEdgeLabel(() => ({}));
if (!workflow.spec || !workflow.spec.templates) {
throw new Error('Could not generate graph. Provided Pipeline had no components.');
}
if (!workflow.spec.entrypoint) {
throw new Error('Could not generate graph. Provided Pipeline had no entrypoint.');
}
const workflowTemplates = workflow.spec.templates;
const templates = new Map<string, { nodeType: nodeType; template: Template }>();
// Iterate through the workflow's templates to construct a map which will be used to traverse and
// construct the graph
for (const template of workflowTemplates.filter(t => !!t && !!t.name)) {
// Argo allows specifying a single global exit handler. We also highlight that node
if (template.name === workflow.spec.onExit) {
const info = new SelectedNodeInfo();
_populateInfoFromTemplate(info, template);
graph.setNode(template.name, {
bgColor: color.lightGrey,
height: Constants.NODE_HEIGHT,
info,
label: 'onExit - ' + template.name,
width: Constants.NODE_WIDTH,
});
}
if (template.container) {
templates.set(template.name, { nodeType: 'container', template });
} else if (template.resource) {
templates.set(template.name, { nodeType: 'resource', template });
} else if (template.dag) {
templates.set(template.name, { nodeType: 'dag', template });
} else {
logger.verbose(`Template: ${template.name} was neither a Container/Resource nor a DAG`);
}
}
buildDag(graph, workflow.spec.entrypoint, templates, new Map(), '');
// DSL-compiled Pipelines will always include a DAG, so they should never reach this point.
// It is, however, possible for users to upload manually constructed Pipelines, and extremely
// simple ones may have no steps or DAGs, just an entry point container.
if (graph.nodeCount() === 0) {
const entryPointTemplate = workflowTemplates.find(t => t.name === workflow.spec.entrypoint);
if (entryPointTemplate) {
graph.setNode(entryPointTemplate.name, {
height: Constants.NODE_HEIGHT,
label: entryPointTemplate.name,
width: Constants.NODE_WIDTH,
});
}
}
return graph;
}
/**
* Perform a transitive reduction over the input graph.
*
* From [1]: Transitive reduction of a directed graph D is another directed
* graph with the same vertices and as few edges as possible, such that for all
* pairs of vertices v, w a (directed) path from v to w in D exists if and only
* if such a path exists in the reduction
*
* The current implementation has a time complexity bound `O(n*m)`, where `n`
* are the nodes and `m` are the edges of the input graph.
*
* [1]: https://en.wikipedia.org/wiki/Transitive_reduction
*
* @param graph The dagre graph object
*/
export function transitiveReduction(graph: dagre.graphlib.Graph): dagre.graphlib.Graph | undefined {
// safeguard against too big graphs
if (!graph || graph.edgeCount() > 1000 || graph.nodeCount() > 1000) {
return undefined;
}
const result = graphlib.json.read(graphlib.json.write(graph));
let visited: string[] = [];
const dfs_with_removal = (current: string, parent: string) => {
result.successors(current)?.forEach((node: any) => {
if (visited.includes(node)) return;
visited.push(node);
if (result.successors(parent)?.includes(node)) {
result.removeEdge(parent, node);
}
dfs_with_removal(node, parent);
});
};
result.nodes().forEach(node => {
visited = []; // clean this up before each new DFS
// start a DFS from each successor of `node`
result.successors(node)?.forEach((successor: any) => dfs_with_removal(successor, node));
});
return result;
}
export function compareGraphEdges(graph1: dagre.graphlib.Graph, graph2: dagre.graphlib.Graph) {
return (
graph1
.edges()
.map(e => `${e.name}${e.v}${e.w}`)
.sort()
.toString() ===
graph2
.edges()
.map(e => `${e.name}${e.v}${e.w}`)
.sort()
.toString()
);
} | the_stack |
import Log from '@secret-agent/commons/Logger';
import { ILocationTrigger, IPipelineStatus } from '@secret-agent/interfaces/Location';
import { IJsPath } from 'awaited-dom/base/AwaitedPath';
import { ICookie } from '@secret-agent/interfaces/ICookie';
import { IInteractionGroups } from '@secret-agent/interfaces/IInteractions';
import { URL } from 'url';
import * as Fs from 'fs';
import Timer from '@secret-agent/commons/Timer';
import { createPromise } from '@secret-agent/commons/utils';
import IWaitForElementOptions from '@secret-agent/interfaces/IWaitForElementOptions';
import IExecJsPathResult from '@secret-agent/interfaces/IExecJsPathResult';
import { IRequestInit } from 'awaited-dom/base/interfaces/official';
import { IPuppetFrame, IPuppetFrameEvents } from '@secret-agent/interfaces/IPuppetFrame';
import { CanceledPromiseError } from '@secret-agent/commons/interfaces/IPendingWaitEvent';
import ISetCookieOptions from '@secret-agent/interfaces/ISetCookieOptions';
import { IBoundLog } from '@secret-agent/interfaces/ILog';
import INodePointer from 'awaited-dom/base/INodePointer';
import IWaitForOptions from '@secret-agent/interfaces/IWaitForOptions';
import IFrameMeta from '@secret-agent/interfaces/IFrameMeta';
import { LoadStatus } from '@secret-agent/interfaces/INavigation';
import { getNodeIdFnName } from '@secret-agent/interfaces/jsPathFnNames';
import IJsPathResult from '@secret-agent/interfaces/IJsPathResult';
import TypeSerializer from '@secret-agent/commons/TypeSerializer';
import * as Os from 'os';
import ICommandMeta from '@secret-agent/interfaces/ICommandMeta';
import IPoint from '@secret-agent/interfaces/IPoint';
import IResourceMeta from '@secret-agent/interfaces/IResourceMeta';
import SessionState from './SessionState';
import TabNavigationObserver from './FrameNavigationsObserver';
import Session from './Session';
import Tab from './Tab';
import Interactor from './Interactor';
import CommandRecorder from './CommandRecorder';
import FrameNavigations from './FrameNavigations';
import { Serializable } from '../interfaces/ISerializable';
import InjectedScriptError from './InjectedScriptError';
import { IJsPathHistory, JsPath } from './JsPath';
import InjectedScripts from './InjectedScripts';
import { PageRecorderResultSet } from '../injected-scripts/pageEventsRecorder';
const { log } = Log(module);
export default class FrameEnvironment {
public get session(): Session {
return this.tab.session;
}
public get devtoolsFrameId(): string {
return this.puppetFrame.id;
}
public get parentId(): number {
return this.parentFrame?.id;
}
public get parentFrame(): FrameEnvironment | null {
if (this.puppetFrame.parentId) {
return this.tab.frameEnvironmentsByPuppetId.get(this.puppetFrame.parentId);
}
return null;
}
public get isAttached(): boolean {
return this.puppetFrame.isAttached;
}
public get securityOrigin(): string {
return this.puppetFrame.securityOrigin;
}
public get childFrameEnvironments(): FrameEnvironment[] {
return [...this.tab.frameEnvironmentsById.values()].filter(
x => x.puppetFrame.parentId === this.devtoolsFrameId && this.isAttached,
);
}
public get isMainFrame(): boolean {
return !this.puppetFrame.parentId;
}
public readonly navigationsObserver: TabNavigationObserver;
public readonly navigations: FrameNavigations;
public readonly id: number;
public readonly tab: Tab;
public readonly jsPath: JsPath;
public readonly createdTime: Date;
public readonly createdAtCommandId: number;
public puppetFrame: IPuppetFrame;
public isReady: Promise<Error | void>;
public domNodeId: number;
public readonly interactor: Interactor;
protected readonly logger: IBoundLog;
private puppetNodeIdsBySaNodeId: Record<number, string> = {};
private prefetchedJsPaths: IJsPathResult[];
private readonly isDetached: boolean;
private isClosing = false;
private waitTimeouts: { timeout: NodeJS.Timeout; reject: (reason?: any) => void }[] = [];
private readonly commandRecorder: CommandRecorder;
private readonly cleanPaths: string[] = [];
public get url(): string {
return this.navigations.currentUrl;
}
private get sessionState(): SessionState {
return this.session.sessionState;
}
constructor(tab: Tab, frame: IPuppetFrame) {
this.puppetFrame = frame;
this.tab = tab;
this.createdTime = new Date();
this.id = tab.session.nextFrameId();
this.logger = log.createChild(module, {
tabId: tab.id,
sessionId: tab.session.id,
frameId: this.id,
});
this.jsPath = new JsPath(this, tab.isDetached);
this.isDetached = tab.isDetached;
this.createdAtCommandId = this.sessionState.lastCommand?.id;
this.navigations = new FrameNavigations(this.id, tab.sessionState);
this.navigationsObserver = new TabNavigationObserver(this.navigations);
this.interactor = new Interactor(this);
// give tab time to setup
process.nextTick(() => this.listen());
this.commandRecorder = new CommandRecorder(this, tab.session, tab.id, this.id, [
this.createRequest,
this.execJsPath,
this.fetch,
this.getChildFrameEnvironment,
this.getCookies,
this.getJsValue,
this.getLocationHref,
this.interact,
this.removeCookie,
this.runPluginCommand,
this.setCookie,
this.setFileInputFiles,
this.waitForElement,
this.waitForLoad,
this.waitForLocation,
// DO NOT ADD waitForReady
]);
// don't let this explode
this.isReady = this.install().catch(err => err);
}
public isAllowedCommand(method: string): boolean {
return (
this.commandRecorder.fnNames.has(method) ||
method === 'close' ||
method === 'recordDetachedJsPath'
);
}
public close(): void {
if (this.isClosing) return;
this.isClosing = true;
const parentLogId = this.logger.stats('FrameEnvironment.Closing');
try {
const cancelMessage = 'Terminated command because session closing';
Timer.expireAll(this.waitTimeouts, new CanceledPromiseError(cancelMessage));
this.navigationsObserver.cancelWaiting(cancelMessage);
this.logger.stats('FrameEnvironment.Closed', { parentLogId });
for (const path of this.cleanPaths) {
Fs.promises.unlink(path).catch(() => null);
}
} catch (error) {
if (!error.message.includes('Target closed') && !(error instanceof CanceledPromiseError)) {
this.logger.error('FrameEnvironment.ClosingError', { error, parentLogId });
}
}
}
/////// COMMANDS /////////////////////////////////////////////////////////////////////////////////////////////////////
public async interact(...interactionGroups: IInteractionGroups): Promise<void> {
if (this.isDetached) {
throw new Error("Sorry, you can't interact with a detached frame");
}
await this.navigationsObserver.waitForLoad(LoadStatus.DomContentLoaded);
const interactionResolvable = createPromise<void>(120e3);
this.waitTimeouts.push({
timeout: interactionResolvable.timeout,
reject: interactionResolvable.reject,
});
const cancelForNavigation = new CanceledPromiseError('Frame navigated');
const cancelOnNavigate = () => {
interactionResolvable.reject(cancelForNavigation);
};
try {
this.interactor.play(interactionGroups, interactionResolvable);
this.puppetFrame.once('frame-navigated', cancelOnNavigate);
await interactionResolvable.promise;
} catch (error) {
if (error === cancelForNavigation) return;
if (error instanceof CanceledPromiseError && this.isClosing) return;
throw error;
} finally {
this.puppetFrame.off('frame-navigated', cancelOnNavigate);
}
}
public async getJsValue<T>(expression: string): Promise<T> {
return await this.puppetFrame.evaluate<T>(expression, false);
}
public meta(): IFrameMeta {
return this.toJSON();
}
public async execJsPath<T>(jsPath: IJsPath): Promise<IExecJsPathResult<T>> {
// if nothing loaded yet, return immediately
if (!this.navigations.top) return null;
await this.navigationsObserver.waitForLoad(LoadStatus.DomContentLoaded);
const containerOffset = await this.getContainerOffset();
return await this.jsPath.exec(jsPath, containerOffset);
}
public async prefetchExecJsPaths(jsPaths: IJsPathHistory[]): Promise<IJsPathResult[]> {
const containerOffset = await this.getContainerOffset();
this.prefetchedJsPaths = await this.jsPath.runJsPaths(jsPaths, containerOffset);
return this.prefetchedJsPaths;
}
public recordDetachedJsPath(index: number, runStartDate: number, endDate: number): void {
const entry = this.prefetchedJsPaths[index];
const commandMeta = <ICommandMeta>{
name: 'execJsPath',
args: TypeSerializer.stringify([entry.jsPath]),
id: this.sessionState.commands.length + 1,
wasPrefetched: true,
tabId: this.tab.id,
frameId: this.id,
result: entry.result,
runStartDate,
endDate,
};
if (this.sessionState.nextCommandMeta) {
const { commandId, sendDate, startDate: clientStartDate } = this.sessionState.nextCommandMeta;
this.sessionState.nextCommandMeta = null;
commandMeta.id = commandId;
commandMeta.clientSendDate = sendDate?.getTime();
commandMeta.clientStartDate = clientStartDate?.getTime();
}
// only need to record start
this.sessionState.recordCommandStart(commandMeta);
}
public async createRequest(input: string | number, init?: IRequestInit): Promise<INodePointer> {
if (!this.navigations.top && !this.url) {
throw new Error(
'You need to use a "goto" before attempting to fetch. The in-browser fetch needs an origin to function properly.',
);
}
await this.navigationsObserver.waitForReady();
return this.runIsolatedFn(
`${InjectedScripts.Fetcher}.createRequest`,
input,
// @ts-ignore
init,
);
}
public async fetch(input: string | number, init?: IRequestInit): Promise<INodePointer> {
if (!this.navigations.top && !this.url) {
throw new Error(
'You need to use a "goto" before attempting to fetch. The in-browser fetch needs an origin to function properly.',
);
}
await this.navigationsObserver.waitForReady();
return this.runIsolatedFn(
`${InjectedScripts.Fetcher}.fetch`,
input,
// @ts-ignore
init,
);
}
public getLocationHref(): Promise<string> {
return Promise.resolve(this.navigations.currentUrl || this.puppetFrame.url);
}
public async getCookies(): Promise<ICookie[]> {
await this.navigationsObserver.waitForReady();
return await this.session.browserContext.getCookies(
new URL(this.puppetFrame.securityOrigin ?? this.puppetFrame.url),
);
}
public async setCookie(
name: string,
value: string,
options?: ISetCookieOptions,
): Promise<boolean> {
if (!this.navigations.top && this.puppetFrame.url === 'about:blank') {
throw new Error(`Chrome won't allow you to set cookies on a blank tab.
SecretAgent supports two options to set cookies:
a) Goto a url first and then set cookies on the activeTab
b) Use the UserProfile feature to set cookies for 1 or more domains before they're loaded (https://secretagent.dev/docs/advanced/user-profile)
`);
}
await this.navigationsObserver.waitForReady();
const url = this.navigations.currentUrl;
await this.session.browserContext.addCookies([
{
name,
value,
url,
...options,
},
]);
return true;
}
public async removeCookie(name: string): Promise<boolean> {
await this.session.browserContext.addCookies([
{
name,
value: '',
expires: 0,
url: this.puppetFrame.url,
},
]);
return true;
}
public async getChildFrameEnvironment(jsPath: IJsPath): Promise<IFrameMeta> {
await this.navigationsObserver.waitForLoad(LoadStatus.DomContentLoaded);
const nodeIdResult = await this.jsPath.exec<number>([...jsPath, [getNodeIdFnName]], null);
if (!nodeIdResult.value) return null;
const domId = nodeIdResult.value;
for (const frame of this.childFrameEnvironments) {
if (!frame.isAttached) continue;
await frame.isReady;
if (frame.domNodeId === domId) {
return frame.toJSON();
}
}
}
public async runPluginCommand(toPluginId: string, args: any[]): Promise<any> {
const commandMeta = {
puppetPage: this.tab.puppetPage,
puppetFrame: this.puppetFrame,
};
return await this.session.plugins.onPluginCommand(toPluginId, commandMeta, args);
}
public waitForElement(jsPath: IJsPath, options?: IWaitForElementOptions): Promise<boolean> {
return this.waitForDom(jsPath, options);
}
public async waitForLoad(status: IPipelineStatus, options?: IWaitForOptions): Promise<void> {
await this.isReady;
return this.navigationsObserver.waitForLoad(status, options);
}
public async waitForLocation(
trigger: ILocationTrigger,
options?: IWaitForOptions,
): Promise<IResourceMeta> {
const timer = new Timer(options?.timeoutMs ?? 60e3, this.waitTimeouts);
await timer.waitForPromise(
this.navigationsObserver.waitForLocation(trigger, options),
`Timeout waiting for location ${trigger}`,
);
const resource = await timer.waitForPromise(
this.navigationsObserver.waitForNavigationResourceId(),
`Timeout waiting for location ${trigger}`,
);
return this.sessionState.getResourceMeta(resource);
}
// NOTE: don't add this function to commands. It will record extra commands when called from interactor, which
// can break waitForLocation
public async waitForDom(jsPath: IJsPath, options?: IWaitForElementOptions): Promise<boolean> {
const waitForVisible = options?.waitForVisible ?? false;
const timeoutMs = options?.timeoutMs ?? 30e3;
const timeoutPerTry = timeoutMs < 1e3 ? timeoutMs : 1e3;
const timeoutMessage = `Timeout waiting for element to be visible`;
const timer = new Timer(timeoutMs, this.waitTimeouts);
await timer.waitForPromise(
this.navigationsObserver.waitForReady(),
'Timeout waiting for DomContentLoaded',
);
try {
while (!timer.isResolved()) {
try {
const containerOffset = await this.getContainerOffset();
const promise = this.jsPath.waitForElement(
jsPath,
containerOffset,
waitForVisible,
timeoutPerTry,
);
const isNodeVisible = await timer.waitForPromise(promise, timeoutMessage);
let isValid = isNodeVisible.value?.isVisible;
if (!waitForVisible) isValid = isNodeVisible.value?.nodeExists;
if (isValid) return true;
} catch (err) {
if (String(err).includes('not a valid selector')) throw err;
// don't log during loop
}
timer.throwIfExpired(timeoutMessage);
}
} finally {
timer.clear();
}
return false;
}
public moveMouseToStartLocation(): Promise<void> {
if (this.isDetached) return;
return this.interactor.initialize();
}
public async flushPageEventsRecorder(): Promise<boolean> {
try {
// don't wait for env to be available
if (!this.puppetFrame.canEvaluate(true)) return false;
const results = await this.puppetFrame.evaluate<PageRecorderResultSet>(
`window.flushPageRecorder()`,
true,
);
return this.onPageRecorderEvents(results);
} catch (error) {
// no op if it fails
}
return false;
}
public onPageRecorderEvents(results: PageRecorderResultSet): boolean {
const [domChanges, mouseEvents, focusEvents, scrollEvents, loadEvents] = results;
const hasRecords = results.some(x => x.length > 0);
if (!hasRecords) return false;
this.logger.stats('FrameEnvironment.onPageEvents', {
tabId: this.id,
dom: domChanges.length,
mouse: mouseEvents.length,
focusEvents: focusEvents.length,
scrollEvents: scrollEvents.length,
loadEvents,
});
for (const [event, url, timestamp] of loadEvents) {
const incomingStatus = pageStateToLoadStatus[event];
// only record the content paint
if (incomingStatus === LoadStatus.ContentPaint) {
this.navigations.onLoadStateChanged(incomingStatus, url, null, new Date(timestamp));
}
}
this.sessionState.captureDomEvents(
this.tab.id,
this.id,
domChanges,
mouseEvents,
focusEvents,
scrollEvents,
);
return true;
}
/////// UTILITIES ////////////////////////////////////////////////////////////////////////////////////////////////////
public toJSON(): IFrameMeta {
return {
id: this.id,
parentFrameId: this.parentId,
name: this.puppetFrame.name,
tabId: this.tab.id,
puppetId: this.devtoolsFrameId,
url: this.navigations.currentUrl,
securityOrigin: this.securityOrigin,
sessionId: this.session.id,
createdAtCommandId: this.createdAtCommandId,
} as IFrameMeta;
}
public runIsolatedFn<T>(fnName: string, ...args: Serializable[]): Promise<T> {
const callFn = `${fnName}(${args
.map(x => {
if (!x) return 'undefined';
return JSON.stringify(x);
})
.join(', ')})`;
return this.runFn<T>(fnName, callFn);
}
public async getDomNodeId(puppetNodeId: string): Promise<number> {
const nodeId = await this.puppetFrame.evaluateOnNode<number>(
puppetNodeId,
'NodeTracker.watchNode(this)',
);
this.puppetNodeIdsBySaNodeId[nodeId] = puppetNodeId;
return nodeId;
}
public async getContainerOffset(): Promise<IPoint> {
if (!this.parentId) return { x: 0, y: 0 };
const parentOffset = await this.parentFrame.getContainerOffset();
const frameElementNodeId = await this.puppetFrame.getFrameElementNodeId();
const thisOffset = await this.puppetFrame.evaluateOnNode<IPoint>(
frameElementNodeId,
`(() => {
const rect = this.getBoundingClientRect().toJSON();
return { x:rect.x, y:rect.y};
})()`,
);
return {
x: thisOffset.x + parentOffset.x,
y: thisOffset.y + parentOffset.y,
};
}
public async setFileInputFiles(
jsPath: IJsPath,
files: { name: string; data: Buffer }[],
): Promise<void> {
const puppetNodeId = this.puppetNodeIdsBySaNodeId[jsPath[0] as number];
const tmpDir = await Fs.promises.mkdtemp(`${Os.tmpdir()}/sa-upload`);
const filepaths: string[] = [];
for (const file of files) {
const fileName = `${tmpDir}/${file.name}`;
filepaths.push(fileName);
await Fs.promises.writeFile(fileName, file.data);
}
await this.puppetFrame.setFileInputFiles(puppetNodeId, filepaths);
this.cleanPaths.push(tmpDir);
}
protected async runFn<T>(fnName: string, serializedFn: string): Promise<T> {
const result = await this.puppetFrame.evaluate<T>(serializedFn, true);
if ((result as any)?.error) {
this.logger.error(fnName, { result });
throw new InjectedScriptError((result as any).error as string);
} else {
return result as T;
}
}
protected async install(): Promise<void> {
try {
if (this.isMainFrame) {
// only install interactor on the main frame
await this.interactor?.initialize();
} else {
const frameElementNodeId = await this.puppetFrame.getFrameElementNodeId();
// retrieve the domNode containing this frame (note: valid id only in the containing frame)
this.domNodeId = await this.getDomNodeId(frameElementNodeId);
}
} catch (error) {
// This can happen if the node goes away. Still want to record frame
this.logger.warn('FrameCreated.getDomNodeIdError', {
error,
frameId: this.id,
});
}
this.sessionState.captureFrameDetails(this);
}
private listen(): void {
const frame = this.puppetFrame;
frame.on('frame-navigated', this.onFrameNavigated.bind(this), true);
frame.on('frame-requested-navigation', this.onFrameRequestedNavigation.bind(this), true);
frame.on('frame-lifecycle', this.onFrameLifecycle.bind(this), true);
}
private onFrameLifecycle(event: IPuppetFrameEvents['frame-lifecycle']): void {
const lowerEventName = event.name.toLowerCase();
let status: LoadStatus.Load | LoadStatus.DomContentLoaded;
if (lowerEventName === 'load') status = LoadStatus.Load;
else if (lowerEventName === 'domcontentloaded') status = LoadStatus.DomContentLoaded;
if (status) {
this.navigations.onLoadStateChanged(
status,
event.loader.url ?? event.frame.url,
event.loader.id,
);
}
}
private onFrameNavigated(event: IPuppetFrameEvents['frame-navigated']): void {
const { navigatedInDocument, frame } = event;
if (navigatedInDocument) {
this.logger.info('Page.navigatedWithinDocument', event);
// set load state back to all loaded
this.navigations.onNavigationRequested(
'inPage',
frame.url,
this.tab.lastCommandId,
event.loaderId,
);
}
this.sessionState.captureFrameDetails(this);
}
// client-side frame navigations (form posts/gets, redirects/ page reloads)
private onFrameRequestedNavigation(
event: IPuppetFrameEvents['frame-requested-navigation'],
): void {
this.logger.info('Page.frameRequestedNavigation', event);
// disposition options: currentTab, newTab, newWindow, download
const { url, reason } = event;
this.navigations.updateNavigationReason(url, reason);
}
}
const pageStateToLoadStatus = {
LargestContentfulPaint: LoadStatus.ContentPaint,
DOMContentLoaded: LoadStatus.DomContentLoaded,
load: LoadStatus.Load,
}; | the_stack |
import * as assert from 'assert'
import { none, some } from 'fp-ts/lib/Option'
import { BehaviorSubject } from 'rxjs'
import { DebugData, DebuggerR, Global, MsgWithDebug } from '../../src/Debug/commons'
import { Connection, getConnection, reduxDevToolDebugger } from '../../src/Debug/redux-devtool'
import { Dispatch } from '../../src/Platform'
import { Model, Msg, STD_DEPS } from './_helpers'
describe('Debug/redux-dev-tool', () => {
it('getConnection() should return an IO of Some<Connection> if dev-tool extension is available', () => {
let called = false
const spyConnect = () => {
called = true
}
const noDevTool = getConnection({} as Global)
const globalWithDevTool = ({ __REDUX_DEVTOOLS_EXTENSION__: { connect: spyConnect } } as unknown) as Global
const withDevTool = getConnection(globalWithDevTool)
assert.deepStrictEqual(noDevTool(), none)
assert.deepStrictEqual(withDevTool(), some(undefined))
assert.ok(called)
})
describe('reduxDevToolDebugger()', () => {
// --- Setup
const oriConsoleWarn = console.warn
let connection: Connection<Model, Msg>
let emit: Dispatch<any>
beforeEach(() => {
connection = {
subscribe: listener => {
emit = listener as Dispatch<any>
return () => undefined
},
send: jest.fn(),
init: jest.fn(),
error: jest.fn(),
unsubscribe: jest.fn()
}
console.warn = jest.fn(() => undefined)
})
// --- Teardown
afterEach(() => {
console.warn = oriConsoleWarn
})
// --- Tests
it('should handle actions dispatched by application', () => {
const send = connection.send as jest.Mock<any, any>
const D = reduxDevToolDebugger(connection)(STD_DEPS)
D.debug([{ type: 'INIT' }, 0])
assert.strictEqual(send.mock.calls.length, 0)
D.debug([{ type: 'MESSAGE', payload: { type: 'Inc' } }, 1])
assertCalledWith(send, { type: 'Inc' }, 1)
})
it('should run connection.unsubscribe on stop', () => {
const unsubscribe = connection.unsubscribe as jest.Mock<any, any>
const D = reduxDevToolDebugger(connection)(STD_DEPS)
D.stop()
assert.strictEqual(unsubscribe.mock.calls.length, 1)
})
it('should handle "START" message from extension', () => {
const init = connection.init as jest.Mock<any, any>
reduxDevToolDebugger(connection)(STD_DEPS)
emit({ type: 'START' })
assertCalledWith(init, 0)
})
it('should handle "ACTION" message from extension', () => {
const warn = console.warn as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
// --- OK
emit({ type: 'ACTION', payload: JSON.stringify({ type: 'Inc' }) })
assertCalledWith(dispatch, { type: 'Inc' })
// --- Parse error
emit({ type: 'ACTION', payload: 'type: "Inc"' })
assertCalledWith(warn, '[REDUX DEV TOOL]', 'Unexpected token y in JSON at position 1')
})
it('should handle "JUMP_TO_STATE" and "JUMP_TO_ACTION" messages from extension', () => {
const warn = console.warn as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
// --- JUMP_TO_STATE - OK
emit({ type: 'DISPATCH', payload: { type: 'JUMP_TO_STATE' }, state: JSON.stringify(123) })
assertCalledNWith(1, dispatch, { type: '__DebugUpdateModel__', payload: 123 })
// --- JUMP_TO_STATE - Parse error
emit({ type: 'DISPATCH', payload: { type: 'JUMP_TO_STATE' } })
assertCalledNWith(1, warn, '[REDUX DEV TOOL]', 'Unexpected token u in JSON at position 0')
// --- JUMP_TO_ACTION - OK
emit({ type: 'DISPATCH', payload: { type: 'JUMP_TO_ACTION' }, state: JSON.stringify(123) })
assertCalledNWith(2, dispatch, { type: '__DebugUpdateModel__', payload: 123 })
// --- JUMP_TO_ACTION - Parse error
emit({ type: 'DISPATCH', payload: { type: 'JUMP_TO_ACTION' }, state: '1,23' })
assertCalledNWith(2, warn, '[REDUX DEV TOOL]', 'Unexpected token , in JSON at position 1')
})
it('should handle "RESET" message from extension', () => {
const init = connection.init as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
emit({ type: 'DISPATCH', payload: { type: 'RESET' } })
assertCalledWith(dispatch, { type: '__DebugUpdateModel__', payload: 0 })
assertCalledWith(init, 0)
})
it('should handle "ROLLBACK" message from extension', () => {
const warn = console.warn as jest.Mock<any, any>
const init = connection.init as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
// --- OK
emit({ type: 'DISPATCH', payload: { type: 'ROLLBACK' }, state: JSON.stringify(123) })
assertCalledWith(dispatch, { type: '__DebugUpdateModel__', payload: 123 })
assertCalledWith(init, 123)
// --- Parse error
emit({ type: 'DISPATCH', payload: { type: 'ROLLBACK' }, state: '1,23' })
assertCalledWith(warn, '[REDUX DEV TOOL]', 'Unexpected token , in JSON at position 1')
})
it('should handle "COMMIT" message from extension', () => {
const init = connection.init as jest.Mock<any, any>
const debug$ = new BehaviorSubject<DebugData<Model, Msg>>([{ type: 'INIT' }, 0])
reduxDevToolDebugger(connection)({ ...STD_DEPS, debug$ })
// Add some values in data$ stream to simulate a "living" application
debug$.next([{ type: 'MESSAGE', payload: { type: 'Inc' } }, 1])
debug$.next([{ type: 'MESSAGE', payload: { type: 'Inc' } }, 2])
debug$.next([{ type: 'MESSAGE', payload: { type: 'Inc' } }, 3])
debug$.next([{ type: 'MESSAGE', payload: { type: 'Dec' } }, 2])
emit({ type: 'DISPATCH', payload: { type: 'COMMIT' } })
assertCalledWith(init, 2) // gets current value from data$
})
it('should handle "IMPORT_STATE" message from extension', () => {
const warn = console.warn as jest.Mock<any, any>
const send = connection.send as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
// --- OK
emit({ type: 'DISPATCH', payload: { type: 'IMPORT_STATE', nextLiftedState: LIFTED_STATE } })
assertCalledWith(dispatch, { type: '__DebugUpdateModel__', payload: 2 })
assertCalledWith(send, null, LIFTED_STATE)
// --- Parse error
emit({ type: 'DISPATCH', payload: { type: 'IMPORT_STATE', foo: LIFTED_STATE } })
assertCalledWith(warn, '[REDUX DEV TOOL]', 'IMPORT_STATE message has some bad payload...')
})
it('should handle "TOGGLE_ACTION" message from extension', () => {
const warn = console.warn as jest.Mock<any, any>
const send = connection.send as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
// --- OK
emit({ type: 'DISPATCH', payload: { type: 'TOGGLE_ACTION', id: 2 }, state: JSON.stringify(LIFTED_STATE) })
assertCalledNWith(1, dispatch, { type: '__DebugUpdateModel__', payload: 1 })
assertCalledNWith(2, dispatch, { type: '__DebugApplyMsg__', payload: { type: 'Dec' } })
assertCalledNWith(3, dispatch, { type: '__DebugApplyMsg__', payload: { type: 'Inc' } })
assertCalledNWith(1, send, null, { ...LIFTED_STATE, skippedActionIds: [2] })
// --- Parse error
emit({ type: 'DISPATCH', payload: { type: 'TOGGLE_ACTION' }, state: JSON.stringify(LIFTED_STATE) })
assertCalledNWith(1, warn, '[REDUX DEV TOOL]', 'TOGGLE_ACTION message has some bad payload...')
emit({ type: 'DISPATCH', payload: { type: 'TOGGLE_ACTION', id: 2 }, state: 'actions: bad' })
assertCalledNWith(1, warn, '[REDUX DEV TOOL]', 'TOGGLE_ACTION message has some bad payload...')
})
it('should handle "TOGGLE_ACTION" message from extension - action not staged', () => {
const send = connection.send as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
emit({ type: 'DISPATCH', payload: { type: 'TOGGLE_ACTION', id: 5 }, state: JSON.stringify(LIFTED_STATE) })
assert.strictEqual(dispatch.mock.calls.length, 0)
assertCalledWith(send, null, LIFTED_STATE)
})
it('should handle "TOGGLE_ACTION" message from extension - action already toggled', () => {
const send = connection.send as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
emit({
type: 'DISPATCH',
payload: { type: 'TOGGLE_ACTION', id: 2 },
state: JSON.stringify({ ...LIFTED_STATE, skippedActionIds: [2] })
})
assertCalledNWith(1, dispatch, { type: '__DebugUpdateModel__', payload: 1 })
assertCalledNWith(2, dispatch, { type: '__DebugApplyMsg__', payload: { type: 'Inc' } })
assertCalledNWith(3, dispatch, { type: '__DebugApplyMsg__', payload: { type: 'Dec' } })
assertCalledNWith(4, dispatch, { type: '__DebugApplyMsg__', payload: { type: 'Inc' } })
assertCalledWith(send, null, LIFTED_STATE)
})
it('should handle "TOGGLE_ACTION" message from extension - action already toggled with others', () => {
const send = connection.send as jest.Mock<any, any>
const dispatch = jest.fn()
reduxDevToolDebugger(connection)(depsWith(dispatch))
emit({
type: 'DISPATCH',
payload: { type: 'TOGGLE_ACTION', id: 2 },
state: JSON.stringify({ ...LIFTED_STATE, skippedActionIds: [2, 4] })
})
assertCalledNWith(1, dispatch, { type: '__DebugUpdateModel__', payload: 1 })
assertCalledNWith(2, dispatch, { type: '__DebugApplyMsg__', payload: { type: 'Inc' } })
assertCalledNWith(3, dispatch, { type: '__DebugApplyMsg__', payload: { type: 'Dec' } })
assertCalledWith(send, null, {
...LIFTED_STATE,
skippedActionIds: [4]
})
})
it('should warn if message is not handled', () => {
const warn = console.warn as jest.Mock<any, any>
reduxDevToolDebugger(connection)(STD_DEPS)
emit({ type: 'DISPATCH', payload: { type: 'UNKNOWN_TYPE' } })
assertCalledWith(warn, '[REDUX DEV TOOL]', 'UNKNOWN_TYPE')
})
})
})
// --- Helpers
const depsWith = (dispatch: Dispatch<MsgWithDebug<Model, Msg>>): DebuggerR<Model, Msg> => ({
...STD_DEPS,
dispatch
})
const LIFTED_STATE = {
actionsById: {
'0': { action: { type: '@@INIT' }, timestamp: 1574269844816, type: 'PERFORM_ACTION' },
'1': { action: { type: 'Inc' }, timestamp: 1574269853594, type: 'PERFORM_ACTION' },
'2': { action: { type: 'Inc' }, timestamp: 1574269853726, type: 'PERFORM_ACTION' },
'3': { action: { type: 'Dec' }, timestamp: 1574269853888, type: 'PERFORM_ACTION' },
'4': { action: { type: 'Inc' }, timestamp: 1574269854031, type: 'PERFORM_ACTION' }
},
computedStates: [{ state: 0 }, { state: 1 }, { state: 2 }, { state: 1 }, { state: 2 }],
currentStateIndex: 4,
nextActionId: 5,
skippedActionIds: [],
stagedActionIds: [0, 1, 2, 3, 4]
}
/**
* Asserts that the mocked function was called **__1__** time with provided parameters
*/
function assertCalledWith(fn: jest.Mock<any, any[]>, ...params: any[]): void {
const calls = fn.mock.calls
assert.strictEqual(calls.length, 1)
calls[0].forEach((p, i) => {
assert.deepStrictEqual(p, params[i])
})
}
/**
* Asserts that the mocked function was called the **__n__** time with provided parameters
*/
function assertCalledNWith(n: number, fn: jest.Mock<any, any[]>, ...params: any[]): void {
const calls = fn.mock.calls
assert.ok(calls.length >= n)
calls[n - 1].forEach((p, i) => {
assert.deepStrictEqual(p, params[i])
})
} | the_stack |
/// <reference types="activex-interop" />
/// <reference types="activex-office" />
/// <reference types="activex-vbide" />
/// <reference types="activex-stdole" />
declare namespace Word {
const enum WdAlertLevel {
wdAlertsAll = -1,
wdAlertsMessageBox = -2,
wdAlertsNone = 0,
}
const enum WdAlignmentTabAlignment {
wdCenter = 1,
wdLeft = 0,
wdRight = 2,
}
const enum WdAlignmentTabRelative {
wdIndent = 1,
wdMargin = 0,
}
const enum WdAnimation {
wdAnimationBlinkingBackground = 2,
wdAnimationLasVegasLights = 1,
wdAnimationMarchingBlackAnts = 4,
wdAnimationMarchingRedAnts = 5,
wdAnimationNone = 0,
wdAnimationShimmer = 6,
wdAnimationSparkleText = 3,
}
const enum WdApplyQuickStyleSets {
wdSessionStartSet = 1,
wdTemplateSet = 2,
}
const enum WdArabicNumeral {
wdNumeralArabic = 0,
wdNumeralContext = 2,
wdNumeralHindi = 1,
wdNumeralSystem = 3,
}
const enum WdAraSpeller {
wdBoth = 3,
wdFinalYaa = 2,
wdInitialAlef = 1,
wdNone = 0,
}
const enum WdArrangeStyle {
wdIcons = 1,
wdTiled = 0,
}
const enum WdAutoFitBehavior {
wdAutoFitContent = 1,
wdAutoFitFixed = 0,
wdAutoFitWindow = 2,
}
const enum WdAutoMacros {
wdAutoClose = 3,
wdAutoExec = 0,
wdAutoExit = 4,
wdAutoNew = 1,
wdAutoOpen = 2,
wdAutoSync = 5,
}
const enum WdAutoVersions {
wdAutoVersionOff = 0,
wdAutoVersionOnClose = 1,
}
const enum WdBaselineAlignment {
wdBaselineAlignAuto = 4,
wdBaselineAlignBaseline = 2,
wdBaselineAlignCenter = 1,
wdBaselineAlignFarEast50 = 3,
wdBaselineAlignTop = 0,
}
const enum WdBookmarkSortBy {
wdSortByLocation = 1,
wdSortByName = 0,
}
const enum WdBorderDistanceFrom {
wdBorderDistanceFromPageEdge = 1,
wdBorderDistanceFromText = 0,
}
const enum WdBorderType {
wdBorderBottom = -3,
wdBorderDiagonalDown = -7,
wdBorderDiagonalUp = -8,
wdBorderHorizontal = -5,
wdBorderLeft = -2,
wdBorderRight = -4,
wdBorderTop = -1,
wdBorderVertical = -6,
}
const enum WdBorderTypeHID {
emptyenum = 0,
}
const enum WdBreakType {
wdColumnBreak = 8,
wdLineBreak = 6,
wdLineBreakClearLeft = 9,
wdLineBreakClearRight = 10,
wdPageBreak = 7,
wdSectionBreakContinuous = 3,
wdSectionBreakEvenPage = 4,
wdSectionBreakNextPage = 2,
wdSectionBreakOddPage = 5,
wdTextWrappingBreak = 11,
}
const enum WdBrowserLevel {
wdBrowserLevelMicrosoftInternetExplorer5 = 1,
wdBrowserLevelMicrosoftInternetExplorer6 = 2,
wdBrowserLevelV4 = 0,
}
const enum WdBrowseTarget {
wdBrowseComment = 3,
wdBrowseEdit = 10,
wdBrowseEndnote = 5,
wdBrowseField = 6,
wdBrowseFind = 11,
wdBrowseFootnote = 4,
wdBrowseGoTo = 12,
wdBrowseGraphic = 8,
wdBrowseHeading = 9,
wdBrowsePage = 1,
wdBrowseSection = 2,
wdBrowseTable = 7,
}
const enum WdBuildingBlockTypes {
wdTypeAutoText = 9,
wdTypeBibliography = 34,
wdTypeCoverPage = 2,
wdTypeCustom1 = 29,
wdTypeCustom2 = 30,
wdTypeCustom3 = 31,
wdTypeCustom4 = 32,
wdTypeCustom5 = 33,
wdTypeCustomAutoText = 23,
wdTypeCustomBibliography = 35,
wdTypeCustomCoverPage = 16,
wdTypeCustomEquations = 17,
wdTypeCustomFooters = 18,
wdTypeCustomHeaders = 19,
wdTypeCustomPageNumber = 20,
wdTypeCustomPageNumberBottom = 26,
wdTypeCustomPageNumberPage = 27,
wdTypeCustomPageNumberTop = 25,
wdTypeCustomQuickParts = 15,
wdTypeCustomTableOfContents = 28,
wdTypeCustomTables = 21,
wdTypeCustomTextBox = 24,
wdTypeCustomWatermarks = 22,
wdTypeEquations = 3,
wdTypeFooters = 4,
wdTypeHeaders = 5,
wdTypePageNumber = 6,
wdTypePageNumberBottom = 12,
wdTypePageNumberPage = 13,
wdTypePageNumberTop = 11,
wdTypeQuickParts = 1,
wdTypeTableOfContents = 14,
wdTypeTables = 7,
wdTypeTextBox = 10,
wdTypeWatermarks = 8,
}
const enum WdBuiltInProperty {
wdPropertyAppName = 9,
wdPropertyAuthor = 3,
wdPropertyBytes = 22,
wdPropertyCategory = 18,
wdPropertyCharacters = 16,
wdPropertyCharsWSpaces = 30,
wdPropertyComments = 5,
wdPropertyCompany = 21,
wdPropertyFormat = 19,
wdPropertyHiddenSlides = 27,
wdPropertyHyperlinkBase = 29,
wdPropertyKeywords = 4,
wdPropertyLastAuthor = 7,
wdPropertyLines = 23,
wdPropertyManager = 20,
wdPropertyMMClips = 28,
wdPropertyNotes = 26,
wdPropertyPages = 14,
wdPropertyParas = 24,
wdPropertyRevision = 8,
wdPropertySecurity = 17,
wdPropertySlides = 25,
wdPropertySubject = 2,
wdPropertyTemplate = 6,
wdPropertyTimeCreated = 11,
wdPropertyTimeLastPrinted = 10,
wdPropertyTimeLastSaved = 12,
wdPropertyTitle = 1,
wdPropertyVBATotalEdit = 13,
wdPropertyWords = 15,
}
const enum WdBuiltinStyle {
wdStyleBibliography = -266,
wdStyleBlockQuotation = -85,
wdStyleBodyText = -67,
wdStyleBodyText2 = -81,
wdStyleBodyText3 = -82,
wdStyleBodyTextFirstIndent = -78,
wdStyleBodyTextFirstIndent2 = -79,
wdStyleBodyTextIndent = -68,
wdStyleBodyTextIndent2 = -83,
wdStyleBodyTextIndent3 = -84,
wdStyleBookTitle = -265,
wdStyleCaption = -35,
wdStyleClosing = -64,
wdStyleCommentReference = -40,
wdStyleCommentText = -31,
wdStyleDate = -77,
wdStyleDefaultParagraphFont = -66,
wdStyleEmphasis = -89,
wdStyleEndnoteReference = -43,
wdStyleEndnoteText = -44,
wdStyleEnvelopeAddress = -37,
wdStyleEnvelopeReturn = -38,
wdStyleFooter = -33,
wdStyleFootnoteReference = -39,
wdStyleFootnoteText = -30,
wdStyleHeader = -32,
wdStyleHeading1 = -2,
wdStyleHeading2 = -3,
wdStyleHeading3 = -4,
wdStyleHeading4 = -5,
wdStyleHeading5 = -6,
wdStyleHeading6 = -7,
wdStyleHeading7 = -8,
wdStyleHeading8 = -9,
wdStyleHeading9 = -10,
wdStyleHtmlAcronym = -96,
wdStyleHtmlAddress = -97,
wdStyleHtmlCite = -98,
wdStyleHtmlCode = -99,
wdStyleHtmlDfn = -100,
wdStyleHtmlKbd = -101,
wdStyleHtmlNormal = -95,
wdStyleHtmlPre = -102,
wdStyleHtmlSamp = -103,
wdStyleHtmlTt = -104,
wdStyleHtmlVar = -105,
wdStyleHyperlink = -86,
wdStyleHyperlinkFollowed = -87,
wdStyleIndex1 = -11,
wdStyleIndex2 = -12,
wdStyleIndex3 = -13,
wdStyleIndex4 = -14,
wdStyleIndex5 = -15,
wdStyleIndex6 = -16,
wdStyleIndex7 = -17,
wdStyleIndex8 = -18,
wdStyleIndex9 = -19,
wdStyleIndexHeading = -34,
wdStyleIntenseEmphasis = -262,
wdStyleIntenseQuote = -182,
wdStyleIntenseReference = -264,
wdStyleLineNumber = -41,
wdStyleList = -48,
wdStyleList2 = -51,
wdStyleList3 = -52,
wdStyleList4 = -53,
wdStyleList5 = -54,
wdStyleListBullet = -49,
wdStyleListBullet2 = -55,
wdStyleListBullet3 = -56,
wdStyleListBullet4 = -57,
wdStyleListBullet5 = -58,
wdStyleListContinue = -69,
wdStyleListContinue2 = -70,
wdStyleListContinue3 = -71,
wdStyleListContinue4 = -72,
wdStyleListContinue5 = -73,
wdStyleListNumber = -50,
wdStyleListNumber2 = -59,
wdStyleListNumber3 = -60,
wdStyleListNumber4 = -61,
wdStyleListNumber5 = -62,
wdStyleListParagraph = -180,
wdStyleMacroText = -46,
wdStyleMessageHeader = -74,
wdStyleNavPane = -90,
wdStyleNormal = -1,
wdStyleNormalIndent = -29,
wdStyleNormalObject = -158,
wdStyleNormalTable = -106,
wdStyleNoteHeading = -80,
wdStylePageNumber = -42,
wdStylePlainText = -91,
wdStyleQuote = -181,
wdStyleSalutation = -76,
wdStyleSignature = -65,
wdStyleStrong = -88,
wdStyleSubtitle = -75,
wdStyleSubtleEmphasis = -261,
wdStyleSubtleReference = -263,
wdStyleTableColorfulGrid = -172,
wdStyleTableColorfulList = -171,
wdStyleTableColorfulShading = -170,
wdStyleTableDarkList = -169,
wdStyleTableLightGrid = -161,
wdStyleTableLightGridAccent1 = -175,
wdStyleTableLightList = -160,
wdStyleTableLightListAccent1 = -174,
wdStyleTableLightShading = -159,
wdStyleTableLightShadingAccent1 = -173,
wdStyleTableMediumGrid1 = -166,
wdStyleTableMediumGrid2 = -167,
wdStyleTableMediumGrid3 = -168,
wdStyleTableMediumList1 = -164,
wdStyleTableMediumList1Accent1 = -178,
wdStyleTableMediumList2 = -165,
wdStyleTableMediumShading1 = -162,
wdStyleTableMediumShading1Accent1 = -176,
wdStyleTableMediumShading2 = -163,
wdStyleTableMediumShading2Accent1 = -177,
wdStyleTableOfAuthorities = -45,
wdStyleTableOfFigures = -36,
wdStyleTitle = -63,
wdStyleTOAHeading = -47,
wdStyleTOC1 = -20,
wdStyleTOC2 = -21,
wdStyleTOC3 = -22,
wdStyleTOC4 = -23,
wdStyleTOC5 = -24,
wdStyleTOC6 = -25,
wdStyleTOC7 = -26,
wdStyleTOC8 = -27,
wdStyleTOC9 = -28,
wdStyleTocHeading = -267,
}
const enum WdCalendarType {
wdCalendarArabic = 1,
wdCalendarHebrew = 2,
wdCalendarJapan = 4,
wdCalendarKorean = 6,
wdCalendarSakaEra = 7,
wdCalendarTaiwan = 3,
wdCalendarThai = 5,
wdCalendarTranslitEnglish = 8,
wdCalendarTranslitFrench = 9,
wdCalendarUmalqura = 13,
wdCalendarWestern = 0,
}
const enum WdCalendarTypeBi {
wdCalendarTypeBidi = 99,
wdCalendarTypeGregorian = 100,
}
const enum WdCaptionLabelID {
wdCaptionEquation = -3,
wdCaptionFigure = -1,
wdCaptionTable = -2,
}
const enum WdCaptionNumberStyle {
wdCaptionNumberStyleArabic = 0,
wdCaptionNumberStyleArabicFullWidth = 14,
wdCaptionNumberStyleArabicLetter1 = 46,
wdCaptionNumberStyleArabicLetter2 = 48,
wdCaptionNumberStyleChosung = 25,
wdCaptionNumberStyleGanada = 24,
wdCaptionNumberStyleHanjaRead = 41,
wdCaptionNumberStyleHanjaReadDigit = 42,
wdCaptionNumberStyleHebrewLetter1 = 45,
wdCaptionNumberStyleHebrewLetter2 = 47,
wdCaptionNumberStyleHindiArabic = 51,
wdCaptionNumberStyleHindiCardinalText = 52,
wdCaptionNumberStyleHindiLetter1 = 49,
wdCaptionNumberStyleHindiLetter2 = 50,
wdCaptionNumberStyleKanji = 10,
wdCaptionNumberStyleKanjiDigit = 11,
wdCaptionNumberStyleKanjiTraditional = 16,
wdCaptionNumberStyleLowercaseLetter = 4,
wdCaptionNumberStyleLowercaseRoman = 2,
wdCaptionNumberStyleNumberInCircle = 18,
wdCaptionNumberStyleSimpChinNum2 = 38,
wdCaptionNumberStyleSimpChinNum3 = 39,
wdCaptionNumberStyleThaiArabic = 54,
wdCaptionNumberStyleThaiCardinalText = 55,
wdCaptionNumberStyleThaiLetter = 53,
wdCaptionNumberStyleTradChinNum2 = 34,
wdCaptionNumberStyleTradChinNum3 = 35,
wdCaptionNumberStyleUppercaseLetter = 3,
wdCaptionNumberStyleUppercaseRoman = 1,
wdCaptionNumberStyleVietCardinalText = 56,
wdCaptionNumberStyleZodiac1 = 30,
wdCaptionNumberStyleZodiac2 = 31,
}
const enum WdCaptionNumberStyleHID {
emptyenum = 0,
}
const enum WdCaptionPosition {
wdCaptionPositionAbove = 0,
wdCaptionPositionBelow = 1,
}
const enum WdCellColor {
wdCellColorByAuthor = -1,
wdCellColorLightBlue = 2,
wdCellColorLightGray = 7,
wdCellColorLightGreen = 6,
wdCellColorLightOrange = 5,
wdCellColorLightPurple = 4,
wdCellColorLightYellow = 3,
wdCellColorNoHighlight = 0,
wdCellColorPink = 1,
}
const enum WdCellVerticalAlignment {
wdCellAlignVerticalBottom = 3,
wdCellAlignVerticalCenter = 1,
wdCellAlignVerticalTop = 0,
}
const enum WdCharacterCase {
wdFullWidth = 7,
wdHalfWidth = 6,
wdHiragana = 9,
wdKatakana = 8,
wdLowerCase = 0,
wdNextCase = -1,
wdTitleSentence = 4,
wdTitleWord = 2,
wdToggleCase = 5,
wdUpperCase = 1,
}
const enum WdCharacterCaseHID {
emptyenum = 0,
}
const enum WdCharacterWidth {
wdWidthFullWidth = 7,
wdWidthHalfWidth = 6,
}
const enum WdCheckInVersionType {
wdCheckInMajorVersion = 1,
wdCheckInMinorVersion = 0,
wdCheckInOverwriteVersion = 2,
}
const enum WdChevronConvertRule {
wdAlwaysConvert = 1,
wdAskToConvert = 3,
wdAskToNotConvert = 2,
wdNeverConvert = 0,
}
const enum WdCollapseDirection {
wdCollapseEnd = 0,
wdCollapseStart = 1,
}
const enum WdColor {
wdColorAqua = 13421619,
wdColorAutomatic = -16777216,
wdColorBlack = 0,
wdColorBlue = 16711680,
wdColorBlueGray = 10053222,
wdColorBrightGreen = 65280,
wdColorBrown = 13209,
wdColorDarkBlue = 8388608,
wdColorDarkGreen = 13056,
wdColorDarkRed = 128,
wdColorDarkTeal = 6697728,
wdColorDarkYellow = 32896,
wdColorGold = 52479,
wdColorGray05 = 15987699,
wdColorGray10 = 15132390,
wdColorGray125 = 14737632,
wdColorGray15 = 14277081,
wdColorGray20 = 13421772,
wdColorGray25 = 12632256,
wdColorGray30 = 11776947,
wdColorGray35 = 10921638,
wdColorGray375 = 10526880,
wdColorGray40 = 10066329,
wdColorGray45 = 9211020,
wdColorGray50 = 8421504,
wdColorGray55 = 7566195,
wdColorGray60 = 6710886,
wdColorGray625 = 6316128,
wdColorGray65 = 5855577,
wdColorGray70 = 5000268,
wdColorGray75 = 4210752,
wdColorGray80 = 3355443,
wdColorGray85 = 2500134,
wdColorGray875 = 2105376,
wdColorGray90 = 1644825,
wdColorGray95 = 789516,
wdColorGreen = 32768,
wdColorIndigo = 10040115,
wdColorLavender = 16751052,
wdColorLightBlue = 16737843,
wdColorLightGreen = 13434828,
wdColorLightOrange = 39423,
wdColorLightTurquoise = 16777164,
wdColorLightYellow = 10092543,
wdColorLime = 52377,
wdColorOliveGreen = 13107,
wdColorOrange = 26367,
wdColorPaleBlue = 16764057,
wdColorPink = 16711935,
wdColorPlum = 6697881,
wdColorRed = 255,
wdColorRose = 13408767,
wdColorSeaGreen = 6723891,
wdColorSkyBlue = 16763904,
wdColorTan = 10079487,
wdColorTeal = 8421376,
wdColorTurquoise = 16776960,
wdColorViolet = 8388736,
wdColorWhite = 16777215,
wdColorYellow = 65535,
}
const enum WdColorIndex {
wdAuto = 0,
wdBlack = 1,
wdBlue = 2,
wdBrightGreen = 4,
wdByAuthor = -1,
wdDarkBlue = 9,
wdDarkRed = 13,
wdDarkYellow = 14,
wdGray25 = 16,
wdGray50 = 15,
wdGreen = 11,
wdNoHighlight = 0,
wdPink = 5,
wdRed = 6,
wdTeal = 10,
wdTurquoise = 3,
wdViolet = 12,
wdWhite = 8,
wdYellow = 7,
}
const enum WdCompareDestination {
wdCompareDestinationNew = 2,
wdCompareDestinationOriginal = 0,
wdCompareDestinationRevised = 1,
}
const enum WdCompareTarget {
wdCompareTargetCurrent = 1,
wdCompareTargetNew = 2,
wdCompareTargetSelected = 0,
}
const enum WdCompatibility {
wdAlignTablesRowByRow = 39,
wdAllowSpaceOfSameStyleInTable = 54,
wdApplyBreakingRules = 46,
wdAutofitLikeWW11 = 57,
wdAutospaceLikeWW7 = 38,
wdCachedColBalance = 65,
wdConvMailMergeEsc = 6,
wdDisableOTKerning = 66,
wdDontAdjustLineHeightInTable = 36,
wdDontAutofitConstrainedTables = 56,
wdDontBalanceSingleByteDoubleByteWidth = 16,
wdDontBreakConstrainedForcedTables = 62,
wdDontBreakWrappedTables = 43,
wdDontOverrideTableStyleFontSzAndJustification = 68,
wdDontSnapTextToGridInTableWithObjects = 44,
wdDontULTrailSpace = 15,
wdDontUseAsianBreakRulesInGrid = 48,
wdDontUseHTMLParagraphAutoSpacing = 35,
wdDontUseIndentAsNumberingTabStop = 52,
wdDontVertAlignCellWithShape = 61,
wdDontVertAlignInTextbox = 63,
wdDontWrapTextWithPunctuation = 47,
wdExactOnTop = 28,
wdExpandShiftReturn = 14,
wdFELineBreak11 = 53,
wdFlipMirrorIndents = 67,
wdFootnoteLayoutLikeWW8 = 34,
wdForgetLastTabAlignment = 37,
wdGrowAutofit = 50,
wdHangulWidthLikeWW11 = 59,
wdLayoutRawTableWidth = 40,
wdLayoutTableRowsApart = 41,
wdLeaveBackslashAlone = 13,
wdLineWrapLikeWord6 = 32,
wdMWSmallCaps = 22,
wdNoColumnBalance = 5,
wdNoExtraLineSpacing = 23,
wdNoLeading = 20,
wdNoSpaceForUL = 21,
wdNoSpaceRaiseLower = 2,
wdNoTabHangIndent = 1,
wdOrigWordTableRules = 9,
wdPrintBodyTextBeforeHeader = 19,
wdPrintColBlack = 3,
wdSelectFieldWithFirstOrLastCharacter = 45,
wdShapeLayoutLikeWW8 = 33,
wdShowBreaksInFrames = 11,
wdSpacingInWholePoints = 18,
wdSplitPgBreakAndParaMark = 60,
wdSubFontBySize = 25,
wdSuppressBottomSpacing = 29,
wdSuppressSpBfAfterPgBrk = 7,
wdSuppressTopSpacing = 8,
wdSuppressTopSpacingMac5 = 17,
wdSwapBordersFacingPages = 12,
wdTransparentMetafiles = 10,
wdTruncateFontHeight = 24,
wdUnderlineTabInNumList = 58,
wdUseNormalStyleForList = 51,
wdUsePrinterMetrics = 26,
wdUseWord2002TableStyleRules = 49,
wdUseWord97LineBreakingRules = 42,
wdWord11KerningPairs = 64,
wdWPJustification = 31,
wdWPSpaceWidth = 30,
wdWrapTrailSpaces = 4,
wdWW11IndentRules = 55,
wdWW6BorderRules = 27,
}
const enum WdCompatibilityMode {
wdCurrent = 65535,
wdWord2003 = 11,
wdWord2007 = 12,
wdWord2010 = 14,
}
const enum WdConditionCode {
wdEvenColumnBanding = 7,
wdEvenRowBanding = 3,
wdFirstColumn = 4,
wdFirstRow = 0,
wdLastColumn = 5,
wdLastRow = 1,
wdNECell = 8,
wdNWCell = 9,
wdOddColumnBanding = 6,
wdOddRowBanding = 2,
wdSECell = 10,
wdSWCell = 11,
}
const enum WdConstants {
wdAutoPosition = 0,
wdBackward = -1073741823,
wdCreatorCode = 1297307460,
wdFirst = 1,
wdForward = 1073741823,
wdToggle = 9999998,
wdUndefined = 9999999,
}
const enum WdContentControlDateStorageFormat {
wdContentControlDateStorageDate = 1,
wdContentControlDateStorageDateTime = 2,
wdContentControlDateStorageText = 0,
}
const enum WdContentControlType {
wdContentControlBuildingBlockGallery = 5,
wdContentControlCheckBox = 8,
wdContentControlComboBox = 3,
wdContentControlDate = 6,
wdContentControlDropdownList = 4,
wdContentControlGroup = 7,
wdContentControlPicture = 2,
wdContentControlRichText = 0,
wdContentControlText = 1,
}
const enum WdContinue {
wdContinueDisabled = 0,
wdContinueList = 2,
wdResetList = 1,
}
const enum WdCountry {
wdArgentina = 54,
wdBrazil = 55,
wdCanada = 2,
wdChile = 56,
wdChina = 86,
wdDenmark = 45,
wdFinland = 358,
wdFrance = 33,
wdGermany = 49,
wdIceland = 354,
wdItaly = 39,
wdJapan = 81,
wdKorea = 82,
wdLatinAmerica = 3,
wdMexico = 52,
wdNetherlands = 31,
wdNorway = 47,
wdPeru = 51,
wdSpain = 34,
wdSweden = 46,
wdTaiwan = 886,
wdUK = 44,
wdUS = 1,
wdVenezuela = 58,
}
const enum WdCursorMovement {
wdCursorMovementLogical = 0,
wdCursorMovementVisual = 1,
}
const enum WdCursorType {
wdCursorIBeam = 1,
wdCursorNormal = 2,
wdCursorNorthwestArrow = 3,
wdCursorWait = 0,
}
const enum WdCustomLabelPageSize {
wdCustomLabelA4 = 2,
wdCustomLabelA4LS = 3,
wdCustomLabelA5 = 4,
wdCustomLabelA5LS = 5,
wdCustomLabelB4JIS = 13,
wdCustomLabelB5 = 6,
wdCustomLabelFanfold = 8,
wdCustomLabelHigaki = 11,
wdCustomLabelHigakiLS = 12,
wdCustomLabelLetter = 0,
wdCustomLabelLetterLS = 1,
wdCustomLabelMini = 7,
wdCustomLabelVertHalfSheet = 9,
wdCustomLabelVertHalfSheetLS = 10,
}
const enum WdDateLanguage {
wdDateLanguageBidi = 10,
wdDateLanguageLatin = 1033,
}
const enum WdDefaultFilePath {
wdAutoRecoverPath = 5,
wdBorderArtPath = 19,
wdCurrentFolderPath = 14,
wdDocumentsPath = 0,
wdGraphicsFiltersPath = 10,
wdPicturesPath = 1,
wdProgramPath = 9,
wdProofingToolsPath = 12,
wdStartupPath = 8,
wdStyleGalleryPath = 15,
wdTempFilePath = 13,
wdTextConvertersPath = 11,
wdToolsPath = 6,
wdTutorialPath = 7,
wdUserOptionsPath = 4,
wdUserTemplatesPath = 2,
wdWorkgroupTemplatesPath = 3,
}
const enum WdDefaultListBehavior {
wdWord10ListBehavior = 2,
wdWord8ListBehavior = 0,
wdWord9ListBehavior = 1,
}
const enum WdDefaultTableBehavior {
wdWord8TableBehavior = 0,
wdWord9TableBehavior = 1,
}
const enum WdDeleteCells {
wdDeleteCellsEntireColumn = 3,
wdDeleteCellsEntireRow = 2,
wdDeleteCellsShiftLeft = 0,
wdDeleteCellsShiftUp = 1,
}
const enum WdDeletedTextMark {
wdDeletedTextMarkBold = 5,
wdDeletedTextMarkCaret = 2,
wdDeletedTextMarkColorOnly = 9,
wdDeletedTextMarkDoubleStrikeThrough = 10,
wdDeletedTextMarkDoubleUnderline = 8,
wdDeletedTextMarkHidden = 0,
wdDeletedTextMarkItalic = 6,
wdDeletedTextMarkNone = 4,
wdDeletedTextMarkPound = 3,
wdDeletedTextMarkStrikeThrough = 1,
wdDeletedTextMarkUnderline = 7,
}
const enum WdDiacriticColor {
wdDiacriticColorBidi = 0,
wdDiacriticColorLatin = 1,
}
const enum WdDictionaryType {
wdGrammar = 1,
wdHangulHanjaConversion = 8,
wdHangulHanjaConversionCustom = 9,
wdHyphenation = 3,
wdSpelling = 0,
wdSpellingComplete = 4,
wdSpellingCustom = 5,
wdSpellingLegal = 6,
wdSpellingMedical = 7,
wdThesaurus = 2,
}
const enum WdDictionaryTypeHID {
emptyenum = 0,
}
const enum WdDisableFeaturesIntroducedAfter {
wd70 = 0,
wd70FE = 1,
wd80 = 2,
}
const enum WdDocPartInsertOptions {
wdInsertContent = 0,
wdInsertPage = 2,
wdInsertParagraph = 1,
}
const enum WdDocumentDirection {
wdLeftToRight = 0,
wdRightToLeft = 1,
}
const enum WdDocumentKind {
wdDocumentEmail = 2,
wdDocumentLetter = 1,
wdDocumentNotSpecified = 0,
}
const enum WdDocumentMedium {
wdDocument = 1,
wdEmailMessage = 0,
wdWebPage = 2,
}
const enum WdDocumentType {
wdTypeDocument = 0,
wdTypeFrameset = 2,
wdTypeTemplate = 1,
}
const enum WdDocumentViewDirection {
wdDocumentViewLtr = 1,
wdDocumentViewRtl = 0,
}
const enum WdDropPosition {
wdDropMargin = 2,
wdDropNone = 0,
wdDropNormal = 1,
}
const enum WdEditionOption {
wdAutomaticUpdate = 3,
wdCancelPublisher = 0,
wdChangeAttributes = 5,
wdManualUpdate = 4,
wdOpenSource = 7,
wdSelectPublisher = 2,
wdSendPublisher = 1,
wdUpdateSubscriber = 6,
}
const enum WdEditionType {
wdPublisher = 0,
wdSubscriber = 1,
}
const enum WdEditorType {
wdEditorCurrent = -6,
wdEditorEditors = -5,
wdEditorEveryone = -1,
wdEditorOwners = -4,
}
const enum WdEmailHTMLFidelity {
wdEmailHTMLFidelityHigh = 3,
wdEmailHTMLFidelityLow = 1,
wdEmailHTMLFidelityMedium = 2,
}
const enum WdEmphasisMark {
wdEmphasisMarkNone = 0,
wdEmphasisMarkOverComma = 2,
wdEmphasisMarkOverSolidCircle = 1,
wdEmphasisMarkOverWhiteCircle = 3,
wdEmphasisMarkUnderSolidCircle = 4,
}
const enum WdEnableCancelKey {
wdCancelDisabled = 0,
wdCancelInterrupt = 1,
}
const enum WdEncloseStyle {
wdEncloseStyleLarge = 2,
wdEncloseStyleNone = 0,
wdEncloseStyleSmall = 1,
}
const enum WdEnclosureType {
wdEnclosureCircle = 0,
wdEnclosureDiamond = 3,
wdEnclosureSquare = 1,
wdEnclosureTriangle = 2,
}
const enum WdEndnoteLocation {
wdEndOfDocument = 1,
wdEndOfSection = 0,
}
const enum WdEnvelopeOrientation {
wdCenterClockwise = 7,
wdCenterLandscape = 4,
wdCenterPortrait = 1,
wdLeftClockwise = 6,
wdLeftLandscape = 3,
wdLeftPortrait = 0,
wdRightClockwise = 8,
wdRightLandscape = 5,
wdRightPortrait = 2,
}
const enum WdExportCreateBookmarks {
wdExportCreateHeadingBookmarks = 1,
wdExportCreateNoBookmarks = 0,
wdExportCreateWordBookmarks = 2,
}
const enum WdExportFormat {
wdExportFormatPDF = 17,
wdExportFormatXPS = 18,
}
const enum WdExportItem {
wdExportDocumentContent = 0,
wdExportDocumentWithMarkup = 7,
}
const enum WdExportOptimizeFor {
wdExportOptimizeForOnScreen = 1,
wdExportOptimizeForPrint = 0,
}
const enum WdExportRange {
wdExportAllDocument = 0,
wdExportCurrentPage = 2,
wdExportFromTo = 3,
wdExportSelection = 1,
}
const enum WdFarEastLineBreakLanguageID {
wdLineBreakJapanese = 1041,
wdLineBreakKorean = 1042,
wdLineBreakSimplifiedChinese = 2052,
wdLineBreakTraditionalChinese = 1028,
}
const enum WdFarEastLineBreakLevel {
wdFarEastLineBreakLevelCustom = 2,
wdFarEastLineBreakLevelNormal = 0,
wdFarEastLineBreakLevelStrict = 1,
}
const enum WdFieldKind {
wdFieldKindCold = 3,
wdFieldKindHot = 1,
wdFieldKindNone = 0,
wdFieldKindWarm = 2,
}
const enum WdFieldShading {
wdFieldShadingAlways = 1,
wdFieldShadingNever = 0,
wdFieldShadingWhenSelected = 2,
}
const enum WdFieldType {
wdFieldAddin = 81,
wdFieldAddressBlock = 93,
wdFieldAdvance = 84,
wdFieldAsk = 38,
wdFieldAuthor = 17,
wdFieldAutoNum = 54,
wdFieldAutoNumLegal = 53,
wdFieldAutoNumOutline = 52,
wdFieldAutoText = 79,
wdFieldAutoTextList = 89,
wdFieldBarCode = 63,
wdFieldBibliography = 97,
wdFieldBidiOutline = 92,
wdFieldCitation = 96,
wdFieldComments = 19,
wdFieldCompare = 80,
wdFieldCreateDate = 21,
wdFieldData = 40,
wdFieldDatabase = 78,
wdFieldDate = 31,
wdFieldDDE = 45,
wdFieldDDEAuto = 46,
wdFieldDocProperty = 85,
wdFieldDocVariable = 64,
wdFieldEditTime = 25,
wdFieldEmbed = 58,
wdFieldEmpty = -1,
wdFieldExpression = 34,
wdFieldFileName = 29,
wdFieldFileSize = 69,
wdFieldFillIn = 39,
wdFieldFootnoteRef = 5,
wdFieldFormCheckBox = 71,
wdFieldFormDropDown = 83,
wdFieldFormTextInput = 70,
wdFieldFormula = 49,
wdFieldGlossary = 47,
wdFieldGoToButton = 50,
wdFieldGreetingLine = 94,
wdFieldHTMLActiveX = 91,
wdFieldHyperlink = 88,
wdFieldIf = 7,
wdFieldImport = 55,
wdFieldInclude = 36,
wdFieldIncludePicture = 67,
wdFieldIncludeText = 68,
wdFieldIndex = 8,
wdFieldIndexEntry = 4,
wdFieldInfo = 14,
wdFieldKeyWord = 18,
wdFieldLastSavedBy = 20,
wdFieldLink = 56,
wdFieldListNum = 90,
wdFieldMacroButton = 51,
wdFieldMergeField = 59,
wdFieldMergeRec = 44,
wdFieldMergeSeq = 75,
wdFieldNext = 41,
wdFieldNextIf = 42,
wdFieldNoteRef = 72,
wdFieldNumChars = 28,
wdFieldNumPages = 26,
wdFieldNumWords = 27,
wdFieldOCX = 87,
wdFieldPage = 33,
wdFieldPageRef = 37,
wdFieldPrint = 48,
wdFieldPrintDate = 23,
wdFieldPrivate = 77,
wdFieldQuote = 35,
wdFieldRef = 3,
wdFieldRefDoc = 11,
wdFieldRevisionNum = 24,
wdFieldSaveDate = 22,
wdFieldSection = 65,
wdFieldSectionPages = 66,
wdFieldSequence = 12,
wdFieldSet = 6,
wdFieldShape = 95,
wdFieldSkipIf = 43,
wdFieldStyleRef = 10,
wdFieldSubject = 16,
wdFieldSubscriber = 82,
wdFieldSymbol = 57,
wdFieldTemplate = 30,
wdFieldTime = 32,
wdFieldTitle = 15,
wdFieldTOA = 73,
wdFieldTOAEntry = 74,
wdFieldTOC = 13,
wdFieldTOCEntry = 9,
wdFieldUserAddress = 62,
wdFieldUserInitials = 61,
wdFieldUserName = 60,
}
const enum WdFindMatch {
wdMatchAnyCharacter = 65599,
wdMatchAnyDigit = 65567,
wdMatchAnyLetter = 65583,
wdMatchCaretCharacter = 11,
wdMatchColumnBreak = 14,
wdMatchCommentMark = 5,
wdMatchEmDash = 8212,
wdMatchEnDash = 8211,
wdMatchEndnoteMark = 65555,
wdMatchField = 19,
wdMatchFootnoteMark = 65554,
wdMatchGraphic = 1,
wdMatchManualLineBreak = 65551,
wdMatchManualPageBreak = 65564,
wdMatchNonbreakingHyphen = 30,
wdMatchNonbreakingSpace = 160,
wdMatchOptionalHyphen = 31,
wdMatchParagraphMark = 65551,
wdMatchSectionBreak = 65580,
wdMatchTabCharacter = 9,
wdMatchWhiteSpace = 65655,
}
const enum WdFindWrap {
wdFindAsk = 2,
wdFindContinue = 1,
wdFindStop = 0,
}
const enum WdFlowDirection {
wdFlowLtr = 0,
wdFlowRtl = 1,
}
const enum WdFontBias {
wdFontBiasDefault = 0,
wdFontBiasDontCare = 255,
wdFontBiasFareast = 1,
}
const enum WdFootnoteLocation {
wdBeneathText = 1,
wdBottomOfPage = 0,
}
const enum WdFramePosition {
wdFrameBottom = -999997,
wdFrameCenter = -999995,
wdFrameInside = -999994,
wdFrameLeft = -999998,
wdFrameOutside = -999993,
wdFrameRight = -999996,
wdFrameTop = -999999,
}
const enum WdFramesetNewFrameLocation {
wdFramesetNewFrameAbove = 0,
wdFramesetNewFrameBelow = 1,
wdFramesetNewFrameLeft = 3,
wdFramesetNewFrameRight = 2,
}
const enum WdFramesetSizeType {
wdFramesetSizeTypeFixed = 1,
wdFramesetSizeTypePercent = 0,
wdFramesetSizeTypeRelative = 2,
}
const enum WdFramesetType {
wdFramesetTypeFrame = 1,
wdFramesetTypeFrameset = 0,
}
const enum WdFrameSizeRule {
wdFrameAtLeast = 1,
wdFrameAuto = 0,
wdFrameExact = 2,
}
const enum WdFrenchSpeller {
wdFrenchBoth = 0,
wdFrenchPostReform = 2,
wdFrenchPreReform = 1,
}
const enum WdGoToDirection {
wdGoToAbsolute = 1,
wdGoToFirst = 1,
wdGoToLast = -1,
wdGoToNext = 2,
wdGoToPrevious = 3,
wdGoToRelative = 2,
}
const enum WdGoToItem {
wdGoToBookmark = -1,
wdGoToComment = 6,
wdGoToEndnote = 5,
wdGoToEquation = 10,
wdGoToField = 7,
wdGoToFootnote = 4,
wdGoToGrammaticalError = 14,
wdGoToGraphic = 8,
wdGoToHeading = 11,
wdGoToLine = 3,
wdGoToObject = 9,
wdGoToPage = 1,
wdGoToPercent = 12,
wdGoToProofreadingError = 15,
wdGoToSection = 0,
wdGoToSpellingError = 13,
wdGoToTable = 2,
}
const enum WdGranularity {
wdGranularityCharLevel = 0,
wdGranularityWordLevel = 1,
}
const enum WdGutterStyle {
wdGutterPosLeft = 0,
wdGutterPosRight = 2,
wdGutterPosTop = 1,
}
const enum WdGutterStyleOld {
wdGutterStyleBidi = 2,
wdGutterStyleLatin = -10,
}
const enum WdHeaderFooterIndex {
wdHeaderFooterEvenPages = 3,
wdHeaderFooterFirstPage = 2,
wdHeaderFooterPrimary = 1,
}
const enum WdHeadingSeparator {
wdHeadingSeparatorBlankLine = 1,
wdHeadingSeparatorLetter = 2,
wdHeadingSeparatorLetterFull = 4,
wdHeadingSeparatorLetterLow = 3,
wdHeadingSeparatorNone = 0,
}
const enum WdHebSpellStart {
wdFullScript = 0,
wdMixedAuthorizedScript = 3,
wdMixedScript = 2,
wdPartialScript = 1,
}
const enum WdHelpType {
wdHelp = 0,
wdHelpAbout = 1,
wdHelpActiveWindow = 2,
wdHelpContents = 3,
wdHelpExamplesAndDemos = 4,
wdHelpHWP = 13,
wdHelpIchitaro = 11,
wdHelpIndex = 5,
wdHelpKeyboard = 6,
wdHelpPE2 = 12,
wdHelpPSSHelp = 7,
wdHelpQuickPreview = 8,
wdHelpSearch = 9,
wdHelpUsingHelp = 10,
}
const enum WdHelpTypeHID {
emptyenum = 0,
}
const enum WdHighAnsiText {
wdAutoDetectHighAnsiFarEast = 2,
wdHighAnsiIsFarEast = 0,
wdHighAnsiIsHighAnsi = 1,
}
const enum WdHorizontalInVerticalType {
wdHorizontalInVerticalFitInLine = 1,
wdHorizontalInVerticalNone = 0,
wdHorizontalInVerticalResizeLine = 2,
}
const enum WdHorizontalLineAlignment {
wdHorizontalLineAlignCenter = 1,
wdHorizontalLineAlignLeft = 0,
wdHorizontalLineAlignRight = 2,
}
const enum WdHorizontalLineWidthType {
wdHorizontalLineFixedWidth = -2,
wdHorizontalLinePercentWidth = -1,
}
const enum WdIMEMode {
wdIMEModeAlpha = 8,
wdIMEModeAlphaFull = 7,
wdIMEModeHangul = 10,
wdIMEModeHangulFull = 9,
wdIMEModeHiragana = 4,
wdIMEModeKatakana = 5,
wdIMEModeKatakanaHalf = 6,
wdIMEModeNoControl = 0,
wdIMEModeOff = 2,
wdIMEModeOn = 1,
}
const enum WdIndexFilter {
wdIndexFilterAiueo = 1,
wdIndexFilterAkasatana = 2,
wdIndexFilterChosung = 3,
wdIndexFilterFull = 6,
wdIndexFilterLow = 4,
wdIndexFilterMedium = 5,
wdIndexFilterNone = 0,
}
const enum WdIndexFormat {
wdIndexBulleted = 4,
wdIndexClassic = 1,
wdIndexFancy = 2,
wdIndexFormal = 5,
wdIndexModern = 3,
wdIndexSimple = 6,
wdIndexTemplate = 0,
}
const enum WdIndexSortBy {
wdIndexSortByStroke = 0,
wdIndexSortBySyllable = 1,
}
const enum WdIndexType {
wdIndexIndent = 0,
wdIndexRunin = 1,
}
const enum WdInformation {
wdActiveEndAdjustedPageNumber = 1,
wdActiveEndPageNumber = 3,
wdActiveEndSectionNumber = 2,
wdAtEndOfRowMarker = 31,
wdCapsLock = 21,
wdEndOfRangeColumnNumber = 17,
wdEndOfRangeRowNumber = 14,
wdFirstCharacterColumnNumber = 9,
wdFirstCharacterLineNumber = 10,
wdFrameIsSelected = 11,
wdHeaderFooterType = 33,
wdHorizontalPositionRelativeToPage = 5,
wdHorizontalPositionRelativeToTextBoundary = 7,
wdInClipboard = 38,
wdInCommentPane = 26,
wdInEndnote = 36,
wdInFootnote = 35,
wdInFootnoteEndnotePane = 25,
wdInHeaderFooter = 28,
wdInMasterDocument = 34,
wdInWordMail = 37,
wdMaximumNumberOfColumns = 18,
wdMaximumNumberOfRows = 15,
wdNumberOfPagesInDocument = 4,
wdNumLock = 22,
wdOverType = 23,
wdReferenceOfType = 32,
wdRevisionMarking = 24,
wdSelectionMode = 20,
wdStartOfRangeColumnNumber = 16,
wdStartOfRangeRowNumber = 13,
wdVerticalPositionRelativeToPage = 6,
wdVerticalPositionRelativeToTextBoundary = 8,
wdWithInTable = 12,
wdZoomPercentage = 19,
}
const enum WdInlineShapeType {
wdInlineShapeChart = 12,
wdInlineShapeDiagram = 13,
wdInlineShapeEmbeddedOLEObject = 1,
wdInlineShapeHorizontalLine = 6,
wdInlineShapeLinkedOLEObject = 2,
wdInlineShapeLinkedPicture = 4,
wdInlineShapeLinkedPictureHorizontalLine = 8,
wdInlineShapeLockedCanvas = 14,
wdInlineShapeOLEControlObject = 5,
wdInlineShapeOWSAnchor = 11,
wdInlineShapePicture = 3,
wdInlineShapePictureBullet = 9,
wdInlineShapePictureHorizontalLine = 7,
wdInlineShapeScriptAnchor = 10,
wdInlineShapeSmartArt = 15,
}
const enum WdInsertCells {
wdInsertCellsEntireColumn = 3,
wdInsertCellsEntireRow = 2,
wdInsertCellsShiftDown = 1,
wdInsertCellsShiftRight = 0,
}
const enum WdInsertedTextMark {
wdInsertedTextMarkBold = 1,
wdInsertedTextMarkColorOnly = 5,
wdInsertedTextMarkDoubleStrikeThrough = 7,
wdInsertedTextMarkDoubleUnderline = 4,
wdInsertedTextMarkItalic = 2,
wdInsertedTextMarkNone = 0,
wdInsertedTextMarkStrikeThrough = 6,
wdInsertedTextMarkUnderline = 3,
}
const enum WdInternationalIndex {
wd24HourClock = 21,
wdCurrencyCode = 20,
wdDateSeparator = 25,
wdDecimalSeparator = 18,
wdInternationalAM = 22,
wdInternationalPM = 23,
wdListSeparator = 17,
wdProductLanguageID = 26,
wdThousandsSeparator = 19,
wdTimeSeparator = 24,
}
const enum WdJustificationMode {
wdJustificationModeCompress = 1,
wdJustificationModeCompressKana = 2,
wdJustificationModeExpand = 0,
}
const enum WdKana {
wdKanaHiragana = 9,
wdKanaKatakana = 8,
}
const enum WdKey {
wdKey0 = 48,
wdKey1 = 49,
wdKey2 = 50,
wdKey3 = 51,
wdKey4 = 52,
wdKey5 = 53,
wdKey6 = 54,
wdKey7 = 55,
wdKey8 = 56,
wdKey9 = 57,
wdKeyA = 65,
wdKeyAlt = 1024,
wdKeyB = 66,
wdKeyBackSingleQuote = 192,
wdKeyBackSlash = 220,
wdKeyBackspace = 8,
wdKeyC = 67,
wdKeyCloseSquareBrace = 221,
wdKeyComma = 188,
wdKeyCommand = 512,
wdKeyControl = 512,
wdKeyD = 68,
wdKeyDelete = 46,
wdKeyE = 69,
wdKeyEnd = 35,
wdKeyEquals = 187,
wdKeyEsc = 27,
wdKeyF = 70,
wdKeyF1 = 112,
wdKeyF10 = 121,
wdKeyF11 = 122,
wdKeyF12 = 123,
wdKeyF13 = 124,
wdKeyF14 = 125,
wdKeyF15 = 126,
wdKeyF16 = 127,
wdKeyF2 = 113,
wdKeyF3 = 114,
wdKeyF4 = 115,
wdKeyF5 = 116,
wdKeyF6 = 117,
wdKeyF7 = 118,
wdKeyF8 = 119,
wdKeyF9 = 120,
wdKeyG = 71,
wdKeyH = 72,
wdKeyHome = 36,
wdKeyHyphen = 189,
wdKeyI = 73,
wdKeyInsert = 45,
wdKeyJ = 74,
wdKeyK = 75,
wdKeyL = 76,
wdKeyM = 77,
wdKeyN = 78,
wdKeyNumeric0 = 96,
wdKeyNumeric1 = 97,
wdKeyNumeric2 = 98,
wdKeyNumeric3 = 99,
wdKeyNumeric4 = 100,
wdKeyNumeric5 = 101,
wdKeyNumeric5Special = 12,
wdKeyNumeric6 = 102,
wdKeyNumeric7 = 103,
wdKeyNumeric8 = 104,
wdKeyNumeric9 = 105,
wdKeyNumericAdd = 107,
wdKeyNumericDecimal = 110,
wdKeyNumericDivide = 111,
wdKeyNumericMultiply = 106,
wdKeyNumericSubtract = 109,
wdKeyO = 79,
wdKeyOpenSquareBrace = 219,
wdKeyOption = 1024,
wdKeyP = 80,
wdKeyPageDown = 34,
wdKeyPageUp = 33,
wdKeyPause = 19,
wdKeyPeriod = 190,
wdKeyQ = 81,
wdKeyR = 82,
wdKeyReturn = 13,
wdKeyS = 83,
wdKeyScrollLock = 145,
wdKeySemiColon = 186,
wdKeyShift = 256,
wdKeySingleQuote = 222,
wdKeySlash = 191,
wdKeySpacebar = 32,
wdKeyT = 84,
wdKeyTab = 9,
wdKeyU = 85,
wdKeyV = 86,
wdKeyW = 87,
wdKeyX = 88,
wdKeyY = 89,
wdKeyZ = 90,
wdNoKey = 255,
}
const enum WdKeyCategory {
wdKeyCategoryAutoText = 4,
wdKeyCategoryCommand = 1,
wdKeyCategoryDisable = 0,
wdKeyCategoryFont = 3,
wdKeyCategoryMacro = 2,
wdKeyCategoryNil = -1,
wdKeyCategoryPrefix = 7,
wdKeyCategoryStyle = 5,
wdKeyCategorySymbol = 6,
}
const enum WdLanguageID {
wdAfrikaans = 1078,
wdAlbanian = 1052,
wdAmharic = 1118,
wdArabic = 1025,
wdArabicAlgeria = 5121,
wdArabicBahrain = 15361,
wdArabicEgypt = 3073,
wdArabicIraq = 2049,
wdArabicJordan = 11265,
wdArabicKuwait = 13313,
wdArabicLebanon = 12289,
wdArabicLibya = 4097,
wdArabicMorocco = 6145,
wdArabicOman = 8193,
wdArabicQatar = 16385,
wdArabicSyria = 10241,
wdArabicTunisia = 7169,
wdArabicUAE = 14337,
wdArabicYemen = 9217,
wdArmenian = 1067,
wdAssamese = 1101,
wdAzeriCyrillic = 2092,
wdAzeriLatin = 1068,
wdBasque = 1069,
wdBelgianDutch = 2067,
wdBelgianFrench = 2060,
wdBengali = 1093,
wdBulgarian = 1026,
wdBurmese = 1109,
wdByelorussian = 1059,
wdCatalan = 1027,
wdCherokee = 1116,
wdChineseHongKongSAR = 3076,
wdChineseMacaoSAR = 5124,
wdChineseSingapore = 4100,
wdCroatian = 1050,
wdCzech = 1029,
wdDanish = 1030,
wdDivehi = 1125,
wdDutch = 1043,
wdEdo = 1126,
wdEnglishAUS = 3081,
wdEnglishBelize = 10249,
wdEnglishCanadian = 4105,
wdEnglishCaribbean = 9225,
wdEnglishIndonesia = 14345,
wdEnglishIreland = 6153,
wdEnglishJamaica = 8201,
wdEnglishNewZealand = 5129,
wdEnglishPhilippines = 13321,
wdEnglishSouthAfrica = 7177,
wdEnglishTrinidadTobago = 11273,
wdEnglishUK = 2057,
wdEnglishUS = 1033,
wdEnglishZimbabwe = 12297,
wdEstonian = 1061,
wdFaeroese = 1080,
wdFilipino = 1124,
wdFinnish = 1035,
wdFrench = 1036,
wdFrenchCameroon = 11276,
wdFrenchCanadian = 3084,
wdFrenchCongoDRC = 9228,
wdFrenchCotedIvoire = 12300,
wdFrenchHaiti = 15372,
wdFrenchLuxembourg = 5132,
wdFrenchMali = 13324,
wdFrenchMonaco = 6156,
wdFrenchMorocco = 14348,
wdFrenchReunion = 8204,
wdFrenchSenegal = 10252,
wdFrenchWestIndies = 7180,
wdFrisianNetherlands = 1122,
wdFulfulde = 1127,
wdGaelicIreland = 2108,
wdGaelicScotland = 1084,
wdGalician = 1110,
wdGeorgian = 1079,
wdGerman = 1031,
wdGermanAustria = 3079,
wdGermanLiechtenstein = 5127,
wdGermanLuxembourg = 4103,
wdGreek = 1032,
wdGuarani = 1140,
wdGujarati = 1095,
wdHausa = 1128,
wdHawaiian = 1141,
wdHebrew = 1037,
wdHindi = 1081,
wdHungarian = 1038,
wdIbibio = 1129,
wdIcelandic = 1039,
wdIgbo = 1136,
wdIndonesian = 1057,
wdInuktitut = 1117,
wdItalian = 1040,
wdJapanese = 1041,
wdKannada = 1099,
wdKanuri = 1137,
wdKashmiri = 1120,
wdKazakh = 1087,
wdKhmer = 1107,
wdKirghiz = 1088,
wdKonkani = 1111,
wdKorean = 1042,
wdKyrgyz = 1088,
wdLanguageNone = 0,
wdLao = 1108,
wdLatin = 1142,
wdLatvian = 1062,
wdLithuanian = 1063,
wdMacedonianFYROM = 1071,
wdMalayalam = 1100,
wdMalayBruneiDarussalam = 2110,
wdMalaysian = 1086,
wdMaltese = 1082,
wdManipuri = 1112,
wdMarathi = 1102,
wdMexicanSpanish = 2058,
wdMongolian = 1104,
wdNepali = 1121,
wdNoProofing = 1024,
wdNorwegianBokmol = 1044,
wdNorwegianNynorsk = 2068,
wdOriya = 1096,
wdOromo = 1138,
wdPashto = 1123,
wdPersian = 1065,
wdPolish = 1045,
wdPortuguese = 2070,
wdPortugueseBrazil = 1046,
wdPunjabi = 1094,
wdRhaetoRomanic = 1047,
wdRomanian = 1048,
wdRomanianMoldova = 2072,
wdRussian = 1049,
wdRussianMoldova = 2073,
wdSamiLappish = 1083,
wdSanskrit = 1103,
wdSerbianCyrillic = 3098,
wdSerbianLatin = 2074,
wdSesotho = 1072,
wdSimplifiedChinese = 2052,
wdSindhi = 1113,
wdSindhiPakistan = 2137,
wdSinhalese = 1115,
wdSlovak = 1051,
wdSlovenian = 1060,
wdSomali = 1143,
wdSorbian = 1070,
wdSpanish = 1034,
wdSpanishArgentina = 11274,
wdSpanishBolivia = 16394,
wdSpanishChile = 13322,
wdSpanishColombia = 9226,
wdSpanishCostaRica = 5130,
wdSpanishDominicanRepublic = 7178,
wdSpanishEcuador = 12298,
wdSpanishElSalvador = 17418,
wdSpanishGuatemala = 4106,
wdSpanishHonduras = 18442,
wdSpanishModernSort = 3082,
wdSpanishNicaragua = 19466,
wdSpanishPanama = 6154,
wdSpanishParaguay = 15370,
wdSpanishPeru = 10250,
wdSpanishPuertoRico = 20490,
wdSpanishUruguay = 14346,
wdSpanishVenezuela = 8202,
wdSutu = 1072,
wdSwahili = 1089,
wdSwedish = 1053,
wdSwedishFinland = 2077,
wdSwissFrench = 4108,
wdSwissGerman = 2055,
wdSwissItalian = 2064,
wdSyriac = 1114,
wdTajik = 1064,
wdTamazight = 1119,
wdTamazightLatin = 2143,
wdTamil = 1097,
wdTatar = 1092,
wdTelugu = 1098,
wdThai = 1054,
wdTibetan = 1105,
wdTigrignaEritrea = 2163,
wdTigrignaEthiopic = 1139,
wdTraditionalChinese = 1028,
wdTsonga = 1073,
wdTswana = 1074,
wdTurkish = 1055,
wdTurkmen = 1090,
wdUkrainian = 1058,
wdUrdu = 1056,
wdUzbekCyrillic = 2115,
wdUzbekLatin = 1091,
wdVenda = 1075,
wdVietnamese = 1066,
wdWelsh = 1106,
wdXhosa = 1076,
wdYi = 1144,
wdYiddish = 1085,
wdYoruba = 1130,
wdZulu = 1077,
}
const enum WdLanguageID2000 {
wdChineseHongKong = 3076,
wdChineseMacao = 5124,
wdEnglishTrinidad = 11273,
}
const enum WdLayoutMode {
wdLayoutModeDefault = 0,
wdLayoutModeGenko = 3,
wdLayoutModeGrid = 1,
wdLayoutModeLineGrid = 2,
}
const enum WdLetterheadLocation {
wdLetterBottom = 1,
wdLetterLeft = 2,
wdLetterRight = 3,
wdLetterTop = 0,
}
const enum WdLetterStyle {
wdFullBlock = 0,
wdModifiedBlock = 1,
wdSemiBlock = 2,
}
const enum WdLigatures {
wdLigaturesAll = 15,
wdLigaturesContextual = 2,
wdLigaturesContextualDiscretional = 10,
wdLigaturesContextualHistorical = 6,
wdLigaturesContextualHistoricalDiscretional = 14,
wdLigaturesDiscretional = 8,
wdLigaturesHistorical = 4,
wdLigaturesHistoricalDiscretional = 12,
wdLigaturesNone = 0,
wdLigaturesStandard = 1,
wdLigaturesStandardContextual = 3,
wdLigaturesStandardContextualDiscretional = 11,
wdLigaturesStandardContextualHistorical = 7,
wdLigaturesStandardDiscretional = 9,
wdLigaturesStandardHistorical = 5,
wdLigaturesStandardHistoricalDiscretional = 13,
}
const enum WdLineEndingType {
wdCRLF = 0,
wdCROnly = 1,
wdLFCR = 3,
wdLFOnly = 2,
wdLSPS = 4,
}
const enum WdLineSpacing {
wdLineSpace1pt5 = 1,
wdLineSpaceAtLeast = 3,
wdLineSpaceDouble = 2,
wdLineSpaceExactly = 4,
wdLineSpaceMultiple = 5,
wdLineSpaceSingle = 0,
}
const enum WdLineStyle {
wdLineStyleDashDot = 5,
wdLineStyleDashDotDot = 6,
wdLineStyleDashDotStroked = 20,
wdLineStyleDashLargeGap = 4,
wdLineStyleDashSmallGap = 3,
wdLineStyleDot = 2,
wdLineStyleDouble = 7,
wdLineStyleDoubleWavy = 19,
wdLineStyleEmboss3D = 21,
wdLineStyleEngrave3D = 22,
wdLineStyleInset = 24,
wdLineStyleNone = 0,
wdLineStyleOutset = 23,
wdLineStyleSingle = 1,
wdLineStyleSingleWavy = 18,
wdLineStyleThickThinLargeGap = 16,
wdLineStyleThickThinMedGap = 13,
wdLineStyleThickThinSmallGap = 10,
wdLineStyleThinThickLargeGap = 15,
wdLineStyleThinThickMedGap = 12,
wdLineStyleThinThickSmallGap = 9,
wdLineStyleThinThickThinLargeGap = 17,
wdLineStyleThinThickThinMedGap = 14,
wdLineStyleThinThickThinSmallGap = 11,
wdLineStyleTriple = 8,
}
const enum WdLineType {
wdTableRow = 1,
wdTextLine = 0,
}
const enum WdLineWidth {
wdLineWidth025pt = 2,
wdLineWidth050pt = 4,
wdLineWidth075pt = 6,
wdLineWidth100pt = 8,
wdLineWidth150pt = 12,
wdLineWidth225pt = 18,
wdLineWidth300pt = 24,
wdLineWidth450pt = 36,
wdLineWidth600pt = 48,
}
const enum WdLinkType {
wdLinkTypeChart = 8,
wdLinkTypeDDE = 6,
wdLinkTypeDDEAuto = 7,
wdLinkTypeImport = 5,
wdLinkTypeInclude = 4,
wdLinkTypeOLE = 0,
wdLinkTypePicture = 1,
wdLinkTypeReference = 3,
wdLinkTypeText = 2,
}
const enum WdListApplyTo {
wdListApplyToSelection = 2,
wdListApplyToThisPointForward = 1,
wdListApplyToWholeList = 0,
}
const enum WdListGalleryType {
wdBulletGallery = 1,
wdNumberGallery = 2,
wdOutlineNumberGallery = 3,
}
const enum WdListLevelAlignment {
wdListLevelAlignCenter = 1,
wdListLevelAlignLeft = 0,
wdListLevelAlignRight = 2,
}
const enum WdListNumberStyle {
wdListNumberStyleAiueo = 20,
wdListNumberStyleAiueoHalfWidth = 12,
wdListNumberStyleArabic = 0,
wdListNumberStyleArabic1 = 46,
wdListNumberStyleArabic2 = 48,
wdListNumberStyleArabicFullWidth = 14,
wdListNumberStyleArabicLZ = 22,
wdListNumberStyleArabicLZ2 = 62,
wdListNumberStyleArabicLZ3 = 63,
wdListNumberStyleArabicLZ4 = 64,
wdListNumberStyleBullet = 23,
wdListNumberStyleCardinalText = 6,
wdListNumberStyleChosung = 25,
wdListNumberStyleGanada = 24,
wdListNumberStyleGBNum1 = 26,
wdListNumberStyleGBNum2 = 27,
wdListNumberStyleGBNum3 = 28,
wdListNumberStyleGBNum4 = 29,
wdListNumberStyleHangul = 43,
wdListNumberStyleHanja = 44,
wdListNumberStyleHanjaRead = 41,
wdListNumberStyleHanjaReadDigit = 42,
wdListNumberStyleHebrew1 = 45,
wdListNumberStyleHebrew2 = 47,
wdListNumberStyleHindiArabic = 51,
wdListNumberStyleHindiCardinalText = 52,
wdListNumberStyleHindiLetter1 = 49,
wdListNumberStyleHindiLetter2 = 50,
wdListNumberStyleIroha = 21,
wdListNumberStyleIrohaHalfWidth = 13,
wdListNumberStyleKanji = 10,
wdListNumberStyleKanjiDigit = 11,
wdListNumberStyleKanjiTraditional = 16,
wdListNumberStyleKanjiTraditional2 = 17,
wdListNumberStyleLegal = 253,
wdListNumberStyleLegalLZ = 254,
wdListNumberStyleLowercaseBulgarian = 67,
wdListNumberStyleLowercaseGreek = 60,
wdListNumberStyleLowercaseLetter = 4,
wdListNumberStyleLowercaseRoman = 2,
wdListNumberStyleLowercaseRussian = 58,
wdListNumberStyleLowercaseTurkish = 65,
wdListNumberStyleNone = 255,
wdListNumberStyleNumberInCircle = 18,
wdListNumberStyleOrdinal = 5,
wdListNumberStyleOrdinalText = 7,
wdListNumberStylePictureBullet = 249,
wdListNumberStyleSimpChinNum1 = 37,
wdListNumberStyleSimpChinNum2 = 38,
wdListNumberStyleSimpChinNum3 = 39,
wdListNumberStyleSimpChinNum4 = 40,
wdListNumberStyleThaiArabic = 54,
wdListNumberStyleThaiCardinalText = 55,
wdListNumberStyleThaiLetter = 53,
wdListNumberStyleTradChinNum1 = 33,
wdListNumberStyleTradChinNum2 = 34,
wdListNumberStyleTradChinNum3 = 35,
wdListNumberStyleTradChinNum4 = 36,
wdListNumberStyleUppercaseBulgarian = 68,
wdListNumberStyleUppercaseGreek = 61,
wdListNumberStyleUppercaseLetter = 3,
wdListNumberStyleUppercaseRoman = 1,
wdListNumberStyleUppercaseRussian = 59,
wdListNumberStyleUppercaseTurkish = 66,
wdListNumberStyleVietCardinalText = 56,
wdListNumberStyleZodiac1 = 30,
wdListNumberStyleZodiac2 = 31,
wdListNumberStyleZodiac3 = 32,
}
const enum WdListNumberStyleHID {
emptyenum = 0,
}
const enum WdListType {
wdListBullet = 2,
wdListListNumOnly = 1,
wdListMixedNumbering = 5,
wdListNoNumbering = 0,
wdListOutlineNumbering = 4,
wdListPictureBullet = 6,
wdListSimpleNumbering = 3,
}
const enum WdLockType {
wdLockChanged = 3,
wdLockEphemeral = 2,
wdLockNone = 0,
wdLockReservation = 1,
}
const enum WdMailerPriority {
wdPriorityHigh = 3,
wdPriorityLow = 2,
wdPriorityNormal = 1,
}
const enum WdMailMergeActiveRecord {
wdFirstDataSourceRecord = -6,
wdFirstRecord = -4,
wdLastDataSourceRecord = -7,
wdLastRecord = -5,
wdNextDataSourceRecord = -8,
wdNextRecord = -2,
wdNoActiveRecord = -1,
wdPreviousDataSourceRecord = -9,
wdPreviousRecord = -3,
}
const enum WdMailMergeComparison {
wdMergeIfEqual = 0,
wdMergeIfGreaterThan = 3,
wdMergeIfGreaterThanOrEqual = 5,
wdMergeIfIsBlank = 6,
wdMergeIfIsNotBlank = 7,
wdMergeIfLessThan = 2,
wdMergeIfLessThanOrEqual = 4,
wdMergeIfNotEqual = 1,
}
const enum WdMailMergeDataSource {
wdMergeInfoFromAccessDDE = 1,
wdMergeInfoFromExcelDDE = 2,
wdMergeInfoFromMSQueryDDE = 3,
wdMergeInfoFromODBC = 4,
wdMergeInfoFromODSO = 5,
wdMergeInfoFromWord = 0,
wdNoMergeInfo = -1,
}
const enum WdMailMergeDefaultRecord {
wdDefaultFirstRecord = 1,
wdDefaultLastRecord = -16,
}
const enum WdMailMergeDestination {
wdSendToEmail = 2,
wdSendToFax = 3,
wdSendToNewDocument = 0,
wdSendToPrinter = 1,
}
const enum WdMailMergeMailFormat {
wdMailFormatHTML = 1,
wdMailFormatPlainText = 0,
}
const enum WdMailMergeMainDocType {
wdCatalog = 3,
wdDirectory = 3,
wdEMail = 4,
wdEnvelopes = 2,
wdFax = 5,
wdFormLetters = 0,
wdMailingLabels = 1,
wdNotAMergeDocument = -1,
}
const enum WdMailMergeState {
wdDataSource = 5,
wdMainAndDataSource = 2,
wdMainAndHeader = 3,
wdMainAndSourceAndHeader = 4,
wdMainDocumentOnly = 1,
wdNormalDocument = 0,
}
const enum WdMailSystem {
wdMAPI = 1,
wdMAPIandPowerTalk = 3,
wdNoMailSystem = 0,
wdPowerTalk = 2,
}
const enum WdMappedDataFields {
wdAddress1 = 10,
wdAddress2 = 11,
wdAddress3 = 29,
wdBusinessFax = 17,
wdBusinessPhone = 16,
wdCity = 12,
wdCompany = 9,
wdCountryRegion = 15,
wdCourtesyTitle = 2,
wdDepartment = 30,
wdEmailAddress = 20,
wdFirstName = 3,
wdHomeFax = 19,
wdHomePhone = 18,
wdJobTitle = 8,
wdLastName = 5,
wdMiddleName = 4,
wdNickname = 7,
wdPostalCode = 14,
wdRubyFirstName = 27,
wdRubyLastName = 28,
wdSpouseCourtesyTitle = 22,
wdSpouseFirstName = 23,
wdSpouseLastName = 25,
wdSpouseMiddleName = 24,
wdSpouseNickname = 26,
wdState = 13,
wdSuffix = 6,
wdUniqueIdentifier = 1,
wdWebPageURL = 21,
}
const enum WdMeasurementUnits {
wdCentimeters = 1,
wdInches = 0,
wdMillimeters = 2,
wdPicas = 4,
wdPoints = 3,
}
const enum WdMeasurementUnitsHID {
emptyenum = 0,
}
const enum WdMergeFormatFrom {
wdMergeFormatFromOriginal = 0,
wdMergeFormatFromPrompt = 2,
wdMergeFormatFromRevised = 1,
}
const enum WdMergeSubType {
wdMergeSubTypeAccess = 1,
wdMergeSubTypeOAL = 2,
wdMergeSubTypeOLEDBText = 5,
wdMergeSubTypeOLEDBWord = 3,
wdMergeSubTypeOther = 0,
wdMergeSubTypeOutlook = 6,
wdMergeSubTypeWord = 7,
wdMergeSubTypeWord2000 = 8,
wdMergeSubTypeWorks = 4,
}
const enum WdMergeTarget {
wdMergeTargetCurrent = 1,
wdMergeTargetNew = 2,
wdMergeTargetSelected = 0,
}
const enum WdMonthNames {
wdMonthNamesArabic = 0,
wdMonthNamesEnglish = 1,
wdMonthNamesFrench = 2,
}
const enum WdMoveFromTextMark {
wdMoveFromTextMarkBold = 6,
wdMoveFromTextMarkCaret = 3,
wdMoveFromTextMarkColorOnly = 10,
wdMoveFromTextMarkDoubleStrikeThrough = 1,
wdMoveFromTextMarkDoubleUnderline = 9,
wdMoveFromTextMarkHidden = 0,
wdMoveFromTextMarkItalic = 7,
wdMoveFromTextMarkNone = 5,
wdMoveFromTextMarkPound = 4,
wdMoveFromTextMarkStrikeThrough = 2,
wdMoveFromTextMarkUnderline = 8,
}
const enum WdMovementType {
wdExtend = 1,
wdMove = 0,
}
const enum WdMoveToTextMark {
wdMoveToTextMarkBold = 1,
wdMoveToTextMarkColorOnly = 5,
wdMoveToTextMarkDoubleStrikeThrough = 7,
wdMoveToTextMarkDoubleUnderline = 4,
wdMoveToTextMarkItalic = 2,
wdMoveToTextMarkNone = 0,
wdMoveToTextMarkStrikeThrough = 6,
wdMoveToTextMarkUnderline = 3,
}
const enum WdMultipleWordConversionsMode {
wdHangulToHanja = 0,
wdHanjaToHangul = 1,
}
const enum WdNewDocumentType {
wdNewBlankDocument = 0,
wdNewEmailMessage = 2,
wdNewFrameset = 3,
wdNewWebPage = 1,
wdNewXMLDocument = 4,
}
const enum WdNoteNumberStyle {
wdNoteNumberStyleArabic = 0,
wdNoteNumberStyleArabicFullWidth = 14,
wdNoteNumberStyleArabicLetter1 = 46,
wdNoteNumberStyleArabicLetter2 = 48,
wdNoteNumberStyleHanjaRead = 41,
wdNoteNumberStyleHanjaReadDigit = 42,
wdNoteNumberStyleHebrewLetter1 = 45,
wdNoteNumberStyleHebrewLetter2 = 47,
wdNoteNumberStyleHindiArabic = 51,
wdNoteNumberStyleHindiCardinalText = 52,
wdNoteNumberStyleHindiLetter1 = 49,
wdNoteNumberStyleHindiLetter2 = 50,
wdNoteNumberStyleKanji = 10,
wdNoteNumberStyleKanjiDigit = 11,
wdNoteNumberStyleKanjiTraditional = 16,
wdNoteNumberStyleLowercaseLetter = 4,
wdNoteNumberStyleLowercaseRoman = 2,
wdNoteNumberStyleNumberInCircle = 18,
wdNoteNumberStyleSimpChinNum1 = 37,
wdNoteNumberStyleSimpChinNum2 = 38,
wdNoteNumberStyleSymbol = 9,
wdNoteNumberStyleThaiArabic = 54,
wdNoteNumberStyleThaiCardinalText = 55,
wdNoteNumberStyleThaiLetter = 53,
wdNoteNumberStyleTradChinNum1 = 33,
wdNoteNumberStyleTradChinNum2 = 34,
wdNoteNumberStyleUppercaseLetter = 3,
wdNoteNumberStyleUppercaseRoman = 1,
wdNoteNumberStyleVietCardinalText = 56,
}
const enum WdNoteNumberStyleHID {
emptyenum = 0,
}
const enum WdNumberForm {
wdNumberFormDefault = 0,
wdNumberFormLining = 1,
wdNumberFormOldStyle = 2,
}
const enum WdNumberingRule {
wdRestartContinuous = 0,
wdRestartPage = 2,
wdRestartSection = 1,
}
const enum WdNumberSpacing {
wdNumberSpacingDefault = 0,
wdNumberSpacingProportional = 1,
wdNumberSpacingTabular = 2,
}
const enum WdNumberStyleWordBasicBiDi {
wdCaptionNumberStyleBidiLetter1 = 49,
wdCaptionNumberStyleBidiLetter2 = 50,
wdListNumberStyleBidi1 = 49,
wdListNumberStyleBidi2 = 50,
wdNoteNumberStyleBidiLetter1 = 49,
wdNoteNumberStyleBidiLetter2 = 50,
wdPageNumberStyleBidiLetter1 = 49,
wdPageNumberStyleBidiLetter2 = 50,
}
const enum WdNumberType {
wdNumberAllNumbers = 3,
wdNumberListNum = 2,
wdNumberParagraph = 1,
}
const enum WdOLEPlacement {
wdFloatOverText = 1,
wdInLine = 0,
}
const enum WdOLEType {
wdOLEControl = 2,
wdOLEEmbed = 1,
wdOLELink = 0,
}
const enum WdOLEVerb {
wdOLEVerbDiscardUndoState = -6,
wdOLEVerbHide = -3,
wdOLEVerbInPlaceActivate = -5,
wdOLEVerbOpen = -2,
wdOLEVerbPrimary = 0,
wdOLEVerbShow = -1,
wdOLEVerbUIActivate = -4,
}
const enum WdOMathBreakBin {
wdOMathBreakBinAfter = 1,
wdOMathBreakBinBefore = 0,
wdOMathBreakBinRepeat = 2,
}
const enum WdOMathBreakSub {
wdOMathBreakSubMinusMinus = 0,
wdOMathBreakSubMinusPlus = 2,
wdOMathBreakSubPlusMinus = 1,
}
const enum WdOMathFracType {
wdOMathFracBar = 0,
wdOMathFracLin = 3,
wdOMathFracNoBar = 1,
wdOMathFracSkw = 2,
}
const enum WdOMathFunctionType {
wdOMathFunctionAcc = 1,
wdOMathFunctionBar = 2,
wdOMathFunctionBorderBox = 4,
wdOMathFunctionBox = 3,
wdOMathFunctionDelim = 5,
wdOMathFunctionEqArray = 6,
wdOMathFunctionFrac = 7,
wdOMathFunctionFunc = 8,
wdOMathFunctionGroupChar = 9,
wdOMathFunctionLimLow = 10,
wdOMathFunctionLimUpp = 11,
wdOMathFunctionLiteralText = 22,
wdOMathFunctionMat = 12,
wdOMathFunctionNary = 13,
wdOMathFunctionNormalText = 21,
wdOMathFunctionPhantom = 14,
wdOMathFunctionRad = 16,
wdOMathFunctionScrPre = 15,
wdOMathFunctionScrSub = 17,
wdOMathFunctionScrSubSup = 18,
wdOMathFunctionScrSup = 19,
wdOMathFunctionText = 20,
}
const enum WdOMathHorizAlignType {
wdOMathHorizAlignCenter = 0,
wdOMathHorizAlignLeft = 1,
wdOMathHorizAlignRight = 2,
}
const enum WdOMathJc {
wdOMathJcCenter = 2,
wdOMathJcCenterGroup = 1,
wdOMathJcInline = 7,
wdOMathJcLeft = 3,
wdOMathJcRight = 4,
}
const enum WdOMathShapeType {
wdOMathShapeCentered = 0,
wdOMathShapeMatch = 1,
}
const enum WdOMathSpacingRule {
wdOMathSpacing1pt5 = 1,
wdOMathSpacingDouble = 2,
wdOMathSpacingExactly = 3,
wdOMathSpacingMultiple = 4,
wdOMathSpacingSingle = 0,
}
const enum WdOMathType {
wdOMathDisplay = 0,
wdOMathInline = 1,
}
const enum WdOMathVertAlignType {
wdOMathVertAlignBottom = 2,
wdOMathVertAlignCenter = 0,
wdOMathVertAlignTop = 1,
}
const enum WdOpenFormat {
wdOpenFormatAllWord = 6,
wdOpenFormatAllWordTemplates = 13,
wdOpenFormatAuto = 0,
wdOpenFormatDocument = 1,
wdOpenFormatDocument97 = 1,
wdOpenFormatEncodedText = 5,
wdOpenFormatOpenDocumentText = 18,
wdOpenFormatRTF = 3,
wdOpenFormatTemplate = 2,
wdOpenFormatTemplate97 = 2,
wdOpenFormatText = 4,
wdOpenFormatUnicodeText = 5,
wdOpenFormatWebPages = 7,
wdOpenFormatXML = 8,
wdOpenFormatXMLDocument = 9,
wdOpenFormatXMLDocumentMacroEnabled = 10,
wdOpenFormatXMLDocumentMacroEnabledSerialized = 15,
wdOpenFormatXMLDocumentSerialized = 14,
wdOpenFormatXMLTemplate = 11,
wdOpenFormatXMLTemplateMacroEnabled = 12,
wdOpenFormatXMLTemplateMacroEnabledSerialized = 17,
wdOpenFormatXMLTemplateSerialized = 16,
}
const enum WdOrganizerObject {
wdOrganizerObjectAutoText = 1,
wdOrganizerObjectCommandBars = 2,
wdOrganizerObjectProjectItems = 3,
wdOrganizerObjectStyles = 0,
}
const enum WdOrientation {
wdOrientLandscape = 1,
wdOrientPortrait = 0,
}
const enum WdOriginalFormat {
wdOriginalDocumentFormat = 1,
wdPromptUser = 2,
wdWordDocument = 0,
}
const enum WdOutlineLevel {
wdOutlineLevel1 = 1,
wdOutlineLevel2 = 2,
wdOutlineLevel3 = 3,
wdOutlineLevel4 = 4,
wdOutlineLevel5 = 5,
wdOutlineLevel6 = 6,
wdOutlineLevel7 = 7,
wdOutlineLevel8 = 8,
wdOutlineLevel9 = 9,
wdOutlineLevelBodyText = 10,
}
const enum WdPageBorderArt {
wdArtApples = 1,
wdArtArchedScallops = 97,
wdArtBabyPacifier = 70,
wdArtBabyRattle = 71,
wdArtBalloons3Colors = 11,
wdArtBalloonsHotAir = 12,
wdArtBasicBlackDashes = 155,
wdArtBasicBlackDots = 156,
wdArtBasicBlackSquares = 154,
wdArtBasicThinLines = 151,
wdArtBasicWhiteDashes = 152,
wdArtBasicWhiteDots = 147,
wdArtBasicWhiteSquares = 153,
wdArtBasicWideInline = 150,
wdArtBasicWideMidline = 148,
wdArtBasicWideOutline = 149,
wdArtBats = 37,
wdArtBirds = 102,
wdArtBirdsFlight = 35,
wdArtCabins = 72,
wdArtCakeSlice = 3,
wdArtCandyCorn = 4,
wdArtCelticKnotwork = 99,
wdArtCertificateBanner = 158,
wdArtChainLink = 128,
wdArtChampagneBottle = 6,
wdArtCheckedBarBlack = 145,
wdArtCheckedBarColor = 61,
wdArtCheckered = 144,
wdArtChristmasTree = 8,
wdArtCirclesLines = 91,
wdArtCirclesRectangles = 140,
wdArtClassicalWave = 56,
wdArtClocks = 27,
wdArtCompass = 54,
wdArtConfetti = 31,
wdArtConfettiGrays = 115,
wdArtConfettiOutline = 116,
wdArtConfettiStreamers = 14,
wdArtConfettiWhite = 117,
wdArtCornerTriangles = 141,
wdArtCouponCutoutDashes = 163,
wdArtCouponCutoutDots = 164,
wdArtCrazyMaze = 100,
wdArtCreaturesButterfly = 32,
wdArtCreaturesFish = 34,
wdArtCreaturesInsects = 142,
wdArtCreaturesLadyBug = 33,
wdArtCrossStitch = 138,
wdArtCup = 67,
wdArtDecoArch = 89,
wdArtDecoArchColor = 50,
wdArtDecoBlocks = 90,
wdArtDiamondsGray = 88,
wdArtDoubleD = 55,
wdArtDoubleDiamonds = 127,
wdArtEarth1 = 22,
wdArtEarth2 = 21,
wdArtEclipsingSquares1 = 101,
wdArtEclipsingSquares2 = 86,
wdArtEggsBlack = 66,
wdArtFans = 51,
wdArtFilm = 52,
wdArtFirecrackers = 28,
wdArtFlowersBlockPrint = 49,
wdArtFlowersDaisies = 48,
wdArtFlowersModern1 = 45,
wdArtFlowersModern2 = 44,
wdArtFlowersPansy = 43,
wdArtFlowersRedRose = 39,
wdArtFlowersRoses = 38,
wdArtFlowersTeacup = 103,
wdArtFlowersTiny = 42,
wdArtGems = 139,
wdArtGingerbreadMan = 69,
wdArtGradient = 122,
wdArtHandmade1 = 159,
wdArtHandmade2 = 160,
wdArtHeartBalloon = 16,
wdArtHeartGray = 68,
wdArtHearts = 15,
wdArtHeebieJeebies = 120,
wdArtHolly = 41,
wdArtHouseFunky = 73,
wdArtHypnotic = 87,
wdArtIceCreamCones = 5,
wdArtLightBulb = 121,
wdArtLightning1 = 53,
wdArtLightning2 = 119,
wdArtMapleLeaf = 81,
wdArtMapleMuffins = 2,
wdArtMapPins = 30,
wdArtMarquee = 146,
wdArtMarqueeToothed = 131,
wdArtMoons = 125,
wdArtMosaic = 118,
wdArtMusicNotes = 79,
wdArtNorthwest = 104,
wdArtOvals = 126,
wdArtPackages = 26,
wdArtPalmsBlack = 80,
wdArtPalmsColor = 10,
wdArtPaperClips = 82,
wdArtPapyrus = 92,
wdArtPartyFavor = 13,
wdArtPartyGlass = 7,
wdArtPencils = 25,
wdArtPeople = 84,
wdArtPeopleHats = 23,
wdArtPeopleWaving = 85,
wdArtPoinsettias = 40,
wdArtPostageStamp = 135,
wdArtPumpkin1 = 65,
wdArtPushPinNote1 = 63,
wdArtPushPinNote2 = 64,
wdArtPyramids = 113,
wdArtPyramidsAbove = 114,
wdArtQuadrants = 60,
wdArtRings = 29,
wdArtSafari = 98,
wdArtSawtooth = 133,
wdArtSawtoothGray = 134,
wdArtScaredCat = 36,
wdArtSeattle = 78,
wdArtShadowedSquares = 57,
wdArtSharksTeeth = 132,
wdArtShorebirdTracks = 83,
wdArtSkyrocket = 77,
wdArtSnowflakeFancy = 76,
wdArtSnowflakes = 75,
wdArtSombrero = 24,
wdArtSouthwest = 105,
wdArtStars = 19,
wdArtStars3D = 17,
wdArtStarsBlack = 74,
wdArtStarsShadowed = 18,
wdArtStarsTop = 157,
wdArtSun = 20,
wdArtSwirligig = 62,
wdArtTornPaper = 161,
wdArtTornPaperBlack = 162,
wdArtTrees = 9,
wdArtTriangleParty = 123,
wdArtTriangles = 129,
wdArtTribal1 = 130,
wdArtTribal2 = 109,
wdArtTribal3 = 108,
wdArtTribal4 = 107,
wdArtTribal5 = 110,
wdArtTribal6 = 106,
wdArtTwistedLines1 = 58,
wdArtTwistedLines2 = 124,
wdArtVine = 47,
wdArtWaveline = 59,
wdArtWeavingAngles = 96,
wdArtWeavingBraid = 94,
wdArtWeavingRibbon = 95,
wdArtWeavingStrips = 136,
wdArtWhiteFlowers = 46,
wdArtWoodwork = 93,
wdArtXIllusions = 111,
wdArtZanyTriangles = 112,
wdArtZigZag = 137,
wdArtZigZagStitch = 143,
}
const enum WdPageFit {
wdPageFitBestFit = 2,
wdPageFitFullPage = 1,
wdPageFitNone = 0,
wdPageFitTextFit = 3,
}
const enum WdPageNumberAlignment {
wdAlignPageNumberCenter = 1,
wdAlignPageNumberInside = 3,
wdAlignPageNumberLeft = 0,
wdAlignPageNumberOutside = 4,
wdAlignPageNumberRight = 2,
}
const enum WdPageNumberStyle {
wdPageNumberStyleArabic = 0,
wdPageNumberStyleArabicFullWidth = 14,
wdPageNumberStyleArabicLetter1 = 46,
wdPageNumberStyleArabicLetter2 = 48,
wdPageNumberStyleHanjaRead = 41,
wdPageNumberStyleHanjaReadDigit = 42,
wdPageNumberStyleHebrewLetter1 = 45,
wdPageNumberStyleHebrewLetter2 = 47,
wdPageNumberStyleHindiArabic = 51,
wdPageNumberStyleHindiCardinalText = 52,
wdPageNumberStyleHindiLetter1 = 49,
wdPageNumberStyleHindiLetter2 = 50,
wdPageNumberStyleKanji = 10,
wdPageNumberStyleKanjiDigit = 11,
wdPageNumberStyleKanjiTraditional = 16,
wdPageNumberStyleLowercaseLetter = 4,
wdPageNumberStyleLowercaseRoman = 2,
wdPageNumberStyleNumberInCircle = 18,
wdPageNumberStyleNumberInDash = 57,
wdPageNumberStyleSimpChinNum1 = 37,
wdPageNumberStyleSimpChinNum2 = 38,
wdPageNumberStyleThaiArabic = 54,
wdPageNumberStyleThaiCardinalText = 55,
wdPageNumberStyleThaiLetter = 53,
wdPageNumberStyleTradChinNum1 = 33,
wdPageNumberStyleTradChinNum2 = 34,
wdPageNumberStyleUppercaseLetter = 3,
wdPageNumberStyleUppercaseRoman = 1,
wdPageNumberStyleVietCardinalText = 56,
}
const enum WdPageNumberStyleHID {
emptyenum = 0,
}
const enum WdPaperSize {
wdPaper10x14 = 0,
wdPaper11x17 = 1,
wdPaperA3 = 6,
wdPaperA4 = 7,
wdPaperA4Small = 8,
wdPaperA5 = 9,
wdPaperB4 = 10,
wdPaperB5 = 11,
wdPaperCSheet = 12,
wdPaperCustom = 41,
wdPaperDSheet = 13,
wdPaperEnvelope10 = 25,
wdPaperEnvelope11 = 26,
wdPaperEnvelope12 = 27,
wdPaperEnvelope14 = 28,
wdPaperEnvelope9 = 24,
wdPaperEnvelopeB4 = 29,
wdPaperEnvelopeB5 = 30,
wdPaperEnvelopeB6 = 31,
wdPaperEnvelopeC3 = 32,
wdPaperEnvelopeC4 = 33,
wdPaperEnvelopeC5 = 34,
wdPaperEnvelopeC6 = 35,
wdPaperEnvelopeC65 = 36,
wdPaperEnvelopeDL = 37,
wdPaperEnvelopeItaly = 38,
wdPaperEnvelopeMonarch = 39,
wdPaperEnvelopePersonal = 40,
wdPaperESheet = 14,
wdPaperExecutive = 5,
wdPaperFanfoldLegalGerman = 15,
wdPaperFanfoldStdGerman = 16,
wdPaperFanfoldUS = 17,
wdPaperFolio = 18,
wdPaperLedger = 19,
wdPaperLegal = 4,
wdPaperLetter = 2,
wdPaperLetterSmall = 3,
wdPaperNote = 20,
wdPaperQuarto = 21,
wdPaperStatement = 22,
wdPaperTabloid = 23,
}
const enum WdPaperTray {
wdPrinterAutomaticSheetFeed = 7,
wdPrinterDefaultBin = 0,
wdPrinterEnvelopeFeed = 5,
wdPrinterFormSource = 15,
wdPrinterLargeCapacityBin = 11,
wdPrinterLargeFormatBin = 10,
wdPrinterLowerBin = 2,
wdPrinterManualEnvelopeFeed = 6,
wdPrinterManualFeed = 4,
wdPrinterMiddleBin = 3,
wdPrinterOnlyBin = 1,
wdPrinterPaperCassette = 14,
wdPrinterSmallFormatBin = 9,
wdPrinterTractorFeed = 8,
wdPrinterUpperBin = 1,
}
const enum WdParagraphAlignment {
wdAlignParagraphCenter = 1,
wdAlignParagraphDistribute = 4,
wdAlignParagraphJustify = 3,
wdAlignParagraphJustifyHi = 7,
wdAlignParagraphJustifyLow = 8,
wdAlignParagraphJustifyMed = 5,
wdAlignParagraphLeft = 0,
wdAlignParagraphRight = 2,
wdAlignParagraphThaiJustify = 9,
}
const enum WdParagraphAlignmentHID {
emptyenum = 0,
}
const enum WdPartOfSpeech {
wdAdjective = 0,
wdAdverb = 2,
wdConjunction = 5,
wdIdiom = 8,
wdInterjection = 7,
wdNoun = 1,
wdOther = 9,
wdPreposition = 6,
wdPronoun = 4,
wdVerb = 3,
}
const enum WdPasteDataType {
wdPasteBitmap = 4,
wdPasteDeviceIndependentBitmap = 5,
wdPasteEnhancedMetafile = 9,
wdPasteHTML = 10,
wdPasteHyperlink = 7,
wdPasteMetafilePicture = 3,
wdPasteOLEObject = 0,
wdPasteRTF = 1,
wdPasteShape = 8,
wdPasteText = 2,
}
const enum WdPasteOptions {
wdKeepSourceFormatting = 0,
wdKeepTextOnly = 2,
wdMatchDestinationFormatting = 1,
wdUseDestinationStyles = 3,
}
const enum WdPhoneticGuideAlignmentType {
wdPhoneticGuideAlignmentCenter = 0,
wdPhoneticGuideAlignmentLeft = 3,
wdPhoneticGuideAlignmentOneTwoOne = 2,
wdPhoneticGuideAlignmentRight = 4,
wdPhoneticGuideAlignmentRightVertical = 5,
wdPhoneticGuideAlignmentZeroOneZero = 1,
}
const enum WdPictureLinkType {
wdLinkDataInDoc = 1,
wdLinkDataOnDisk = 2,
wdLinkNone = 0,
}
const enum WdPortugueseReform {
wdPortugueseBoth = 3,
wdPortuguesePostReform = 2,
wdPortuguesePreReform = 1,
}
const enum WdPreferredWidthType {
wdPreferredWidthAuto = 1,
wdPreferredWidthPercent = 2,
wdPreferredWidthPoints = 3,
}
const enum WdPrintOutItem {
wdPrintAutoTextEntries = 4,
wdPrintComments = 2,
wdPrintDocumentContent = 0,
wdPrintDocumentWithMarkup = 7,
wdPrintEnvelope = 6,
wdPrintKeyAssignments = 5,
wdPrintMarkup = 2,
wdPrintProperties = 1,
wdPrintStyles = 3,
}
const enum WdPrintOutPages {
wdPrintAllPages = 0,
wdPrintEvenPagesOnly = 2,
wdPrintOddPagesOnly = 1,
}
const enum WdPrintOutRange {
wdPrintAllDocument = 0,
wdPrintCurrentPage = 2,
wdPrintFromTo = 3,
wdPrintRangeOfPages = 4,
wdPrintSelection = 1,
}
const enum WdProofreadingErrorType {
wdGrammaticalError = 1,
wdSpellingError = 0,
}
const enum WdProtectedViewCloseReason {
wdProtectedViewCloseEdit = 1,
wdProtectedViewCloseForced = 2,
wdProtectedViewCloseNormal = 0,
}
const enum WdProtectionType {
wdAllowOnlyComments = 1,
wdAllowOnlyFormFields = 2,
wdAllowOnlyReading = 3,
wdAllowOnlyRevisions = 0,
wdNoProtection = -1,
}
const enum WdReadingLayoutMargin {
wdAutomaticMargin = 0,
wdFullMargin = 2,
wdSuppressMargin = 1,
}
const enum WdReadingOrder {
wdReadingOrderLtr = 1,
wdReadingOrderRtl = 0,
}
const enum WdRecoveryType {
wdChart = 14,
wdChartLinked = 15,
wdChartPicture = 13,
wdFormatOriginalFormatting = 16,
wdFormatPlainText = 22,
wdFormatSurroundingFormattingWithEmphasis = 20,
wdListCombineWithExistingList = 24,
wdListContinueNumbering = 7,
wdListDontMerge = 25,
wdListRestartNumbering = 8,
wdPasteDefault = 0,
wdSingleCellTable = 6,
wdSingleCellText = 5,
wdTableAppendTable = 10,
wdTableInsertAsRows = 11,
wdTableOriginalFormatting = 12,
wdTableOverwriteCells = 23,
wdUseDestinationStylesRecovery = 19,
}
const enum WdRectangleType {
wdDocumentControlRectangle = 13,
wdLineBetweenColumnRectangle = 5,
wdMailNavArea = 12,
wdMarkupRectangle = 2,
wdMarkupRectangleArea = 8,
wdMarkupRectangleButton = 3,
wdMarkupRectangleMoveMatch = 10,
wdPageBorderRectangle = 4,
wdReadingModeNavigation = 9,
wdReadingModePanningArea = 11,
wdSelection = 6,
wdShapeRectangle = 1,
wdSystem = 7,
wdTextRectangle = 0,
}
const enum WdReferenceKind {
wdContentText = -1,
wdEndnoteNumber = 6,
wdEndnoteNumberFormatted = 17,
wdEntireCaption = 2,
wdFootnoteNumber = 5,
wdFootnoteNumberFormatted = 16,
wdNumberFullContext = -4,
wdNumberNoContext = -3,
wdNumberRelativeContext = -2,
wdOnlyCaptionText = 4,
wdOnlyLabelAndNumber = 3,
wdPageNumber = 7,
wdPosition = 15,
}
const enum WdReferenceType {
wdRefTypeBookmark = 2,
wdRefTypeEndnote = 4,
wdRefTypeFootnote = 3,
wdRefTypeHeading = 1,
wdRefTypeNumberedItem = 0,
}
const enum WdRelativeHorizontalPosition {
wdRelativeHorizontalPositionCharacter = 3,
wdRelativeHorizontalPositionColumn = 2,
wdRelativeHorizontalPositionInnerMarginArea = 6,
wdRelativeHorizontalPositionLeftMarginArea = 4,
wdRelativeHorizontalPositionMargin = 0,
wdRelativeHorizontalPositionOuterMarginArea = 7,
wdRelativeHorizontalPositionPage = 1,
wdRelativeHorizontalPositionRightMarginArea = 5,
}
const enum WdRelativeHorizontalSize {
wdRelativeHorizontalSizeInnerMarginArea = 4,
wdRelativeHorizontalSizeLeftMarginArea = 2,
wdRelativeHorizontalSizeMargin = 0,
wdRelativeHorizontalSizeOuterMarginArea = 5,
wdRelativeHorizontalSizePage = 1,
wdRelativeHorizontalSizeRightMarginArea = 3,
}
const enum WdRelativeVerticalPosition {
wdRelativeVerticalPositionBottomMarginArea = 5,
wdRelativeVerticalPositionInnerMarginArea = 6,
wdRelativeVerticalPositionLine = 3,
wdRelativeVerticalPositionMargin = 0,
wdRelativeVerticalPositionOuterMarginArea = 7,
wdRelativeVerticalPositionPage = 1,
wdRelativeVerticalPositionParagraph = 2,
wdRelativeVerticalPositionTopMarginArea = 4,
}
const enum WdRelativeVerticalSize {
wdRelativeVerticalSizeBottomMarginArea = 3,
wdRelativeVerticalSizeInnerMarginArea = 4,
wdRelativeVerticalSizeMargin = 0,
wdRelativeVerticalSizeOuterMarginArea = 5,
wdRelativeVerticalSizePage = 1,
wdRelativeVerticalSizeTopMarginArea = 2,
}
const enum WdRelocate {
wdRelocateDown = 1,
wdRelocateUp = 0,
}
const enum WdRemoveDocInfoType {
wdRDIAll = 99,
wdRDIComments = 1,
wdRDIContentType = 16,
wdRDIDocumentManagementPolicy = 15,
wdRDIDocumentProperties = 8,
wdRDIDocumentServerProperties = 14,
wdRDIDocumentWorkspace = 10,
wdRDIEmailHeader = 5,
wdRDIInkAnnotations = 11,
wdRDIRemovePersonalInformation = 4,
wdRDIRevisions = 2,
wdRDIRoutingSlip = 6,
wdRDISendForReview = 7,
wdRDITemplate = 9,
wdRDIVersions = 3,
}
const enum WdReplace {
wdReplaceAll = 2,
wdReplaceNone = 0,
wdReplaceOne = 1,
}
const enum WdRevisedLinesMark {
wdRevisedLinesMarkLeftBorder = 1,
wdRevisedLinesMarkNone = 0,
wdRevisedLinesMarkOutsideBorder = 3,
wdRevisedLinesMarkRightBorder = 2,
}
const enum WdRevisedPropertiesMark {
wdRevisedPropertiesMarkBold = 1,
wdRevisedPropertiesMarkColorOnly = 5,
wdRevisedPropertiesMarkDoubleStrikeThrough = 7,
wdRevisedPropertiesMarkDoubleUnderline = 4,
wdRevisedPropertiesMarkItalic = 2,
wdRevisedPropertiesMarkNone = 0,
wdRevisedPropertiesMarkStrikeThrough = 6,
wdRevisedPropertiesMarkUnderline = 3,
}
const enum WdRevisionsBalloonMargin {
wdLeftMargin = 0,
wdRightMargin = 1,
}
const enum WdRevisionsBalloonPrintOrientation {
wdBalloonPrintOrientationAuto = 0,
wdBalloonPrintOrientationForceLandscape = 2,
wdBalloonPrintOrientationPreserve = 1,
}
const enum WdRevisionsBalloonWidthType {
wdBalloonWidthPercent = 0,
wdBalloonWidthPoints = 1,
}
const enum WdRevisionsMode {
wdBalloonRevisions = 0,
wdInLineRevisions = 1,
wdMixedRevisions = 2,
}
const enum WdRevisionsView {
wdRevisionsViewFinal = 0,
wdRevisionsViewOriginal = 1,
}
const enum WdRevisionsWrap {
wdWrapAlways = 1,
wdWrapAsk = 2,
wdWrapNever = 0,
}
const enum WdRevisionType {
wdNoRevision = 0,
wdRevisionCellDeletion = 17,
wdRevisionCellInsertion = 16,
wdRevisionCellMerge = 18,
wdRevisionCellSplit = 19,
wdRevisionConflict = 7,
wdRevisionConflictDelete = 21,
wdRevisionConflictInsert = 20,
wdRevisionDelete = 2,
wdRevisionDisplayField = 5,
wdRevisionInsert = 1,
wdRevisionMovedFrom = 14,
wdRevisionMovedTo = 15,
wdRevisionParagraphNumber = 4,
wdRevisionParagraphProperty = 10,
wdRevisionProperty = 3,
wdRevisionReconcile = 6,
wdRevisionReplace = 9,
wdRevisionSectionProperty = 12,
wdRevisionStyle = 8,
wdRevisionStyleDefinition = 13,
wdRevisionTableProperty = 11,
}
const enum WdRoutingSlipDelivery {
wdAllAtOnce = 1,
wdOneAfterAnother = 0,
}
const enum WdRoutingSlipStatus {
wdNotYetRouted = 0,
wdRouteComplete = 2,
wdRouteInProgress = 1,
}
const enum WdRowAlignment {
wdAlignRowCenter = 1,
wdAlignRowLeft = 0,
wdAlignRowRight = 2,
}
const enum WdRowHeightRule {
wdRowHeightAtLeast = 1,
wdRowHeightAuto = 0,
wdRowHeightExactly = 2,
}
const enum WdRulerStyle {
wdAdjustFirstColumn = 2,
wdAdjustNone = 0,
wdAdjustProportional = 1,
wdAdjustSameWidth = 3,
}
const enum WdSalutationGender {
wdGenderFemale = 0,
wdGenderMale = 1,
wdGenderNeutral = 2,
wdGenderUnknown = 3,
}
const enum WdSalutationType {
wdSalutationBusiness = 2,
wdSalutationFormal = 1,
wdSalutationInformal = 0,
wdSalutationOther = 3,
}
const enum WdSaveFormat {
wdFormatDocument = 0,
wdFormatDocument97 = 0,
wdFormatDocumentDefault = 16,
wdFormatDOSText = 4,
wdFormatDOSTextLineBreaks = 5,
wdFormatEncodedText = 7,
wdFormatFilteredHTML = 10,
wdFormatFlatXML = 19,
wdFormatFlatXMLMacroEnabled = 20,
wdFormatFlatXMLTemplate = 21,
wdFormatFlatXMLTemplateMacroEnabled = 22,
wdFormatHTML = 8,
wdFormatOpenDocumentText = 23,
wdFormatPDF = 17,
wdFormatRTF = 6,
wdFormatTemplate = 1,
wdFormatTemplate97 = 1,
wdFormatText = 2,
wdFormatTextLineBreaks = 3,
wdFormatUnicodeText = 7,
wdFormatWebArchive = 9,
wdFormatXML = 11,
wdFormatXMLDocument = 12,
wdFormatXMLDocumentMacroEnabled = 13,
wdFormatXMLTemplate = 14,
wdFormatXMLTemplateMacroEnabled = 15,
wdFormatXPS = 18,
}
const enum WdSaveOptions {
wdDoNotSaveChanges = 0,
wdPromptToSaveChanges = -2,
wdSaveChanges = -1,
}
const enum WdScrollbarType {
wdScrollbarTypeAuto = 0,
wdScrollbarTypeNo = 2,
wdScrollbarTypeYes = 1,
}
const enum WdSectionDirection {
wdSectionDirectionLtr = 1,
wdSectionDirectionRtl = 0,
}
const enum WdSectionStart {
wdSectionContinuous = 0,
wdSectionEvenPage = 3,
wdSectionNewColumn = 1,
wdSectionNewPage = 2,
wdSectionOddPage = 4,
}
const enum WdSeekView {
wdSeekCurrentPageFooter = 10,
wdSeekCurrentPageHeader = 9,
wdSeekEndnotes = 8,
wdSeekEvenPagesFooter = 6,
wdSeekEvenPagesHeader = 3,
wdSeekFirstPageFooter = 5,
wdSeekFirstPageHeader = 2,
wdSeekFootnotes = 7,
wdSeekMainDocument = 0,
wdSeekPrimaryFooter = 4,
wdSeekPrimaryHeader = 1,
}
const enum WdSelectionFlags {
wdSelActive = 8,
wdSelAtEOL = 2,
wdSelOvertype = 4,
wdSelReplace = 16,
wdSelStartActive = 1,
}
const enum WdSelectionType {
wdNoSelection = 0,
wdSelectionBlock = 6,
wdSelectionColumn = 4,
wdSelectionFrame = 3,
wdSelectionInlineShape = 7,
wdSelectionIP = 1,
wdSelectionNormal = 2,
wdSelectionRow = 5,
wdSelectionShape = 8,
}
const enum WdSeparatorType {
wdSeparatorColon = 2,
wdSeparatorEmDash = 3,
wdSeparatorEnDash = 4,
wdSeparatorHyphen = 0,
wdSeparatorPeriod = 1,
}
const enum WdShapePosition {
wdShapeBottom = -999997,
wdShapeCenter = -999995,
wdShapeInside = -999994,
wdShapeLeft = -999998,
wdShapeOutside = -999993,
wdShapeRight = -999996,
wdShapeTop = -999999,
}
const enum WdShapePositionRelative {
wdShapePositionRelativeNone = -999999,
}
const enum WdShapeSizeRelative {
wdShapeSizeRelativeNone = -999999,
}
const enum WdShowFilter {
wdShowFilterFormattingAvailable = 4,
wdShowFilterFormattingInUse = 3,
wdShowFilterFormattingRecommended = 5,
wdShowFilterStylesAll = 2,
wdShowFilterStylesAvailable = 0,
wdShowFilterStylesInUse = 1,
}
const enum WdShowSourceDocuments {
wdShowSourceDocumentsBoth = 3,
wdShowSourceDocumentsNone = 0,
wdShowSourceDocumentsOriginal = 1,
wdShowSourceDocumentsRevised = 2,
}
const enum WdSmartTagControlType {
wdControlActiveX = 13,
wdControlButton = 6,
wdControlCheckbox = 9,
wdControlCombo = 12,
wdControlDocumentFragment = 14,
wdControlDocumentFragmentURL = 15,
wdControlHelp = 3,
wdControlHelpURL = 4,
wdControlImage = 8,
wdControlLabel = 7,
wdControlLink = 2,
wdControlListbox = 11,
wdControlRadioGroup = 16,
wdControlSeparator = 5,
wdControlSmartTag = 1,
wdControlTextbox = 10,
}
const enum WdSortFieldType {
wdSortFieldAlphanumeric = 0,
wdSortFieldDate = 2,
wdSortFieldJapanJIS = 4,
wdSortFieldKoreaKS = 6,
wdSortFieldNumeric = 1,
wdSortFieldStroke = 5,
wdSortFieldSyllable = 3,
}
const enum WdSortFieldTypeHID {
emptyenum = 0,
}
const enum WdSortOrder {
wdSortOrderAscending = 0,
wdSortOrderDescending = 1,
}
const enum WdSortSeparator {
wdSortSeparateByCommas = 1,
wdSortSeparateByDefaultTableSeparator = 2,
wdSortSeparateByTabs = 0,
}
const enum WdSpanishSpeller {
wdSpanishTuteoAndVoseo = 1,
wdSpanishTuteoOnly = 0,
wdSpanishVoseoOnly = 2,
}
const enum WdSpecialPane {
wdPaneComments = 15,
wdPaneCurrentPageFooter = 17,
wdPaneCurrentPageHeader = 16,
wdPaneEndnoteContinuationNotice = 12,
wdPaneEndnoteContinuationSeparator = 13,
wdPaneEndnotes = 8,
wdPaneEndnoteSeparator = 14,
wdPaneEvenPagesFooter = 6,
wdPaneEvenPagesHeader = 3,
wdPaneFirstPageFooter = 5,
wdPaneFirstPageHeader = 2,
wdPaneFootnoteContinuationNotice = 9,
wdPaneFootnoteContinuationSeparator = 10,
wdPaneFootnotes = 7,
wdPaneFootnoteSeparator = 11,
wdPaneNone = 0,
wdPanePrimaryFooter = 4,
wdPanePrimaryHeader = 1,
wdPaneRevisions = 18,
wdPaneRevisionsHoriz = 19,
wdPaneRevisionsVert = 20,
}
const enum WdSpellingErrorType {
wdSpellingCapitalization = 2,
wdSpellingCorrect = 0,
wdSpellingNotInDictionary = 1,
}
const enum WdSpellingWordType {
wdAnagram = 2,
wdSpellword = 0,
wdWildcard = 1,
}
const enum WdStatistic {
wdStatisticCharacters = 3,
wdStatisticCharactersWithSpaces = 5,
wdStatisticFarEastCharacters = 6,
wdStatisticLines = 1,
wdStatisticPages = 2,
wdStatisticParagraphs = 4,
wdStatisticWords = 0,
}
const enum WdStatisticHID {
emptyenum = 0,
}
const enum WdStoryType {
wdCommentsStory = 4,
wdEndnoteContinuationNoticeStory = 17,
wdEndnoteContinuationSeparatorStory = 16,
wdEndnoteSeparatorStory = 15,
wdEndnotesStory = 3,
wdEvenPagesFooterStory = 8,
wdEvenPagesHeaderStory = 6,
wdFirstPageFooterStory = 11,
wdFirstPageHeaderStory = 10,
wdFootnoteContinuationNoticeStory = 14,
wdFootnoteContinuationSeparatorStory = 13,
wdFootnoteSeparatorStory = 12,
wdFootnotesStory = 2,
wdMainTextStory = 1,
wdPrimaryFooterStory = 9,
wdPrimaryHeaderStory = 7,
wdTextFrameStory = 5,
}
const enum WdStyleSheetLinkType {
wdStyleSheetLinkTypeImported = 1,
wdStyleSheetLinkTypeLinked = 0,
}
const enum WdStyleSheetPrecedence {
wdStyleSheetPrecedenceHigher = -1,
wdStyleSheetPrecedenceHighest = 1,
wdStyleSheetPrecedenceLower = -2,
wdStyleSheetPrecedenceLowest = 0,
}
const enum WdStyleSort {
wdStyleSortByBasedOn = 3,
wdStyleSortByFont = 2,
wdStyleSortByName = 0,
wdStyleSortByType = 4,
wdStyleSortRecommended = 1,
}
const enum WdStyleType {
wdStyleTypeCharacter = 2,
wdStyleTypeLinked = 6,
wdStyleTypeList = 4,
wdStyleTypeParagraph = 1,
wdStyleTypeParagraphOnly = 5,
wdStyleTypeTable = 3,
}
const enum WdStylisticSet {
wdStylisticSet01 = 1,
wdStylisticSet02 = 2,
wdStylisticSet03 = 4,
wdStylisticSet04 = 8,
wdStylisticSet05 = 16,
wdStylisticSet06 = 32,
wdStylisticSet07 = 64,
wdStylisticSet08 = 128,
wdStylisticSet09 = 256,
wdStylisticSet10 = 512,
wdStylisticSet11 = 1024,
wdStylisticSet12 = 2048,
wdStylisticSet13 = 4096,
wdStylisticSet14 = 8192,
wdStylisticSet15 = 16384,
wdStylisticSet16 = 32768,
wdStylisticSet17 = 65536,
wdStylisticSet18 = 131072,
wdStylisticSet19 = 262144,
wdStylisticSet20 = 524288,
wdStylisticSetDefault = 0,
}
const enum WdSubscriberFormats {
wdSubscriberBestFormat = 0,
wdSubscriberPict = 4,
wdSubscriberRTF = 1,
wdSubscriberText = 2,
}
const enum WdSummaryLength {
wd100Words = -4,
wd10Percent = -6,
wd10Sentences = -2,
wd20Sentences = -3,
wd25Percent = -7,
wd500Words = -5,
wd50Percent = -8,
wd75Percent = -9,
}
const enum WdSummaryMode {
wdSummaryModeCreateNew = 3,
wdSummaryModeHideAllButSummary = 1,
wdSummaryModeHighlight = 0,
wdSummaryModeInsert = 2,
}
const enum WdTabAlignment {
wdAlignTabBar = 4,
wdAlignTabCenter = 1,
wdAlignTabDecimal = 3,
wdAlignTabLeft = 0,
wdAlignTabList = 6,
wdAlignTabRight = 2,
}
const enum WdTabLeader {
wdTabLeaderDashes = 2,
wdTabLeaderDots = 1,
wdTabLeaderHeavy = 4,
wdTabLeaderLines = 3,
wdTabLeaderMiddleDot = 5,
wdTabLeaderSpaces = 0,
}
const enum WdTabLeaderHID {
emptyenum = 0,
}
const enum WdTableDirection {
wdTableDirectionLtr = 1,
wdTableDirectionRtl = 0,
}
const enum WdTableFieldSeparator {
wdSeparateByCommas = 2,
wdSeparateByDefaultListSeparator = 3,
wdSeparateByParagraphs = 0,
wdSeparateByTabs = 1,
}
const enum WdTableFormat {
wdTableFormat3DEffects1 = 32,
wdTableFormat3DEffects2 = 33,
wdTableFormat3DEffects3 = 34,
wdTableFormatClassic1 = 4,
wdTableFormatClassic2 = 5,
wdTableFormatClassic3 = 6,
wdTableFormatClassic4 = 7,
wdTableFormatColorful1 = 8,
wdTableFormatColorful2 = 9,
wdTableFormatColorful3 = 10,
wdTableFormatColumns1 = 11,
wdTableFormatColumns2 = 12,
wdTableFormatColumns3 = 13,
wdTableFormatColumns4 = 14,
wdTableFormatColumns5 = 15,
wdTableFormatContemporary = 35,
wdTableFormatElegant = 36,
wdTableFormatGrid1 = 16,
wdTableFormatGrid2 = 17,
wdTableFormatGrid3 = 18,
wdTableFormatGrid4 = 19,
wdTableFormatGrid5 = 20,
wdTableFormatGrid6 = 21,
wdTableFormatGrid7 = 22,
wdTableFormatGrid8 = 23,
wdTableFormatList1 = 24,
wdTableFormatList2 = 25,
wdTableFormatList3 = 26,
wdTableFormatList4 = 27,
wdTableFormatList5 = 28,
wdTableFormatList6 = 29,
wdTableFormatList7 = 30,
wdTableFormatList8 = 31,
wdTableFormatNone = 0,
wdTableFormatProfessional = 37,
wdTableFormatSimple1 = 1,
wdTableFormatSimple2 = 2,
wdTableFormatSimple3 = 3,
wdTableFormatSubtle1 = 38,
wdTableFormatSubtle2 = 39,
wdTableFormatWeb1 = 40,
wdTableFormatWeb2 = 41,
wdTableFormatWeb3 = 42,
}
const enum WdTableFormatApply {
wdTableFormatApplyAutoFit = 16,
wdTableFormatApplyBorders = 1,
wdTableFormatApplyColor = 8,
wdTableFormatApplyFirstColumn = 128,
wdTableFormatApplyFont = 4,
wdTableFormatApplyHeadingRows = 32,
wdTableFormatApplyLastColumn = 256,
wdTableFormatApplyLastRow = 64,
wdTableFormatApplyShading = 2,
}
const enum WdTablePosition {
wdTableBottom = -999997,
wdTableCenter = -999995,
wdTableInside = -999994,
wdTableLeft = -999998,
wdTableOutside = -999993,
wdTableRight = -999996,
wdTableTop = -999999,
}
const enum WdTaskPanes {
wdTaskPaneApplyStyles = 17,
wdTaskPaneDocumentActions = 7,
wdTaskPaneDocumentManagement = 16,
wdTaskPaneDocumentProtection = 6,
wdTaskPaneDocumentUpdates = 13,
wdTaskPaneFaxService = 11,
wdTaskPaneFormatting = 0,
wdTaskPaneHelp = 9,
wdTaskPaneMailMerge = 2,
wdTaskPaneNav = 18,
wdTaskPaneResearch = 10,
wdTaskPaneRevealFormatting = 1,
wdTaskPaneSearch = 4,
wdTaskPaneSelection = 19,
wdTaskPaneSharedWorkspace = 8,
wdTaskPaneSignature = 14,
wdTaskPaneStyleInspector = 15,
wdTaskPaneTranslate = 3,
wdTaskPaneXMLDocument = 12,
wdTaskPaneXMLStructure = 5,
}
const enum WdTCSCConverterDirection {
wdTCSCConverterDirectionAuto = 2,
wdTCSCConverterDirectionSCTC = 0,
wdTCSCConverterDirectionTCSC = 1,
}
const enum WdTemplateType {
wdAttachedTemplate = 2,
wdGlobalTemplate = 1,
wdNormalTemplate = 0,
}
const enum WdTextboxTightWrap {
wdTightAll = 1,
wdTightFirstAndLastLines = 2,
wdTightFirstLineOnly = 3,
wdTightLastLineOnly = 4,
wdTightNone = 0,
}
const enum WdTextFormFieldType {
wdCalculationText = 5,
wdCurrentDateText = 3,
wdCurrentTimeText = 4,
wdDateText = 2,
wdNumberText = 1,
wdRegularText = 0,
}
const enum WdTextOrientation {
wdTextOrientationDownward = 3,
wdTextOrientationHorizontal = 0,
wdTextOrientationHorizontalRotatedFarEast = 4,
wdTextOrientationUpward = 2,
wdTextOrientationVertical = 5,
wdTextOrientationVerticalFarEast = 1,
}
const enum WdTextOrientationHID {
emptyenum = 0,
}
const enum WdTextureIndex {
wdTexture10Percent = 100,
wdTexture12Pt5Percent = 125,
wdTexture15Percent = 150,
wdTexture17Pt5Percent = 175,
wdTexture20Percent = 200,
wdTexture22Pt5Percent = 225,
wdTexture25Percent = 250,
wdTexture27Pt5Percent = 275,
wdTexture2Pt5Percent = 25,
wdTexture30Percent = 300,
wdTexture32Pt5Percent = 325,
wdTexture35Percent = 350,
wdTexture37Pt5Percent = 375,
wdTexture40Percent = 400,
wdTexture42Pt5Percent = 425,
wdTexture45Percent = 450,
wdTexture47Pt5Percent = 475,
wdTexture50Percent = 500,
wdTexture52Pt5Percent = 525,
wdTexture55Percent = 550,
wdTexture57Pt5Percent = 575,
wdTexture5Percent = 50,
wdTexture60Percent = 600,
wdTexture62Pt5Percent = 625,
wdTexture65Percent = 650,
wdTexture67Pt5Percent = 675,
wdTexture70Percent = 700,
wdTexture72Pt5Percent = 725,
wdTexture75Percent = 750,
wdTexture77Pt5Percent = 775,
wdTexture7Pt5Percent = 75,
wdTexture80Percent = 800,
wdTexture82Pt5Percent = 825,
wdTexture85Percent = 850,
wdTexture87Pt5Percent = 875,
wdTexture90Percent = 900,
wdTexture92Pt5Percent = 925,
wdTexture95Percent = 950,
wdTexture97Pt5Percent = 975,
wdTextureCross = -11,
wdTextureDarkCross = -5,
wdTextureDarkDiagonalCross = -6,
wdTextureDarkDiagonalDown = -3,
wdTextureDarkDiagonalUp = -4,
wdTextureDarkHorizontal = -1,
wdTextureDarkVertical = -2,
wdTextureDiagonalCross = -12,
wdTextureDiagonalDown = -9,
wdTextureDiagonalUp = -10,
wdTextureHorizontal = -7,
wdTextureNone = 0,
wdTextureSolid = 1000,
wdTextureVertical = -8,
}
const enum WdThemeColorIndex {
wdNotThemeColor = -1,
wdThemeColorAccent1 = 4,
wdThemeColorAccent2 = 5,
wdThemeColorAccent3 = 6,
wdThemeColorAccent4 = 7,
wdThemeColorAccent5 = 8,
wdThemeColorAccent6 = 9,
wdThemeColorBackground1 = 12,
wdThemeColorBackground2 = 14,
wdThemeColorHyperlink = 10,
wdThemeColorHyperlinkFollowed = 11,
wdThemeColorMainDark1 = 0,
wdThemeColorMainDark2 = 2,
wdThemeColorMainLight1 = 1,
wdThemeColorMainLight2 = 3,
wdThemeColorText1 = 13,
wdThemeColorText2 = 15,
}
const enum WdToaFormat {
wdTOAClassic = 1,
wdTOADistinctive = 2,
wdTOAFormal = 3,
wdTOASimple = 4,
wdTOATemplate = 0,
}
const enum WdTocFormat {
wdTOCClassic = 1,
wdTOCDistinctive = 2,
wdTOCFancy = 3,
wdTOCFormal = 5,
wdTOCModern = 4,
wdTOCSimple = 6,
wdTOCTemplate = 0,
}
const enum WdTofFormat {
wdTOFCentered = 3,
wdTOFClassic = 1,
wdTOFDistinctive = 2,
wdTOFFormal = 4,
wdTOFSimple = 5,
wdTOFTemplate = 0,
}
const enum WdTrailingCharacter {
wdTrailingNone = 2,
wdTrailingSpace = 1,
wdTrailingTab = 0,
}
const enum WdTwoLinesInOneType {
wdTwoLinesInOneAngleBrackets = 4,
wdTwoLinesInOneCurlyBrackets = 5,
wdTwoLinesInOneNoBrackets = 1,
wdTwoLinesInOneNone = 0,
wdTwoLinesInOneParentheses = 2,
wdTwoLinesInOneSquareBrackets = 3,
}
const enum WdUnderline {
wdUnderlineDash = 7,
wdUnderlineDashHeavy = 23,
wdUnderlineDashLong = 39,
wdUnderlineDashLongHeavy = 55,
wdUnderlineDotDash = 9,
wdUnderlineDotDashHeavy = 25,
wdUnderlineDotDotDash = 10,
wdUnderlineDotDotDashHeavy = 26,
wdUnderlineDotted = 4,
wdUnderlineDottedHeavy = 20,
wdUnderlineDouble = 3,
wdUnderlineNone = 0,
wdUnderlineSingle = 1,
wdUnderlineThick = 6,
wdUnderlineWavy = 11,
wdUnderlineWavyDouble = 43,
wdUnderlineWavyHeavy = 27,
wdUnderlineWords = 2,
}
const enum WdUnits {
wdCell = 12,
wdCharacter = 1,
wdCharacterFormatting = 13,
wdColumn = 9,
wdItem = 16,
wdLine = 5,
wdParagraph = 4,
wdParagraphFormatting = 14,
wdRow = 10,
wdScreen = 7,
wdSection = 8,
wdSentence = 3,
wdStory = 6,
wdTable = 15,
wdWindow = 11,
wdWord = 2,
}
const enum WdUpdateStyleListBehavior {
wdListBehaviorAddBulletsNumbering = 1,
wdListBehaviorKeepPreviousPattern = 0,
}
const enum WdUseFormattingFrom {
wdFormattingFromCurrent = 0,
wdFormattingFromPrompt = 2,
wdFormattingFromSelected = 1,
}
const enum WdVerticalAlignment {
wdAlignVerticalBottom = 3,
wdAlignVerticalCenter = 1,
wdAlignVerticalJustify = 2,
wdAlignVerticalTop = 0,
}
const enum WdViewType {
wdConflictView = 8,
wdMasterView = 5,
wdNormalView = 1,
wdOutlineView = 2,
wdPrintPreview = 4,
wdPrintView = 3,
wdReadingView = 7,
wdWebView = 6,
}
const enum WdViewTypeOld {
wdOnlineView = 6,
wdPageView = 3,
}
const enum WdVisualSelection {
wdVisualSelectionBlock = 0,
wdVisualSelectionContinuous = 1,
}
const enum WdWindowState {
wdWindowStateMaximize = 1,
wdWindowStateMinimize = 2,
wdWindowStateNormal = 0,
}
const enum WdWindowType {
wdWindowDocument = 0,
wdWindowTemplate = 1,
}
const enum WdWordDialog {
wdDialogBuildingBlockOrganizer = 2067,
wdDialogCompatibilityChecker = 2439,
wdDialogConnect = 420,
wdDialogConsistencyChecker = 1121,
wdDialogContentControlProperties = 2394,
wdDialogControlRun = 235,
wdDialogConvertObject = 392,
wdDialogCopyFile = 300,
wdDialogCreateAutoText = 872,
wdDialogCreateSource = 1922,
wdDialogCSSLinks = 1261,
wdDialogDocumentInspector = 1482,
wdDialogDocumentStatistics = 78,
wdDialogDrawAlign = 634,
wdDialogDrawSnapToGrid = 633,
wdDialogEditAutoText = 985,
wdDialogEditCreatePublisher = 732,
wdDialogEditFind = 112,
wdDialogEditFrame = 458,
wdDialogEditGoTo = 896,
wdDialogEditGoToOld = 811,
wdDialogEditLinks = 124,
wdDialogEditObject = 125,
wdDialogEditPasteSpecial = 111,
wdDialogEditPublishOptions = 735,
wdDialogEditReplace = 117,
wdDialogEditStyle = 120,
wdDialogEditSubscribeOptions = 736,
wdDialogEditSubscribeTo = 733,
wdDialogEditTOACategory = 625,
wdDialogEmailOptions = 863,
wdDialogExportAsFixedFormat = 2349,
wdDialogFileDocumentLayout = 178,
wdDialogFileFind = 99,
wdDialogFileMacCustomPageSetupGX = 737,
wdDialogFileMacPageSetup = 685,
wdDialogFileMacPageSetupGX = 444,
wdDialogFileNew = 79,
wdDialogFileNew2007 = 1116,
wdDialogFileOpen = 80,
wdDialogFilePageSetup = 178,
wdDialogFilePrint = 88,
wdDialogFilePrintOneCopy = 445,
wdDialogFilePrintSetup = 97,
wdDialogFileRoutingSlip = 624,
wdDialogFileSaveAs = 84,
wdDialogFileSaveVersion = 1007,
wdDialogFileSummaryInfo = 86,
wdDialogFileVersions = 945,
wdDialogFitText = 983,
wdDialogFontSubstitution = 581,
wdDialogFormatAddrFonts = 103,
wdDialogFormatBordersAndShading = 189,
wdDialogFormatBulletsAndNumbering = 824,
wdDialogFormatCallout = 610,
wdDialogFormatChangeCase = 322,
wdDialogFormatColumns = 177,
wdDialogFormatDefineStyleBorders = 185,
wdDialogFormatDefineStyleFont = 181,
wdDialogFormatDefineStyleFrame = 184,
wdDialogFormatDefineStyleLang = 186,
wdDialogFormatDefineStylePara = 182,
wdDialogFormatDefineStyleTabs = 183,
wdDialogFormatDrawingObject = 960,
wdDialogFormatDropCap = 488,
wdDialogFormatEncloseCharacters = 1162,
wdDialogFormatFont = 174,
wdDialogFormatFrame = 190,
wdDialogFormatPageNumber = 298,
wdDialogFormatParagraph = 175,
wdDialogFormatPicture = 187,
wdDialogFormatRetAddrFonts = 221,
wdDialogFormatSectionLayout = 176,
wdDialogFormatStyle = 180,
wdDialogFormatStyleGallery = 505,
wdDialogFormatStylesCustom = 1248,
wdDialogFormatTabs = 179,
wdDialogFormatTheme = 855,
wdDialogFormattingRestrictions = 1427,
wdDialogFormFieldHelp = 361,
wdDialogFormFieldOptions = 353,
wdDialogFrameSetProperties = 1074,
wdDialogHelpAbout = 9,
wdDialogHelpWordPerfectHelp = 10,
wdDialogHelpWordPerfectHelpOptions = 511,
wdDialogHorizontalInVertical = 1160,
wdDialogIMESetDefault = 1094,
wdDialogInsertAddCaption = 402,
wdDialogInsertAutoCaption = 359,
wdDialogInsertBookmark = 168,
wdDialogInsertBreak = 159,
wdDialogInsertCaption = 357,
wdDialogInsertCaptionNumbering = 358,
wdDialogInsertCrossReference = 367,
wdDialogInsertDatabase = 341,
wdDialogInsertDateTime = 165,
wdDialogInsertField = 166,
wdDialogInsertFile = 164,
wdDialogInsertFootnote = 370,
wdDialogInsertFormField = 483,
wdDialogInsertHyperlink = 925,
wdDialogInsertIndex = 170,
wdDialogInsertIndexAndTables = 473,
wdDialogInsertMergeField = 167,
wdDialogInsertNumber = 812,
wdDialogInsertObject = 172,
wdDialogInsertPageNumbers = 294,
wdDialogInsertPicture = 163,
wdDialogInsertPlaceholder = 2348,
wdDialogInsertSource = 2120,
wdDialogInsertSubdocument = 583,
wdDialogInsertSymbol = 162,
wdDialogInsertTableOfAuthorities = 471,
wdDialogInsertTableOfContents = 171,
wdDialogInsertTableOfFigures = 472,
wdDialogInsertWebComponent = 1324,
wdDialogLabelOptions = 1367,
wdDialogLetterWizard = 821,
wdDialogListCommands = 723,
wdDialogMailMerge = 676,
wdDialogMailMergeCheck = 677,
wdDialogMailMergeCreateDataSource = 642,
wdDialogMailMergeCreateHeaderSource = 643,
wdDialogMailMergeFieldMapping = 1304,
wdDialogMailMergeFindRecipient = 1326,
wdDialogMailMergeFindRecord = 569,
wdDialogMailMergeHelper = 680,
wdDialogMailMergeInsertAddressBlock = 1305,
wdDialogMailMergeInsertAsk = 4047,
wdDialogMailMergeInsertFields = 1307,
wdDialogMailMergeInsertFillIn = 4048,
wdDialogMailMergeInsertGreetingLine = 1306,
wdDialogMailMergeInsertIf = 4049,
wdDialogMailMergeInsertNextIf = 4053,
wdDialogMailMergeInsertSet = 4054,
wdDialogMailMergeInsertSkipIf = 4055,
wdDialogMailMergeOpenDataSource = 81,
wdDialogMailMergeOpenHeaderSource = 82,
wdDialogMailMergeQueryOptions = 681,
wdDialogMailMergeRecipients = 1308,
wdDialogMailMergeSetDocumentType = 1339,
wdDialogMailMergeUseAddressBook = 779,
wdDialogMarkCitation = 463,
wdDialogMarkIndexEntry = 169,
wdDialogMarkTableOfContentsEntry = 442,
wdDialogMyPermission = 1437,
wdDialogNewToolbar = 586,
wdDialogNoteOptions = 373,
wdDialogOMathRecognizedFunctions = 2165,
wdDialogOrganizer = 222,
wdDialogPermission = 1469,
wdDialogPhoneticGuide = 986,
wdDialogReviewAfmtRevisions = 570,
wdDialogSchemaLibrary = 1417,
wdDialogSearch = 1363,
wdDialogShowRepairs = 1381,
wdDialogSourceManager = 1920,
wdDialogStyleManagement = 1948,
wdDialogTableAutoFormat = 563,
wdDialogTableCellOptions = 1081,
wdDialogTableColumnWidth = 143,
wdDialogTableDeleteCells = 133,
wdDialogTableFormatCell = 612,
wdDialogTableFormula = 348,
wdDialogTableInsertCells = 130,
wdDialogTableInsertRow = 131,
wdDialogTableInsertTable = 129,
wdDialogTableOfCaptionsOptions = 551,
wdDialogTableOfContentsOptions = 470,
wdDialogTableProperties = 861,
wdDialogTableRowHeight = 142,
wdDialogTableSort = 199,
wdDialogTableSplitCells = 137,
wdDialogTableTableOptions = 1080,
wdDialogTableToText = 128,
wdDialogTableWrapping = 854,
wdDialogTCSCTranslator = 1156,
wdDialogTextToTable = 127,
wdDialogToolsAcceptRejectChanges = 506,
wdDialogToolsAdvancedSettings = 206,
wdDialogToolsAutoCorrect = 378,
wdDialogToolsAutoCorrectExceptions = 762,
wdDialogToolsAutoManager = 915,
wdDialogToolsAutoSummarize = 874,
wdDialogToolsBulletsNumbers = 196,
wdDialogToolsCompareDocuments = 198,
wdDialogToolsCreateDirectory = 833,
wdDialogToolsCreateEnvelope = 173,
wdDialogToolsCreateLabels = 489,
wdDialogToolsCustomize = 152,
wdDialogToolsCustomizeKeyboard = 432,
wdDialogToolsCustomizeMenuBar = 615,
wdDialogToolsCustomizeMenus = 433,
wdDialogToolsDictionary = 989,
wdDialogToolsEnvelopesAndLabels = 607,
wdDialogToolsGrammarSettings = 885,
wdDialogToolsHangulHanjaConversion = 784,
wdDialogToolsHighlightChanges = 197,
wdDialogToolsHyphenation = 195,
wdDialogToolsLanguage = 188,
wdDialogToolsMacro = 215,
wdDialogToolsMacroRecord = 214,
wdDialogToolsManageFields = 631,
wdDialogToolsMergeDocuments = 435,
wdDialogToolsOptions = 974,
wdDialogToolsOptionsAutoFormat = 959,
wdDialogToolsOptionsAutoFormatAsYouType = 778,
wdDialogToolsOptionsBidi = 1029,
wdDialogToolsOptionsCompatibility = 525,
wdDialogToolsOptionsEdit = 224,
wdDialogToolsOptionsEditCopyPaste = 1356,
wdDialogToolsOptionsFileLocations = 225,
wdDialogToolsOptionsFuzzy = 790,
wdDialogToolsOptionsGeneral = 203,
wdDialogToolsOptionsPrint = 208,
wdDialogToolsOptionsSave = 209,
wdDialogToolsOptionsSecurity = 1361,
wdDialogToolsOptionsSmartTag = 1395,
wdDialogToolsOptionsSpellingAndGrammar = 211,
wdDialogToolsOptionsTrackChanges = 386,
wdDialogToolsOptionsTypography = 739,
wdDialogToolsOptionsUserInfo = 213,
wdDialogToolsOptionsView = 204,
wdDialogToolsProtectDocument = 503,
wdDialogToolsProtectSection = 578,
wdDialogToolsRevisions = 197,
wdDialogToolsSpellingAndGrammar = 828,
wdDialogToolsTemplates = 87,
wdDialogToolsThesaurus = 194,
wdDialogToolsUnprotectDocument = 521,
wdDialogToolsWordCount = 228,
wdDialogTwoLinesInOne = 1161,
wdDialogUpdateTOC = 331,
wdDialogViewZoom = 577,
wdDialogWebOptions = 898,
wdDialogWindowActivate = 220,
wdDialogXMLElementAttributes = 1460,
wdDialogXMLOptions = 1425,
}
const enum WdWordDialogHID {
emptyenum = 0,
}
const enum WdWordDialogTab {
wdDialogEmailOptionsTabQuoting = 1900002,
wdDialogEmailOptionsTabSignature = 1900000,
wdDialogEmailOptionsTabStationary = 1900001,
wdDialogFilePageSetupTabCharsLines = 150004,
wdDialogFilePageSetupTabLayout = 150003,
wdDialogFilePageSetupTabMargins = 150000,
wdDialogFilePageSetupTabPaper = 150001,
wdDialogFormatBordersAndShadingTabBorders = 700000,
wdDialogFormatBordersAndShadingTabPageBorder = 700001,
wdDialogFormatBordersAndShadingTabShading = 700002,
wdDialogFormatBulletsAndNumberingTabBulleted = 1500000,
wdDialogFormatBulletsAndNumberingTabNumbered = 1500001,
wdDialogFormatBulletsAndNumberingTabOutlineNumbered = 1500002,
wdDialogFormatDrawingObjectTabColorsAndLines = 1200000,
wdDialogFormatDrawingObjectTabHR = 1200007,
wdDialogFormatDrawingObjectTabPicture = 1200004,
wdDialogFormatDrawingObjectTabPosition = 1200002,
wdDialogFormatDrawingObjectTabSize = 1200001,
wdDialogFormatDrawingObjectTabTextbox = 1200005,
wdDialogFormatDrawingObjectTabWeb = 1200006,
wdDialogFormatDrawingObjectTabWrapping = 1200003,
wdDialogFormatFontTabAnimation = 600002,
wdDialogFormatFontTabCharacterSpacing = 600001,
wdDialogFormatFontTabFont = 600000,
wdDialogFormatParagraphTabIndentsAndSpacing = 1000000,
wdDialogFormatParagraphTabTeisai = 1000002,
wdDialogFormatParagraphTabTextFlow = 1000001,
wdDialogInsertIndexAndTablesTabIndex = 400000,
wdDialogInsertIndexAndTablesTabTableOfAuthorities = 400003,
wdDialogInsertIndexAndTablesTabTableOfContents = 400001,
wdDialogInsertIndexAndTablesTabTableOfFigures = 400002,
wdDialogInsertSymbolTabSpecialCharacters = 200001,
wdDialogInsertSymbolTabSymbols = 200000,
wdDialogLetterWizardTabLetterFormat = 1600000,
wdDialogLetterWizardTabOtherElements = 1600002,
wdDialogLetterWizardTabRecipientInfo = 1600001,
wdDialogLetterWizardTabSenderInfo = 1600003,
wdDialogNoteOptionsTabAllEndnotes = 300001,
wdDialogNoteOptionsTabAllFootnotes = 300000,
wdDialogOrganizerTabAutoText = 500001,
wdDialogOrganizerTabCommandBars = 500002,
wdDialogOrganizerTabMacros = 500003,
wdDialogOrganizerTabStyles = 500000,
wdDialogStyleManagementTabEdit = 2200000,
wdDialogStyleManagementTabRecommend = 2200001,
wdDialogStyleManagementTabRestrict = 2200002,
wdDialogTablePropertiesTabCell = 1800003,
wdDialogTablePropertiesTabColumn = 1800002,
wdDialogTablePropertiesTabRow = 1800001,
wdDialogTablePropertiesTabTable = 1800000,
wdDialogTemplates = 2100000,
wdDialogTemplatesLinkedCSS = 2100003,
wdDialogTemplatesXMLExpansionPacks = 2100002,
wdDialogTemplatesXMLSchema = 2100001,
wdDialogToolsAutoCorrectExceptionsTabFirstLetter = 1400000,
wdDialogToolsAutoCorrectExceptionsTabHangulAndAlphabet = 1400002,
wdDialogToolsAutoCorrectExceptionsTabIac = 1400003,
wdDialogToolsAutoCorrectExceptionsTabInitialCaps = 1400001,
wdDialogToolsAutoManagerTabAutoCorrect = 1700000,
wdDialogToolsAutoManagerTabAutoFormat = 1700003,
wdDialogToolsAutoManagerTabAutoFormatAsYouType = 1700001,
wdDialogToolsAutoManagerTabAutoText = 1700002,
wdDialogToolsAutoManagerTabSmartTags = 1700004,
wdDialogToolsEnvelopesAndLabelsTabEnvelopes = 800000,
wdDialogToolsEnvelopesAndLabelsTabLabels = 800001,
wdDialogToolsOptionsTabAcetate = 1266,
wdDialogToolsOptionsTabBidi = 1029,
wdDialogToolsOptionsTabCompatibility = 525,
wdDialogToolsOptionsTabEdit = 224,
wdDialogToolsOptionsTabFileLocations = 225,
wdDialogToolsOptionsTabFuzzy = 790,
wdDialogToolsOptionsTabGeneral = 203,
wdDialogToolsOptionsTabHangulHanjaConversion = 786,
wdDialogToolsOptionsTabPrint = 208,
wdDialogToolsOptionsTabProofread = 211,
wdDialogToolsOptionsTabSave = 209,
wdDialogToolsOptionsTabSecurity = 1361,
wdDialogToolsOptionsTabTrackChanges = 386,
wdDialogToolsOptionsTabTypography = 739,
wdDialogToolsOptionsTabUserInfo = 213,
wdDialogToolsOptionsTabView = 204,
wdDialogWebOptionsBrowsers = 2000000,
wdDialogWebOptionsEncoding = 2000003,
wdDialogWebOptionsFiles = 2000001,
wdDialogWebOptionsFonts = 2000004,
wdDialogWebOptionsGeneral = 2000000,
wdDialogWebOptionsPictures = 2000002,
}
const enum WdWordDialogTabHID {
wdDialogFilePageSetupTabPaperSize = 150001,
wdDialogFilePageSetupTabPaperSource = 150002,
}
const enum WdWrapSideType {
wdWrapBoth = 0,
wdWrapLargest = 3,
wdWrapLeft = 1,
wdWrapRight = 2,
}
const enum WdWrapType {
wdWrapBehind = 5,
wdWrapFront = 3,
wdWrapInline = 7,
wdWrapNone = 3,
wdWrapSquare = 0,
wdWrapThrough = 2,
wdWrapTight = 1,
wdWrapTopBottom = 4,
}
const enum WdWrapTypeMerged {
wdWrapMergeBehind = 3,
wdWrapMergeFront = 4,
wdWrapMergeInline = 0,
wdWrapMergeSquare = 1,
wdWrapMergeThrough = 5,
wdWrapMergeTight = 2,
wdWrapMergeTopBottom = 6,
}
const enum WdXMLNodeLevel {
wdXMLNodeLevelCell = 3,
wdXMLNodeLevelInline = 0,
wdXMLNodeLevelParagraph = 1,
wdXMLNodeLevelRow = 2,
}
const enum WdXMLNodeType {
wdXMLNodeAttribute = 2,
wdXMLNodeElement = 1,
}
const enum WdXMLSelectionChangeReason {
wdXMLSelectionChangeReasonDelete = 2,
wdXMLSelectionChangeReasonInsert = 1,
wdXMLSelectionChangeReasonMove = 0,
}
const enum WdXMLValidationStatus {
wdXMLValidationStatusCustom = -1072898048,
wdXMLValidationStatusOK = 0,
}
const enum XlAxisCrosses {
xlAxisCrossesAutomatic = -4105,
xlAxisCrossesCustom = -4114,
xlAxisCrossesMaximum = 2,
xlAxisCrossesMinimum = 4,
}
const enum XlAxisGroup {
xlPrimary = 1,
xlSecondary = 2,
}
const enum XlAxisType {
xlCategory = 1,
xlSeriesAxis = 3,
xlValue = 2,
}
const enum XlBackground {
xlBackgroundAutomatic = -4105,
xlBackgroundOpaque = 3,
xlBackgroundTransparent = 2,
}
const enum XlBarShape {
xlBox = 0,
xlConeToMax = 5,
xlConeToPoint = 4,
xlCylinder = 3,
xlPyramidToMax = 2,
xlPyramidToPoint = 1,
}
const enum XlBorderWeight {
xlHairline = 1,
xlMedium = -4138,
xlThick = 4,
xlThin = 2,
}
const enum XlCategoryType {
xlAutomaticScale = -4105,
xlCategoryScale = 2,
xlTimeScale = 3,
}
const enum XlChartElementPosition {
xlChartElementPositionAutomatic = -4105,
xlChartElementPositionCustom = -4114,
}
const enum XlChartGallery {
xlAnyGallery = 23,
xlBuiltIn = 21,
xlUserDefined = 22,
}
const enum XlChartItem {
xlAxis = 21,
xlAxisTitle = 17,
xlChartArea = 2,
xlChartTitle = 4,
xlCorners = 6,
xlDataLabel = 0,
xlDataTable = 7,
xlDisplayUnitLabel = 30,
xlDownBars = 20,
xlDropLines = 26,
xlErrorBars = 9,
xlFloor = 23,
xlHiLoLines = 25,
xlLeaderLines = 29,
xlLegend = 24,
xlLegendEntry = 12,
xlLegendKey = 13,
xlMajorGridlines = 15,
xlMinorGridlines = 16,
xlNothing = 28,
xlPivotChartDropZone = 32,
xlPivotChartFieldButton = 31,
xlPlotArea = 19,
xlRadarAxisLabels = 27,
xlSeries = 3,
xlSeriesLines = 22,
xlShape = 14,
xlTrendline = 8,
xlUpBars = 18,
xlWalls = 5,
xlXErrorBars = 10,
xlYErrorBars = 11,
}
const enum XlChartPicturePlacement {
xlAllFaces = 7,
xlEnd = 2,
xlEndSides = 3,
xlFront = 4,
xlFrontEnd = 6,
xlFrontSides = 5,
xlSides = 1,
}
const enum XlChartPictureType {
xlStack = 2,
xlStackScale = 3,
xlStretch = 1,
}
const enum XlChartSplitType {
xlSplitByCustomSplit = 4,
xlSplitByPercentValue = 3,
xlSplitByPosition = 1,
xlSplitByValue = 2,
}
const enum XlColorIndex {
xlColorIndexAutomatic = -4105,
xlColorIndexNone = -4142,
}
const enum XlConstants {
xl3DBar = -4099,
xl3DSurface = -4103,
xlAbove = 0,
xlAutomatic = -4105,
xlBar = 2,
xlBelow = 1,
xlBoth = 1,
xlBottom = -4107,
xlCenter = -4108,
xlChecker = 9,
xlCircle = 8,
xlColumn = 3,
xlCombination = -4111,
xlCorner = 2,
xlCrissCross = 16,
xlCross = 4,
xlCustom = -4114,
xlDefaultAutoFormat = -1,
xlDiamond = 2,
xlDistributed = -4117,
xlFill = 5,
xlFixedValue = 1,
xlGeneral = 1,
xlGray16 = 17,
xlGray25 = -4124,
xlGray50 = -4125,
xlGray75 = -4126,
xlGray8 = 18,
xlGrid = 15,
xlHigh = -4127,
xlInside = 2,
xlJustify = -4130,
xlLeft = -4131,
xlLightDown = 13,
xlLightHorizontal = 11,
xlLightUp = 14,
xlLightVertical = 12,
xlLow = -4134,
xlMaximum = 2,
xlMinimum = 4,
xlMinusValues = 3,
xlNextToAxis = 4,
xlNone = -4142,
xlOpaque = 3,
xlOutside = 3,
xlPercent = 2,
xlPlus = 9,
xlPlusValues = 2,
xlRight = -4152,
xlScale = 3,
xlSemiGray75 = 10,
xlShowLabel = 4,
xlShowLabelAndPercent = 5,
xlShowPercent = 3,
xlShowValue = 2,
xlSingle = 2,
xlSolid = 1,
xlSquare = 1,
xlStar = 5,
xlStError = 4,
xlTop = -4160,
xlTransparent = 2,
xlTriangle = 3,
}
const enum XlCopyPictureFormat {
xlBitmap = 2,
xlPicture = -4147,
}
const enum XlDataLabelPosition {
xlLabelPositionAbove = 0,
xlLabelPositionBelow = 1,
xlLabelPositionBestFit = 5,
xlLabelPositionCenter = -4108,
xlLabelPositionCustom = 7,
xlLabelPositionInsideBase = 4,
xlLabelPositionInsideEnd = 3,
xlLabelPositionLeft = -4131,
xlLabelPositionMixed = 6,
xlLabelPositionOutsideEnd = 2,
xlLabelPositionRight = -4152,
}
const enum XlDataLabelSeparator {
xlDataLabelSeparatorDefault = 1,
}
const enum XlDataLabelsType {
xlDataLabelsShowBubbleSizes = 6,
xlDataLabelsShowLabel = 4,
xlDataLabelsShowLabelAndPercent = 5,
xlDataLabelsShowNone = -4142,
xlDataLabelsShowPercent = 3,
xlDataLabelsShowValue = 2,
}
const enum XlDisplayBlanksAs {
xlInterpolated = 3,
xlNotPlotted = 1,
xlZero = 2,
}
const enum XlDisplayUnit {
xlHundredMillions = -8,
xlHundreds = -2,
xlHundredThousands = -5,
xlMillionMillions = -10,
xlMillions = -6,
xlTenMillions = -7,
xlTenThousands = -4,
xlThousandMillions = -9,
xlThousands = -3,
}
const enum XlEndStyleCap {
xlCap = 1,
xlNoCap = 2,
}
const enum XlErrorBarDirection {
xlChartX = -4168,
xlChartY = 1,
}
const enum XlErrorBarInclude {
xlErrorBarIncludeBoth = 1,
xlErrorBarIncludeMinusValues = 3,
xlErrorBarIncludeNone = -4142,
xlErrorBarIncludePlusValues = 2,
}
const enum XlErrorBarType {
xlErrorBarTypeCustom = -4114,
xlErrorBarTypeFixedValue = 1,
xlErrorBarTypePercent = 2,
xlErrorBarTypeStDev = -4155,
xlErrorBarTypeStError = 4,
}
const enum XlHAlign {
xlHAlignCenter = -4108,
xlHAlignCenterAcrossSelection = 7,
xlHAlignDistributed = -4117,
xlHAlignFill = 5,
xlHAlignGeneral = 1,
xlHAlignJustify = -4130,
xlHAlignLeft = -4131,
xlHAlignRight = -4152,
}
const enum XlLegendPosition {
xlLegendPositionBottom = -4107,
xlLegendPositionCorner = 2,
xlLegendPositionCustom = -4161,
xlLegendPositionLeft = -4131,
xlLegendPositionRight = -4152,
xlLegendPositionTop = -4160,
}
const enum XlLineStyle {
xlContinuous = 1,
xlDash = -4115,
xlDashDot = 4,
xlDashDotDot = 5,
xlDot = -4118,
xlDouble = -4119,
xlLineStyleNone = -4142,
xlSlantDashDot = 13,
}
const enum XlMarkerStyle {
xlMarkerStyleAutomatic = -4105,
xlMarkerStyleCircle = 8,
xlMarkerStyleDash = -4115,
xlMarkerStyleDiamond = 2,
xlMarkerStyleDot = -4118,
xlMarkerStyleNone = -4142,
xlMarkerStylePicture = -4147,
xlMarkerStylePlus = 9,
xlMarkerStyleSquare = 1,
xlMarkerStyleStar = 5,
xlMarkerStyleTriangle = 3,
xlMarkerStyleX = -4168,
}
const enum XlOrientation {
xlDownward = -4170,
xlHorizontal = -4128,
xlUpward = -4171,
xlVertical = -4166,
}
const enum XlPattern {
xlPatternAutomatic = -4105,
xlPatternChecker = 9,
xlPatternCrissCross = 16,
xlPatternDown = -4121,
xlPatternGray16 = 17,
xlPatternGray25 = -4124,
xlPatternGray50 = -4125,
xlPatternGray75 = -4126,
xlPatternGray8 = 18,
xlPatternGrid = 15,
xlPatternHorizontal = -4128,
xlPatternLightDown = 13,
xlPatternLightHorizontal = 11,
xlPatternLightUp = 14,
xlPatternLightVertical = 12,
xlPatternLinearGradient = 4000,
xlPatternNone = -4142,
xlPatternRectangularGradient = 4001,
xlPatternSemiGray75 = 10,
xlPatternSolid = 1,
xlPatternUp = -4162,
xlPatternVertical = -4166,
}
const enum XlPictureAppearance {
xlPrinter = 2,
xlScreen = 1,
}
const enum XlPieSliceIndex {
xlCenterPoint = 5,
xlInnerCenterPoint = 8,
xlInnerClockwisePoint = 7,
xlInnerCounterClockwisePoint = 9,
xlMidClockwiseRadiusPoint = 4,
xlMidCounterClockwiseRadiusPoint = 6,
xlOuterCenterPoint = 2,
xlOuterClockwisePoint = 3,
xlOuterCounterClockwisePoint = 1,
}
const enum XlPieSliceLocation {
xlHorizontalCoordinate = 1,
xlVerticalCoordinate = 2,
}
const enum XlPivotFieldOrientation {
xlColumnField = 2,
xlDataField = 4,
xlHidden = 0,
xlPageField = 3,
xlRowField = 1,
}
const enum XlReadingOrder {
xlContext = -5002,
xlLTR = -5003,
xlRTL = -5004,
}
const enum XlRgbColor {
xlAliceBlue = 16775408,
xlAntiqueWhite = 14150650,
xlAqua = 16776960,
xlAquamarine = 13959039,
xlAzure = 16777200,
xlBeige = 14480885,
xlBisque = 12903679,
xlBlack = 0,
xlBlanchedAlmond = 13495295,
xlBlue = 16711680,
xlBlueViolet = 14822282,
xlBrown = 2763429,
xlBurlyWood = 8894686,
xlCadetBlue = 10526303,
xlChartreuse = 65407,
xlCoral = 5275647,
xlCornflowerBlue = 15570276,
xlCornsilk = 14481663,
xlCrimson = 3937500,
xlDarkBlue = 9109504,
xlDarkCyan = 9145088,
xlDarkGoldenrod = 755384,
xlDarkGray = 11119017,
xlDarkGreen = 25600,
xlDarkGrey = 11119017,
xlDarkKhaki = 7059389,
xlDarkMagenta = 9109643,
xlDarkOliveGreen = 3107669,
xlDarkOrange = 36095,
xlDarkOrchid = 13382297,
xlDarkRed = 139,
xlDarkSalmon = 8034025,
xlDarkSeaGreen = 9419919,
xlDarkSlateBlue = 9125192,
xlDarkSlateGray = 5197615,
xlDarkSlateGrey = 5197615,
xlDarkTurquoise = 13749760,
xlDarkViolet = 13828244,
xlDeepPink = 9639167,
xlDeepSkyBlue = 16760576,
xlDimGray = 6908265,
xlDimGrey = 6908265,
xlDodgerBlue = 16748574,
xlFireBrick = 2237106,
xlFloralWhite = 15792895,
xlForestGreen = 2263842,
xlFuchsia = 16711935,
xlGainsboro = 14474460,
xlGhostWhite = 16775416,
xlGold = 55295,
xlGoldenrod = 2139610,
xlGray = 8421504,
xlGreen = 32768,
xlGreenYellow = 3145645,
xlGrey = 8421504,
xlHoneydew = 15794160,
xlHotPink = 11823615,
xlIndianRed = 6053069,
xlIndigo = 8519755,
xlIvory = 15794175,
xlKhaki = 9234160,
xlLavender = 16443110,
xlLavenderBlush = 16118015,
xlLawnGreen = 64636,
xlLemonChiffon = 13499135,
xlLightBlue = 15128749,
xlLightCoral = 8421616,
xlLightCyan = 9145088,
xlLightGoldenrodYellow = 13826810,
xlLightGray = 13882323,
xlLightGreen = 9498256,
xlLightGrey = 13882323,
xlLightPink = 12695295,
xlLightSalmon = 8036607,
xlLightSeaGreen = 11186720,
xlLightSkyBlue = 16436871,
xlLightSlateGray = 10061943,
xlLightSlateGrey = 10061943,
xlLightSteelBlue = 14599344,
xlLightYellow = 14745599,
xlLime = 65280,
xlLimeGreen = 3329330,
xlLinen = 15134970,
xlMaroon = 128,
xlMediumAquamarine = 11206502,
xlMediumBlue = 13434880,
xlMediumOrchid = 13850042,
xlMediumPurple = 14381203,
xlMediumSeaGreen = 7451452,
xlMediumSlateBlue = 15624315,
xlMediumSpringGreen = 10156544,
xlMediumTurquoise = 13422920,
xlMediumVioletRed = 8721863,
xlMidnightBlue = 7346457,
xlMintCream = 16449525,
xlMistyRose = 14804223,
xlMoccasin = 11920639,
xlNavajoWhite = 11394815,
xlNavy = 8388608,
xlNavyBlue = 8388608,
xlOldLace = 15136253,
xlOlive = 32896,
xlOliveDrab = 2330219,
xlOrange = 42495,
xlOrangeRed = 17919,
xlOrchid = 14053594,
xlPaleGoldenrod = 7071982,
xlPaleGreen = 10025880,
xlPaleTurquoise = 15658671,
xlPaleVioletRed = 9662683,
xlPapayaWhip = 14020607,
xlPeachPuff = 12180223,
xlPeru = 4163021,
xlPink = 13353215,
xlPlum = 14524637,
xlPowderBlue = 15130800,
xlPurple = 8388736,
xlRed = 255,
xlRosyBrown = 9408444,
xlRoyalBlue = 14772545,
xlSalmon = 7504122,
xlSandyBrown = 6333684,
xlSeaGreen = 5737262,
xlSeashell = 15660543,
xlSienna = 2970272,
xlSilver = 12632256,
xlSkyBlue = 15453831,
xlSlateBlue = 13458026,
xlSlateGray = 9470064,
xlSlateGrey = 9470064,
xlSnow = 16448255,
xlSpringGreen = 8388352,
xlSteelBlue = 11829830,
xlTan = 9221330,
xlTeal = 8421376,
xlThistle = 14204888,
xlTomato = 4678655,
xlTurquoise = 13688896,
xlViolet = 15631086,
xlWheat = 11788021,
xlWhite = 16777215,
xlWhiteSmoke = 16119285,
xlYellow = 65535,
xlYellowGreen = 3329434,
}
const enum XlRowCol {
xlColumns = 2,
xlRows = 1,
}
const enum XlScaleType {
xlScaleLinear = -4132,
xlScaleLogarithmic = -4133,
}
const enum XlSizeRepresents {
xlSizeIsArea = 1,
xlSizeIsWidth = 2,
}
const enum XlTickLabelOrientation {
xlTickLabelOrientationAutomatic = -4105,
xlTickLabelOrientationDownward = -4170,
xlTickLabelOrientationHorizontal = -4128,
xlTickLabelOrientationUpward = -4171,
xlTickLabelOrientationVertical = -4166,
}
const enum XlTickLabelPosition {
xlTickLabelPositionHigh = -4127,
xlTickLabelPositionLow = -4134,
xlTickLabelPositionNextToAxis = 4,
xlTickLabelPositionNone = -4142,
}
const enum XlTickMark {
xlTickMarkCross = 4,
xlTickMarkInside = 2,
xlTickMarkNone = -4142,
xlTickMarkOutside = 3,
}
const enum XlTimeUnit {
xlDays = 0,
xlMonths = 1,
xlYears = 2,
}
const enum XlTrendlineType {
xlExponential = 5,
xlLinear = -4132,
xlLogarithmic = -4133,
xlMovingAvg = 6,
xlPolynomial = 3,
xlPower = 4,
}
const enum XlUnderlineStyle {
xlUnderlineStyleDouble = -4119,
xlUnderlineStyleDoubleAccounting = 5,
xlUnderlineStyleNone = -4142,
xlUnderlineStyleSingle = 2,
xlUnderlineStyleSingleAccounting = 4,
}
const enum XlVAlign {
xlVAlignBottom = -4107,
xlVAlignCenter = -4108,
xlVAlignDistributed = -4117,
xlVAlignJustify = -4130,
xlVAlignTop = -4160,
}
class AddIn {
private 'Word.AddIn_typekey': AddIn;
private constructor();
readonly Application: Application;
readonly Autoload: boolean;
readonly Compiled: boolean;
readonly Creator: number;
Delete(): void;
readonly Index: number;
Installed: boolean;
readonly Name: string;
readonly Parent: any;
readonly Path: string;
}
class AddIns {
private 'Word.AddIns_typekey': AddIns;
private constructor();
Add(FileName: string, Install?: any): AddIn;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): AddIn;
readonly Parent: any;
Unload(RemoveFromList: boolean): void;
}
class Adjustments {
private 'Word.Adjustments_typekey': Adjustments;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): number;
readonly Parent: any;
}
class Application {
private 'Word.Application_typekey': Application;
private constructor();
Activate(): void;
readonly ActiveDocument: Document;
readonly ActiveEncryptionSession: number;
ActivePrinter: string;
readonly ActiveProtectedViewWindow: ProtectedViewWindow;
readonly ActiveWindow: Window;
AddAddress(TagID: SafeArray<string>, Value: SafeArray<string>): void;
readonly AddIns: AddIns;
readonly AnswerWizard: Office.AnswerWizard;
readonly Application: Application;
readonly ArbitraryXMLSupportAvailable: boolean;
readonly Assistance: Office.IAssistance;
readonly Assistant: Office.Assistant;
readonly AutoCaptions: AutoCaptions;
readonly AutoCorrect: AutoCorrect;
readonly AutoCorrectEmail: AutoCorrect;
AutomaticChange(): void;
AutomationSecurity: Office.MsoAutomationSecurity;
readonly BackgroundPrintingStatus: number;
readonly BackgroundSavingStatus: number;
readonly Bibliography: Bibliography;
BrowseExtraFileTypes: string;
readonly Browser: Browser;
readonly Build: string;
readonly BuildFeatureCrew: string;
readonly BuildFull: string;
BuildKeyCode(Arg1: WdKey, Arg2?: any, Arg3?: any, Arg4?: any): number;
readonly CapsLock: boolean;
Caption: string;
readonly CaptionLabels: CaptionLabels;
CentimetersToPoints(Centimeters: number): number;
ChangeFileOpenDirectory(Path: string): void;
CheckGrammar(String: string): boolean;
CheckLanguage: boolean;
CheckSpelling(
Word: string, CustomDictionary?: any, IgnoreUppercase?: any, MainDictionary?: any, CustomDictionary2?: any, CustomDictionary3?: any, CustomDictionary4?: any,
CustomDictionary5?: any, CustomDictionary6?: any, CustomDictionary7?: any, CustomDictionary8?: any, CustomDictionary9?: any, CustomDictionary10?: any): boolean;
CleanString(String: string): string;
readonly COMAddIns: Office.COMAddIns;
readonly CommandBars: Office.CommandBars;
/**
* @param Word.WdCompareDestination [Destination=2]
* @param Word.WdGranularity [Granularity=1]
* @param boolean [CompareFormatting=true]
* @param boolean [CompareCaseChanges=true]
* @param boolean [CompareWhitespace=true]
* @param boolean [CompareTables=true]
* @param boolean [CompareHeaders=true]
* @param boolean [CompareFootnotes=true]
* @param boolean [CompareTextboxes=true]
* @param boolean [CompareFields=true]
* @param boolean [CompareComments=true]
* @param boolean [CompareMoves=true]
* @param string [RevisedAuthor='']
* @param boolean [IgnoreAllComparisonWarnings=false]
*/
CompareDocuments(
OriginalDocument: Document, RevisedDocument: Document, Destination?: WdCompareDestination, Granularity?: WdGranularity, CompareFormatting?: boolean,
CompareCaseChanges?: boolean, CompareWhitespace?: boolean, CompareTables?: boolean, CompareHeaders?: boolean, CompareFootnotes?: boolean,
CompareTextboxes?: boolean, CompareFields?: boolean, CompareComments?: boolean, CompareMoves?: boolean, RevisedAuthor?: string, IgnoreAllComparisonWarnings?: boolean): Document;
readonly Creator: number;
readonly CustomDictionaries: Dictionaries;
CustomizationContext: any;
DDEExecute(Channel: number, Command: string): void;
DDEInitiate(App: string, Topic: string): number;
DDEPoke(Channel: number, Item: string, Data: string): void;
DDERequest(Channel: number, Item: string): string;
DDETerminate(Channel: number): void;
DDETerminateAll(): void;
DefaultLegalBlackline: boolean;
DefaultSaveFormat: string;
DefaultTableSeparator: string;
DefaultWebOptions(): DefaultWebOptions;
readonly Dialogs: Dialogs;
DiscussionSupport(Range: any, cid: any, piCSE: any): void;
DisplayAlerts: WdAlertLevel;
DisplayAutoCompleteTips: boolean;
DisplayDocumentInformationPanel: boolean;
DisplayRecentFiles: boolean;
DisplayScreenTips: boolean;
DisplayScrollBars: boolean;
DisplayStatusBar: boolean;
readonly Documents: Documents;
DontResetInsertionPointProperties: boolean;
readonly Dummy1: boolean;
Dummy2(): boolean;
Dummy4(): void;
readonly EmailOptions: EmailOptions;
EmailTemplate: string;
EnableCancelKey: WdEnableCancelKey;
FeatureInstall: Office.MsoFeatureInstall;
readonly FileConverters: FileConverters;
FileDialog(FileDialogType: Office.MsoFileDialogType): Office.FileDialog;
readonly FileSearch: Office.FileSearch;
FileValidation: Office.MsoFileValidationMode;
FindKey(KeyCode: number, KeyCode2?: any): KeyBinding;
readonly FocusInMailHeader: boolean;
readonly FontNames: FontNames;
GetAddress(
Name?: any, AddressProperties?: any, UseAutoText?: any, DisplaySelectDialog?: any, SelectDialog?: any, CheckNamesDialog?: any, RecentAddressesChoice?: any,
UpdateRecentAddresses?: any): string;
GetDefaultTheme(DocumentType: WdDocumentMedium): string;
GetSpellingSuggestions(
Word: string, CustomDictionary?: any, IgnoreUppercase?: any, MainDictionary?: any, SuggestionMode?: any, CustomDictionary2?: any, CustomDictionary3?: any,
CustomDictionary4?: any, CustomDictionary5?: any, CustomDictionary6?: any, CustomDictionary7?: any, CustomDictionary8?: any, CustomDictionary9?: any,
CustomDictionary10?: any): SpellingSuggestions;
GoBack(): void;
GoForward(): void;
readonly HangulHanjaDictionaries: HangulHanjaConversionDictionaries;
Height: number;
Help(HelpType: any): void;
HelpTool(): void;
InchesToPoints(Inches: number): number;
International(Index: WdInternationalIndex): any;
IsObjectValid(Object: any): boolean;
readonly IsSandboxed: boolean;
readonly KeyBindings: KeyBindings;
/** @param number [LangId=0] */
Keyboard(LangId?: number): number;
KeyboardBidi(): void;
KeyboardLatin(): void;
KeysBoundTo(KeyCategory: WdKeyCategory, Command: string, CommandParameter?: any): KeysBoundTo;
KeyString(KeyCode: number, KeyCode2?: any): string;
readonly LandscapeFontNames: FontNames;
readonly Language: Office.MsoLanguageID;
readonly Languages: Languages;
readonly LanguageSettings: Office.LanguageSettings;
Left: number;
LinesToPoints(Lines: number): number;
ListCommands(ListAllCommands: boolean): void;
readonly ListGalleries: ListGalleries;
LoadMasterList(FileName: string): void;
LookupNameProperties(Name: string): void;
readonly MacroContainer: any;
readonly MailingLabel: MailingLabel;
readonly MailMessage: MailMessage;
readonly MailSystem: WdMailSystem;
readonly MAPIAvailable: boolean;
readonly MathCoprocessorAvailable: boolean;
/**
* @param Word.WdCompareDestination [Destination=2]
* @param Word.WdGranularity [Granularity=1]
* @param boolean [CompareFormatting=true]
* @param boolean [CompareCaseChanges=true]
* @param boolean [CompareWhitespace=true]
* @param boolean [CompareTables=true]
* @param boolean [CompareHeaders=true]
* @param boolean [CompareFootnotes=true]
* @param boolean [CompareTextboxes=true]
* @param boolean [CompareFields=true]
* @param boolean [CompareComments=true]
* @param boolean [CompareMoves=true]
* @param string [OriginalAuthor='']
* @param string [RevisedAuthor='']
* @param Word.WdMergeFormatFrom [FormatFrom=2]
*/
MergeDocuments(
OriginalDocument: Document, RevisedDocument: Document, Destination?: WdCompareDestination, Granularity?: WdGranularity, CompareFormatting?: boolean,
CompareCaseChanges?: boolean, CompareWhitespace?: boolean, CompareTables?: boolean, CompareHeaders?: boolean, CompareFootnotes?: boolean,
CompareTextboxes?: boolean, CompareFields?: boolean, CompareComments?: boolean, CompareMoves?: boolean, OriginalAuthor?: string, RevisedAuthor?: string,
FormatFrom?: WdMergeFormatFrom): Document;
MillimetersToPoints(Millimeters: number): number;
MountVolume(Zone: string, Server: string, Volume: string, User?: any, UserPassword?: any, VolumePassword?: any): number;
readonly MouseAvailable: boolean;
Move(Left: number, Top: number): void;
readonly Name: string;
readonly NewDocument: Office.NewFile;
NewWindow(): Window;
NextLetter(): void;
readonly NormalTemplate: Template;
readonly NumLock: boolean;
readonly OMathAutoCorrect: OMathAutoCorrect;
OnTime(When: any, Name: string, Tolerance?: any): void;
OpenAttachmentsInFullScreen: boolean;
readonly Options: Options;
OrganizerCopy(Source: string, Destination: string, Name: string, Object: WdOrganizerObject): void;
OrganizerDelete(Source: string, Name: string, Object: WdOrganizerObject): void;
OrganizerRename(Source: string, Name: string, NewName: string, Object: WdOrganizerObject): void;
readonly Parent: any;
readonly Path: string;
readonly PathSeparator: string;
PicasToPoints(Picas: number): number;
readonly PickerDialog: Office.PickerDialog;
PixelsToPoints(Pixels: number, fVertical?: any): number;
PointsToCentimeters(Points: number): number;
PointsToInches(Points: number): number;
PointsToLines(Points: number): number;
PointsToMillimeters(Points: number): number;
PointsToPicas(Points: number): number;
PointsToPixels(Points: number, fVertical?: any): number;
readonly PortraitFontNames: FontNames;
PrintOut(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, FileName?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any, PrintZoomColumn?: any, PrintZoomRow?: any,
PrintZoomPaperWidth?: any, PrintZoomPaperHeight?: any): void;
PrintOut2000(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, FileName?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any, PrintZoomColumn?: any, PrintZoomRow?: any,
PrintZoomPaperWidth?: any, PrintZoomPaperHeight?: any): void;
PrintOutOld(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, FileName?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any): void;
PrintPreview: boolean;
ProductCode(): string;
readonly ProtectedViewWindows: ProtectedViewWindows;
PutFocusInMailHeader(): void;
Quit(SaveChanges?: any, OriginalFormat?: any, RouteDocument?: any): void;
readonly RecentFiles: RecentFiles;
Repeat(Times?: any): boolean;
ResetIgnoreAll(): void;
Resize(Width: number, Height: number): void;
RestrictLinkedStyles: boolean;
Run(
MacroName: string, varg1?: any, varg2?: any, varg3?: any, varg4?: any, varg5?: any, varg6?: any, varg7?: any, varg8?: any, varg9?: any, varg10?: any,
varg11?: any, varg12?: any, varg13?: any, varg14?: any, varg15?: any, varg16?: any, varg17?: any, varg18?: any, varg19?: any, varg20?: any, varg21?: any,
varg22?: any, varg23?: any, varg24?: any, varg25?: any, varg26?: any, varg27?: any, varg28?: any, varg29?: any, varg30?: any): any;
RunOld(MacroName: string): void;
ScreenRefresh(): void;
ScreenUpdating: boolean;
readonly Selection: Selection;
SendFax(): void;
SetDefaultTheme(Name: string, DocumentType: WdDocumentMedium): void;
ShowClipboard(): void;
ShowMe(): void;
ShowStartupDialog: boolean;
ShowStylePreviews: boolean;
ShowVisualBasicEditor: boolean;
ShowWindowsInTaskbar: boolean;
readonly SmartArtColors: Office.SmartArtColors;
readonly SmartArtLayouts: Office.SmartArtLayouts;
readonly SmartArtQuickStyles: Office.SmartArtQuickStyles;
readonly SmartTagRecognizers: SmartTagRecognizers;
readonly SmartTagTypes: SmartTagTypes;
readonly SpecialMode: boolean;
StartupPath: string;
StatusBar: string;
SubstituteFont(UnavailableFont: string, SubstituteFont: string): void;
SynonymInfo(Word: string, LanguageID?: any): SynonymInfo;
readonly System: System;
readonly TaskPanes: TaskPanes;
readonly Tasks: Tasks;
readonly Templates: Templates;
ThreeWayMerge(LocalDocument: Document, ServerDocument: Document, BaseDocument: Document, FavorSource: boolean): void;
ToggleKeyboard(): void;
Top: number;
readonly UndoRecord: UndoRecord;
readonly UsableHeight: number;
readonly UsableWidth: number;
UserAddress: string;
readonly UserControl: boolean;
UserInitials: string;
UserName: string;
readonly VBE: VBIDE.VBE;
readonly Version: string;
Visible: boolean;
Width: number;
readonly Windows: Windows;
WindowState: WdWindowState;
readonly WordBasic: any;
readonly XMLNamespaces: XMLNamespaces;
}
class AutoCaption {
private 'Word.AutoCaption_typekey': AutoCaption;
private constructor();
readonly Application: Application;
AutoInsert: boolean;
CaptionLabel: any;
readonly Creator: number;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
}
class AutoCaptions {
private 'Word.AutoCaptions_typekey': AutoCaptions;
private constructor();
readonly Application: Application;
CancelAutoInsert(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: any): AutoCaption;
readonly Parent: any;
}
class AutoCorrect {
private 'Word.AutoCorrect_typekey': AutoCorrect;
private constructor();
readonly Application: Application;
CorrectCapsLock: boolean;
CorrectDays: boolean;
CorrectHangulAndAlphabet: boolean;
CorrectInitialCaps: boolean;
CorrectKeyboardSetting: boolean;
CorrectSentenceCaps: boolean;
CorrectTableCells: boolean;
readonly Creator: number;
DisplayAutoCorrectOptions: boolean;
readonly Entries: AutoCorrectEntries;
FirstLetterAutoAdd: boolean;
readonly FirstLetterExceptions: FirstLetterExceptions;
HangulAndAlphabetAutoAdd: boolean;
readonly HangulAndAlphabetExceptions: HangulAndAlphabetExceptions;
OtherCorrectionsAutoAdd: boolean;
readonly OtherCorrectionsExceptions: OtherCorrectionsExceptions;
readonly Parent: any;
ReplaceText: boolean;
ReplaceTextFromSpellingChecker: boolean;
TwoInitialCapsAutoAdd: boolean;
readonly TwoInitialCapsExceptions: TwoInitialCapsExceptions;
}
class AutoCorrectEntries {
private 'Word.AutoCorrectEntries_typekey': AutoCorrectEntries;
private constructor();
Add(Name: string, Value: string): AutoCorrectEntry;
AddRichText(Name: string, Range: Range): AutoCorrectEntry;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): AutoCorrectEntry;
readonly Parent: any;
}
class AutoCorrectEntry {
private 'Word.AutoCorrectEntry_typekey': AutoCorrectEntry;
private constructor();
readonly Application: Application;
Apply(Range: Range): void;
readonly Creator: number;
Delete(): void;
readonly Index: number;
Name: string;
readonly Parent: any;
readonly RichText: boolean;
Value: string;
}
class AutoTextEntries {
private 'Word.AutoTextEntries_typekey': AutoTextEntries;
private constructor();
Add(Name: string, Range: Range): AutoTextEntry;
AppendToSpike(Range: Range): AutoTextEntry;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): AutoTextEntry;
readonly Parent: any;
}
class AutoTextEntry {
private 'Word.AutoTextEntry_typekey': AutoTextEntry;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
Insert(Where: Range, RichText?: any): Range;
Name: string;
readonly Parent: any;
readonly StyleName: string;
Value: string;
}
class Bibliography {
private 'Word.Bibliography_typekey': Bibliography;
private constructor();
readonly Application: Application;
BibliographyStyle: string;
readonly Creator: number;
GenerateUniqueTag(): string;
readonly Parent: any;
readonly Sources: Sources;
}
class Bookmark {
private 'Word.Bookmark_typekey': Bookmark;
private constructor();
readonly Application: Application;
readonly Column: boolean;
Copy(Name: string): Bookmark;
readonly Creator: number;
Delete(): void;
readonly Empty: boolean;
End: number;
readonly Name: string;
readonly Parent: any;
readonly Range: Range;
Select(): void;
Start: number;
readonly StoryType: WdStoryType;
}
class Bookmarks {
private 'Word.Bookmarks_typekey': Bookmarks;
private constructor();
Add(Name: string, Range?: any): Bookmark;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
DefaultSorting: WdBookmarkSortBy;
Exists(Name: string): boolean;
Item(Index: number | string): Bookmark;
readonly Parent: any;
ShowHidden: boolean;
}
class Border {
private 'Word.Border_typekey': Border;
private constructor();
readonly Application: Application;
ArtStyle: WdPageBorderArt;
ArtWidth: number;
Color: WdColor;
ColorIndex: WdColorIndex;
readonly Creator: number;
readonly Inside: boolean;
LineStyle: WdLineStyle;
LineWidth: WdLineWidth;
readonly Parent: any;
Visible: boolean;
}
class Borders {
private 'Word.Borders_typekey': Borders;
private constructor();
AlwaysInFront: boolean;
readonly Application: Application;
ApplyPageBordersToAllSections(): void;
readonly Count: number;
readonly Creator: number;
DistanceFrom: WdBorderDistanceFrom;
DistanceFromBottom: number;
DistanceFromLeft: number;
DistanceFromRight: number;
DistanceFromTop: number;
Enable: boolean | WdConstants.wdUndefined | WdLineStyle;
EnableFirstPageInSection: boolean;
EnableOtherPagesInSection: boolean;
readonly HasHorizontal: boolean;
readonly HasVertical: boolean;
InsideColor: WdColor;
InsideColorIndex: WdColorIndex;
InsideLineStyle: WdLineStyle;
InsideLineWidth: WdLineWidth;
Item(Index: WdBorderType): Border;
JoinBorders: boolean;
OutsideColor: WdColor;
OutsideColorIndex: WdColorIndex;
OutsideLineStyle: WdLineStyle;
OutsideLineWidth: WdLineWidth;
readonly Parent: any;
Shadow: boolean;
SurroundFooter: boolean;
SurroundHeader: boolean;
}
class Break {
private 'Word.Break_typekey': Break;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly PageIndex: number;
readonly Parent: any;
readonly Range: Range;
}
class Breaks {
private 'Word.Breaks_typekey': Breaks;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Break;
readonly Parent: any;
}
class Browser {
private 'Word.Browser_typekey': Browser;
private constructor();
readonly Application: Application;
readonly Creator: number;
Next(): void;
readonly Parent: any;
Previous(): void;
Target: WdBrowseTarget;
}
class BuildingBlock {
private 'Word.BuildingBlock_typekey': BuildingBlock;
private constructor();
readonly Application: Application;
readonly Category: Category;
readonly Creator: number;
Delete(): void;
Description: string;
readonly ID: string;
readonly Index: number;
Insert(Where: Range, RichText?: any): Range;
InsertOptions: number;
Name: string;
readonly Parent: any;
readonly Type: BuildingBlockType;
Value: string;
}
class BuildingBlockEntries {
private 'Word.BuildingBlockEntries_typekey': BuildingBlockEntries;
private constructor();
/** @param Word.WdDocPartInsertOptions [InsertOptions=0] */
Add(Name: string, Type: WdBuildingBlockTypes, Category: string, Range: Range, Description: any, InsertOptions?: WdDocPartInsertOptions): BuildingBlock;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): BuildingBlock;
readonly Parent: any;
}
class BuildingBlocks {
private 'Word.BuildingBlocks_typekey': BuildingBlocks;
private constructor();
/** @param Word.WdDocPartInsertOptions [InsertOptions=0] */
Add(Name: string, Range: Range, Description: any, InsertOptions?: WdDocPartInsertOptions): BuildingBlock;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): BuildingBlock;
readonly Parent: any;
}
class BuildingBlockType {
private 'Word.BuildingBlockType_typekey': BuildingBlockType;
private constructor();
readonly Application: Application;
readonly Categories: Categories;
readonly Creator: number;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
}
class BuildingBlockTypes {
private 'Word.BuildingBlockTypes_typekey': BuildingBlockTypes;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: WdBuildingBlockTypes): BuildingBlockType;
readonly Parent: any;
}
class CalloutFormat {
private 'Word.CalloutFormat_typekey': CalloutFormat;
private constructor();
Accent: Office.MsoTriState;
Angle: Office.MsoCalloutAngleType;
readonly Application: Application;
AutoAttach: Office.MsoTriState;
readonly AutoLength: Office.MsoTriState;
AutomaticLength(): void;
Border: Office.MsoTriState;
readonly Creator: number;
CustomDrop(Drop: number): void;
CustomLength(Length: number): void;
readonly Drop: number;
readonly DropType: Office.MsoCalloutDropType;
Gap: number;
readonly Length: number;
readonly Parent: any;
PresetDrop(DropType: Office.MsoCalloutDropType): void;
Type: Office.MsoCalloutType;
}
class CanvasShapes {
private 'Word.CanvasShapes_typekey': CanvasShapes;
private constructor();
AddCallout(Type: Office.MsoCalloutType, Left: number, Top: number, Width: number, Height: number): Shape;
AddConnector(Type: Office.MsoConnectorType, BeginX: number, BeginY: number, EndX: number, EndY: number): Shape;
AddCurve(SafeArrayOfPoints: any): Shape;
AddLabel(Orientation: Office.MsoTextOrientation, Left: number, Top: number, Width: number, Height: number): Shape;
AddLine(BeginX: number, BeginY: number, EndX: number, EndY: number): Shape;
AddPicture(FileName: string, LinkToFile?: any, SaveWithDocument?: any, Left?: any, Top?: any, Width?: any, Height?: any): Shape;
AddPolyline(SafeArrayOfPoints: any): Shape;
AddShape(Type: number, Left: number, Top: number, Width: number, Height: number): Shape;
AddTextbox(Orientation: Office.MsoTextOrientation, Left: number, Top: number, Width: number, Height: number): Shape;
AddTextEffect(
PresetTextEffect: Office.MsoPresetTextEffect, Text: string, FontName: string, FontSize: number, FontBold: Office.MsoTriState, FontItalic: Office.MsoTriState,
Left: number, Top: number): Shape;
readonly Application: Application;
BuildFreeform(EditingType: Office.MsoEditingType, X1: number, Y1: number): FreeformBuilder;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Shape;
readonly Parent: any;
Range(Index: any): ShapeRange;
SelectAll(): void;
}
class CaptionLabel {
private 'Word.CaptionLabel_typekey': CaptionLabel;
private constructor();
readonly Application: Application;
readonly BuiltIn: boolean;
ChapterStyleLevel: number;
readonly Creator: number;
Delete(): void;
readonly ID: WdCaptionLabelID;
IncludeChapterNumber: boolean;
readonly Name: string;
NumberStyle: WdCaptionNumberStyle;
readonly Parent: any;
Position: WdCaptionPosition;
Separator: WdSeparatorType;
}
class CaptionLabels {
private 'Word.CaptionLabels_typekey': CaptionLabels;
private constructor();
Add(Name: string): CaptionLabel;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): CaptionLabel;
readonly Parent: any;
}
class Categories {
private 'Word.Categories_typekey': Categories;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Category;
readonly Parent: any;
}
class Category {
private 'Word.Category_typekey': Category;
private constructor();
readonly Application: Application;
readonly BuildingBlocks: BuildingBlocks;
readonly Creator: number;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
readonly Type: BuildingBlockType;
}
class Cell {
private 'Word.Cell_typekey': Cell;
private constructor();
readonly Application: Application;
AutoSum(): void;
Borders: Borders;
BottomPadding: number;
readonly Column: Column;
readonly ColumnIndex: number;
readonly Creator: number;
Delete(ShiftCells?: any): void;
FitText: boolean;
Formula(Formula?: any, NumFormat?: any): void;
Height: number;
HeightRule: WdRowHeightRule;
ID: string;
LeftPadding: number;
Merge(MergeTo: Cell): void;
readonly NestingLevel: number;
readonly Next: Cell;
readonly Parent: any;
PreferredWidth: number;
PreferredWidthType: WdPreferredWidthType;
readonly Previous: Cell;
readonly Range: Range;
RightPadding: number;
readonly Row: Row;
readonly RowIndex: number;
Select(): void;
SetHeight(RowHeight: any, HeightRule: WdRowHeightRule): void;
SetWidth(ColumnWidth: number, RulerStyle: WdRulerStyle): void;
readonly Shading: Shading;
Split(NumRows?: any, NumColumns?: any): void;
readonly Tables: Tables;
TopPadding: number;
VerticalAlignment: WdCellVerticalAlignment;
Width: number;
WordWrap: boolean;
}
class Cells {
private 'Word.Cells_typekey': Cells;
private constructor();
Add(BeforeCell?: any): Cell;
readonly Application: Application;
AutoFit(): void;
Borders: Borders;
readonly Count: number;
readonly Creator: number;
Delete(ShiftCells?: any): void;
DistributeHeight(): void;
DistributeWidth(): void;
Height: number;
HeightRule: WdRowHeightRule;
Item(Index: number): Cell;
Merge(): void;
readonly NestingLevel: number;
readonly Parent: any;
PreferredWidth: number;
PreferredWidthType: WdPreferredWidthType;
SetHeight(RowHeight: any, HeightRule: WdRowHeightRule): void;
SetWidth(ColumnWidth: number, RulerStyle: WdRulerStyle): void;
readonly Shading: Shading;
Split(NumRows?: any, NumColumns?: any, MergeBeforeSplit?: any): void;
VerticalAlignment: WdCellVerticalAlignment;
Width: number;
}
class Characters {
private 'Word.Characters_typekey': Characters;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
readonly First: Range;
Item(Index: number): Range;
readonly Last: Range;
readonly Parent: any;
}
class Chart {
private 'Word.Chart_typekey': Chart;
private constructor();
readonly Application: any;
ApplyChartTemplate(FileName: string): void;
ApplyCustomType(ChartType: Office.XlChartType, TypeName?: any): void;
/** @param Word.XlDataLabelsType [Type=2] */
ApplyDataLabels(
Type?: XlDataLabelsType, LegendKey?: any, AutoText?: any, HasLeaderLines?: any, ShowSeriesName?: any, ShowCategoryName?: any, ShowValue?: any,
ShowPercentage?: any, ShowBubbleSize?: any, Separator?: any): void;
ApplyLayout(Layout: number, ChartType?: any): void;
readonly Area3DGroup: ChartGroup;
AreaGroups(Index?: any): any;
AutoFormat(Gallery: number, Format?: any): void;
AutoScaling: boolean;
/** @param Word.XlAxisGroup [AxisGroup=1] */
Axes(Type: any, AxisGroup?: XlAxisGroup): any;
readonly BackWall: Walls;
readonly Bar3DGroup: ChartGroup;
BarGroups(Index?: any): any;
BarShape: XlBarShape;
readonly ChartArea: ChartArea;
readonly ChartData: ChartData;
ChartGroups(Index?: any): any;
ChartStyle: any;
readonly ChartTitle: ChartTitle;
ChartType: Office.XlChartType;
ChartWizard(
Source?: any, Gallery?: any, Format?: any, PlotBy?: any, CategoryLabels?: any, SeriesLabels?: any, HasLegend?: any, Title?: any, CategoryTitle?: any,
ValueTitle?: any, ExtraTitle?: any): void;
ClearToMatchStyle(): void;
readonly Column3DGroup: ChartGroup;
ColumnGroups(Index?: any): any;
Copy(Before?: any, After?: any): void;
/**
* @param Word.XlPictureAppearance [Appearance=1]
* @param Word.XlCopyPictureFormat [Format=-4147]
* @param Word.XlPictureAppearance [Size=2]
*/
CopyPicture(Appearance?: XlPictureAppearance, Format?: XlCopyPictureFormat, Size?: XlPictureAppearance): void;
readonly Corners: Corners;
readonly Creator: number;
readonly DataTable: DataTable;
Delete(): any;
DepthPercent: number;
DisplayBlanksAs: XlDisplayBlanksAs;
DoughnutGroups(Index?: any): any;
Elevation: number;
Export(FileName: string, FilterName?: any, Interactive?: any): boolean;
readonly Floor: Floor;
GapDepth: number;
GetChartElement(x: number, y: number, ElementID: number, Arg1: number, Arg2: number): void;
HasAxis(Index1?: any, Index2?: any): any;
HasDataTable: boolean;
HasLegend: boolean;
HasPivotFields: boolean;
HasTitle: boolean;
HeightPercent: number;
readonly Legend: Legend;
readonly Line3DGroup: ChartGroup;
LineGroups(Index?: any): any;
readonly Parent: any;
Paste(Type?: any): void;
Perspective: number;
readonly Pie3DGroup: ChartGroup;
PieGroups(Index?: any): any;
readonly PivotLayout: any;
readonly PlotArea: PlotArea;
PlotBy: XlRowCol;
PlotVisibleOnly: boolean;
RadarGroups(Index?: any): any;
Refresh(): void;
RightAngleAxes: any;
Rotation: any;
SaveChartTemplate(FileName: string): void;
Select(Replace?: any): any;
SeriesCollection(Index?: any): any;
SetBackgroundPicture(FileName: string): void;
SetDefaultChart(Name: any): void;
SetElement(Element: Office.MsoChartElementType): void;
SetSourceData(Source: string, PlotBy?: any): void;
readonly Shapes: any;
ShowAllFieldButtons: boolean;
ShowAxisFieldButtons: boolean;
ShowDataLabelsOverMaximum: boolean;
ShowLegendFieldButtons: boolean;
ShowReportFilterFieldButtons: boolean;
ShowValueFieldButtons: boolean;
readonly SideWall: Walls;
SubType: number;
readonly SurfaceGroup: ChartGroup;
Type: number;
readonly Walls: Walls;
XYGroups(Index?: any): any;
}
class ChartArea {
private 'Word.ChartArea_typekey': ChartArea;
private constructor();
readonly Application: any;
AutoScaleFont: any;
readonly Border: ChartBorder;
Clear(): any;
ClearContents(): any;
ClearFormats(): any;
Copy(): any;
readonly Creator: number;
readonly Fill: ChartFillFormat;
readonly Font: ChartFont;
readonly Format: ChartFormat;
Height: number;
readonly Interior: Interior;
Left: number;
readonly Name: string;
readonly Parent: any;
Select(): any;
Shadow: boolean;
Top: number;
Width: number;
}
class ChartBorder {
private 'Word.ChartBorder_typekey': ChartBorder;
private constructor();
readonly Application: any;
Color: any;
ColorIndex: any;
readonly Creator: number;
LineStyle: any;
readonly Parent: any;
Weight: any;
}
class ChartCharacters {
private 'Word.ChartCharacters_typekey': ChartCharacters;
private constructor();
readonly Application: any;
Caption: string;
readonly Count: number;
readonly Creator: number;
Delete(): any;
readonly Font: ChartFont;
Insert(String: string): any;
readonly Parent: any;
PhoneticCharacters: string;
Text: string;
}
class ChartColorFormat {
private 'Word.ChartColorFormat_typekey': ChartColorFormat;
private constructor();
readonly _Default: number;
readonly Application: any;
readonly Creator: number;
readonly Parent: any;
readonly RGB: number;
SchemeColor: number;
readonly Type: number;
}
class ChartData {
private 'Word.ChartData_typekey': ChartData;
private constructor();
Activate(): void;
BreakLink(): void;
readonly IsLinked: boolean;
readonly Workbook: any;
}
class ChartFillFormat {
private 'Word.ChartFillFormat_typekey': ChartFillFormat;
private constructor();
readonly Application: any;
readonly BackColor: ChartColorFormat;
readonly Creator: number;
readonly ForeColor: ChartColorFormat;
readonly GradientColorType: Office.MsoGradientColorType;
readonly GradientDegree: number;
readonly GradientStyle: Office.MsoGradientStyle;
readonly GradientVariant: number;
OneColorGradient(Style: Office.MsoGradientStyle, Variant: number, Degree: number): void;
readonly Parent: any;
readonly Pattern: Office.MsoPatternType;
Patterned(Pattern: Office.MsoPatternType): void;
PresetGradient(Style: Office.MsoGradientStyle, Variant: number, PresetGradientType: Office.MsoPresetGradientType): void;
readonly PresetGradientType: Office.MsoPresetGradientType;
readonly PresetTexture: Office.MsoPresetTexture;
PresetTextured(PresetTexture: Office.MsoPresetTexture): void;
Solid(): void;
readonly TextureName: string;
readonly TextureType: Office.MsoTextureType;
TwoColorGradient(Style: Office.MsoGradientStyle, Variant: number): void;
readonly Type: Office.MsoFillType;
UserPicture(PictureFile?: any, PictureFormat?: any, PictureStackUnit?: any, PicturePlacement?: any): void;
UserTextured(TextureFile: string): void;
Visible: Office.MsoTriState;
}
class ChartFont {
private 'Word.ChartFont_typekey': ChartFont;
private constructor();
readonly Application: any;
Background: any;
Bold: any;
Color: any;
ColorIndex: any;
readonly Creator: number;
FontStyle: any;
Italic: any;
Name: any;
OutlineFont: any;
readonly Parent: any;
Shadow: any;
Size: any;
StrikeThrough: any;
Subscript: any;
Superscript: any;
Underline: any;
}
class ChartFormat {
private 'Word.ChartFormat_typekey': ChartFormat;
private constructor();
readonly Application: any;
readonly Creator: number;
readonly Fill: FillFormat;
readonly Glow: GlowFormat;
readonly Line: LineFormat;
readonly Parent: any;
readonly PictureFormat: PictureFormat;
readonly Shadow: ShadowFormat;
readonly SoftEdge: SoftEdgeFormat;
readonly TextFrame2: Office.TextFrame2;
readonly ThreeD: ThreeDFormat;
}
class ChartGroup {
private 'Word.ChartGroup_typekey': ChartGroup;
private constructor();
readonly Application: any;
AxisGroup: XlAxisGroup;
BubbleScale: number;
readonly Creator: number;
DoughnutHoleSize: number;
readonly DownBars: DownBars;
readonly DropLines: DropLines;
FirstSliceAngle: number;
GapWidth: number;
Has3DShading: boolean;
HasDropLines: boolean;
HasHiLoLines: boolean;
HasRadarAxisLabels: boolean;
HasSeriesLines: boolean;
HasUpDownBars: boolean;
readonly HiLoLines: HiLoLines;
readonly Index: number;
Overlap: number;
readonly Parent: any;
readonly RadarAxisLabels: TickLabels;
SecondPlotSize: number;
SeriesCollection(Index?: any): any;
readonly SeriesLines: SeriesLines;
ShowNegativeBubbles: boolean;
SizeRepresents: XlSizeRepresents;
SplitType: XlChartSplitType;
SplitValue: any;
SubType: number;
Type: number;
readonly UpBars: UpBars;
VaryByCategories: boolean;
}
class ChartTitle {
private 'Word.ChartTitle_typekey': ChartTitle;
private constructor();
readonly Application: any;
AutoScaleFont: any;
readonly Border: ChartBorder;
Caption: string;
Characters(Start?: any, Length?: any): ChartCharacters;
readonly Creator: number;
Delete(): any;
readonly Fill: ChartFillFormat;
readonly Font: ChartFont;
readonly Format: ChartFormat;
Formula: string;
FormulaLocal: string;
FormulaR1C1: string;
FormulaR1C1Local: string;
readonly Height: number;
HorizontalAlignment: any;
IncludeInLayout: boolean;
readonly Interior: Interior;
Left: number;
readonly Name: string;
Orientation: any;
readonly Parent: any;
Position: XlChartElementPosition;
ReadingOrder: number;
Select(): any;
Shadow: boolean;
Text: string;
Top: number;
VerticalAlignment: any;
readonly Width: number;
}
class CheckBox {
private 'Word.CheckBox_typekey': CheckBox;
private constructor();
readonly Application: Application;
AutoSize: boolean;
readonly Creator: number;
Default: boolean;
readonly Parent: any;
Size: number;
readonly Valid: boolean;
Value: boolean;
}
class CoAuthLock {
private 'Word.CoAuthLock_typekey': CoAuthLock;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly HeaderFooter: boolean;
readonly Owner: CoAuthor;
readonly Parent: any;
readonly Range: Range;
readonly Type: WdLockType;
Unlock(): void;
}
class CoAuthLocks {
private 'Word.CoAuthLocks_typekey': CoAuthLocks;
private constructor();
/** @param Word.WdLockType [Type=1] */
Add(Range: any, Type?: WdLockType): CoAuthLock;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): CoAuthLock;
readonly Parent: any;
RemoveEphemeralLocks(): void;
}
class CoAuthor {
private 'Word.CoAuthor_typekey': CoAuthor;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly EmailAddress: string;
readonly ID: string;
readonly IsMe: boolean;
readonly Locks: CoAuthLocks;
readonly Name: string;
readonly Parent: any;
}
class CoAuthoring {
private 'Word.CoAuthoring_typekey': CoAuthoring;
private constructor();
readonly Application: Application;
readonly Authors: CoAuthors;
readonly CanMerge: boolean;
readonly CanShare: boolean;
readonly Conflicts: Conflicts;
readonly Creator: number;
readonly Locks: CoAuthLocks;
readonly Me: CoAuthor;
readonly Parent: any;
readonly PendingUpdates: boolean;
readonly Updates: CoAuthUpdates;
}
class CoAuthors {
private 'Word.CoAuthors_typekey': CoAuthors;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): CoAuthor;
readonly Parent: any;
}
class CoAuthUpdate {
private 'Word.CoAuthUpdate_typekey': CoAuthUpdate;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Parent: any;
readonly Range: Range;
}
class CoAuthUpdates {
private 'Word.CoAuthUpdates_typekey': CoAuthUpdates;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): CoAuthUpdate;
readonly Parent: any;
}
class ColorFormat {
private 'Word.ColorFormat_typekey': ColorFormat;
private constructor();
readonly Application: Application;
Black: number;
Brightness: number;
readonly Creator: number;
Cyan: number;
Ink(Index: number): number;
Magenta: number;
Name: string;
ObjectThemeColor: WdThemeColorIndex;
OverPrint: Office.MsoTriState;
readonly Parent: any;
RGB: number;
SchemeColor: number;
SetCMYK(Cyan: number, Magenta: number, Yellow: number, Black: number): void;
TintAndShade: number;
readonly Type: Office.MsoColorType;
Yellow: number;
}
class Column {
private 'Word.Column_typekey': Column;
private constructor();
readonly Application: Application;
AutoFit(): void;
Borders: Borders;
readonly Cells: Cells;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly IsFirst: boolean;
readonly IsLast: boolean;
readonly NestingLevel: number;
readonly Next: Column;
readonly Parent: any;
PreferredWidth: number;
PreferredWidthType: WdPreferredWidthType;
readonly Previous: Column;
Select(): void;
SetWidth(ColumnWidth: number, RulerStyle: WdRulerStyle): void;
readonly Shading: Shading;
Sort(
ExcludeHeader?: any, SortFieldType?: any, SortOrder?: any, CaseSensitive?: any, BidiSort?: any, IgnoreThe?: any, IgnoreKashida?: any, IgnoreDiacritics?: any,
IgnoreHe?: any, LanguageID?: any): void;
SortOld(ExcludeHeader?: any, SortFieldType?: any, SortOrder?: any, CaseSensitive?: any, LanguageID?: any): void;
Width: number;
}
class Columns {
private 'Word.Columns_typekey': Columns;
private constructor();
Add(BeforeColumn?: any): Column;
readonly Application: Application;
AutoFit(): void;
Borders: Borders;
readonly Count: number;
readonly Creator: number;
Delete(): void;
DistributeWidth(): void;
readonly First: Column;
Item(Index: number): Column;
readonly Last: Column;
readonly NestingLevel: number;
readonly Parent: any;
PreferredWidth: number;
PreferredWidthType: WdPreferredWidthType;
Select(): void;
SetWidth(ColumnWidth: number, RulerStyle: WdRulerStyle): void;
readonly Shading: Shading;
Width: number;
}
class Comment {
private 'Word.Comment_typekey': Comment;
private constructor();
readonly Application: Application;
Author: string;
readonly Creator: number;
readonly Date: VarDate;
Delete(): void;
Edit(): void;
readonly Index: number;
Initial: string;
readonly IsInk: boolean;
readonly Parent: any;
readonly Range: Range;
readonly Reference: Range;
readonly Scope: Range;
ShowTip: boolean;
}
class Comments {
private 'Word.Comments_typekey': Comments;
private constructor();
Add(Range: Range, Text?: any): Comment;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Comment;
readonly Parent: any;
ShowBy: string;
}
class ConditionalStyle {
private 'Word.ConditionalStyle_typekey': ConditionalStyle;
private constructor();
readonly Application: Application;
Borders: Borders;
BottomPadding: number;
readonly Creator: number;
Font: Font;
LeftPadding: number;
ParagraphFormat: ParagraphFormat;
readonly Parent: any;
RightPadding: number;
readonly Shading: Shading;
TopPadding: number;
}
class Conflict {
private 'Word.Conflict_typekey': Conflict;
private constructor();
Accept(): void;
readonly Application: Application;
readonly Creator: number;
readonly Index: number;
readonly Parent: any;
readonly Range: Range;
Reject(): void;
readonly Type: WdRevisionType;
}
class Conflicts {
private 'Word.Conflicts_typekey': Conflicts;
private constructor();
AcceptAll(): void;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Conflict;
readonly Parent: any;
RejectAll(): void;
}
class ConnectorFormat {
private 'Word.ConnectorFormat_typekey': ConnectorFormat;
private constructor();
readonly Application: Application;
BeginConnect(ConnectedShape: Shape, ConnectionSite: number): void;
readonly BeginConnected: Office.MsoTriState;
readonly BeginConnectedShape: Shape;
readonly BeginConnectionSite: number;
BeginDisconnect(): void;
readonly Creator: number;
EndConnect(ConnectedShape: Shape, ConnectionSite: number): void;
readonly EndConnected: Office.MsoTriState;
readonly EndConnectedShape: Shape;
readonly EndConnectionSite: number;
EndDisconnect(): void;
readonly Parent: any;
Type: Office.MsoConnectorType;
}
class ContentControl {
private 'Word.ContentControl_typekey': ContentControl;
private constructor();
readonly Application: Application;
BuildingBlockCategory: string;
BuildingBlockType: WdBuildingBlockTypes;
Checked: boolean;
Copy(): void;
readonly Creator: number;
Cut(): void;
DateCalendarType: WdCalendarType;
DateDisplayFormat: string;
DateDisplayLocale: WdLanguageID;
DateStorageFormat: WdContentControlDateStorageFormat;
DefaultTextStyle: any;
/** @param boolean [DeleteContents=false] */
Delete(DeleteContents?: boolean): void;
readonly DropdownListEntries: ContentControlListEntries;
readonly ID: string;
LockContentControl: boolean;
LockContents: boolean;
MultiLine: boolean;
readonly Parent: any;
readonly ParentContentControl: ContentControl;
readonly PlaceholderText: BuildingBlock;
readonly Range: Range;
/** @param string [Font=''] */
SetCheckedSymbol(CharacterNumber: number, Font?: string): void;
/**
* @param Word.BuildingBlock [BuildingBlock=0]
* @param Word.Range [Range=0]
* @param string [Text='']
*/
SetPlaceholderText(BuildingBlock?: BuildingBlock, Range?: Range, Text?: string): void;
/** @param string [Font=''] */
SetUncheckedSymbol(CharacterNumber: number, Font?: string): void;
readonly ShowingPlaceholderText: boolean;
Tag: string;
Temporary: boolean;
Title: string;
Type: WdContentControlType;
Ungroup(): void;
readonly XMLMapping: XMLMapping;
}
class ContentControlListEntries {
private 'Word.ContentControlListEntries_typekey': ContentControlListEntries;
private constructor();
/**
* @param string [Value='']
* @param number [Index=0]
*/
Add(Text: string, Value?: string, Index?: number): ContentControlListEntry;
readonly Application: Application;
Clear(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: number): ContentControlListEntry;
readonly Parent: any;
}
class ContentControlListEntry {
private 'Word.ContentControlListEntry_typekey': ContentControlListEntry;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
Index: number;
MoveDown(): void;
MoveUp(): void;
readonly Parent: any;
Select(): void;
Text: string;
Value: string;
}
class ContentControls {
private 'Word.ContentControls_typekey': ContentControls;
private constructor();
/** @param Word.WdContentControlType [Type=0] */
Add(Type?: WdContentControlType, Range?: any): ContentControl;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): ContentControl;
readonly Parent: any;
}
class Corners {
private 'Word.Corners_typekey': Corners;
private constructor();
readonly Application: any;
readonly Creator: number;
readonly Name: string;
readonly Parent: any;
Select(): any;
}
class CustomLabel {
private 'Word.CustomLabel_typekey': CustomLabel;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly DotMatrix: boolean;
Height: number;
HorizontalPitch: number;
readonly Index: number;
Name: string;
NumberAcross: number;
NumberDown: number;
PageSize: WdCustomLabelPageSize;
readonly Parent: any;
SideMargin: number;
TopMargin: number;
readonly Valid: boolean;
VerticalPitch: number;
Width: number;
}
class CustomLabels {
private 'Word.CustomLabels_typekey': CustomLabels;
private constructor();
Add(Name: string, DotMatrix?: any): CustomLabel;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): CustomLabel;
readonly Parent: any;
}
class CustomProperties {
private 'Word.CustomProperties_typekey': CustomProperties;
private constructor();
Add(Name: string, Value: string): CustomProperty;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): CustomProperty;
readonly Parent: any;
}
class CustomProperty {
private 'Word.CustomProperty_typekey': CustomProperty;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Name: string;
readonly Parent: any;
Value: string;
}
class DataTable {
private 'Word.DataTable_typekey': DataTable;
private constructor();
readonly Application: any;
AutoScaleFont: any;
readonly Border: ChartBorder;
readonly Creator: number;
Delete(): void;
readonly Font: ChartFont;
readonly Format: ChartFormat;
HasBorderHorizontal: boolean;
HasBorderOutline: boolean;
HasBorderVertical: boolean;
readonly Parent: any;
Select(): void;
ShowLegendKey: boolean;
}
class DefaultWebOptions {
private 'Word.DefaultWebOptions_typekey': DefaultWebOptions;
private constructor();
AllowPNG: boolean;
AlwaysSaveInDefaultEncoding: boolean;
readonly Application: Application;
BrowserLevel: WdBrowserLevel;
CheckIfOfficeIsHTMLEditor: boolean;
CheckIfWordIsDefaultHTMLEditor: boolean;
readonly Creator: number;
Encoding: Office.MsoEncoding;
readonly FolderSuffix: string;
readonly Fonts: Office.WebPageFonts;
OptimizeForBrowser: boolean;
OrganizeInFolder: boolean;
readonly Parent: any;
PixelsPerInch: number;
RelyOnCSS: boolean;
RelyOnVML: boolean;
SaveNewWebPagesAsWebArchives: boolean;
ScreenSize: Office.MsoScreenSize;
TargetBrowser: Office.MsoTargetBrowser;
UpdateLinksOnSave: boolean;
UseLongFileNames: boolean;
}
class Diagram {
private 'Word.Diagram_typekey': Diagram;
private constructor();
readonly Application: Application;
AutoFormat: Office.MsoTriState;
AutoLayout: Office.MsoTriState;
Convert(Type: Office.MsoDiagramType): void;
readonly Creator: number;
FitText(): void;
readonly Nodes: DiagramNodes;
readonly Parent: any;
Reverse: Office.MsoTriState;
readonly Type: Office.MsoDiagramType;
}
class DiagramNode {
private 'Word.DiagramNode_typekey': DiagramNode;
private constructor();
/**
* @param Office.MsoRelativeNodePosition [Pos=2]
* @param Office.MsoDiagramNodeType [NodeType=1]
*/
AddNode(Pos?: Office.MsoRelativeNodePosition, NodeType?: Office.MsoDiagramNodeType): DiagramNode;
readonly Application: Application;
readonly Children: DiagramNodeChildren;
/**
* @param Word.DiagramNode [TargetNode=0]
* @param Office.MsoRelativeNodePosition [Pos=2]
*/
CloneNode(copyChildren: boolean, TargetNode?: DiagramNode, Pos?: Office.MsoRelativeNodePosition): DiagramNode;
readonly Creator: number;
Delete(): void;
readonly Diagram: Diagram;
Layout: Office.MsoOrgChartLayoutType;
MoveNode(TargetNode: DiagramNode, Pos: Office.MsoRelativeNodePosition): void;
NextNode(): DiagramNode;
readonly Parent: any;
PrevNode(): DiagramNode;
ReplaceNode(TargetNode: DiagramNode): void;
readonly Root: DiagramNode;
readonly Shape: Shape;
/** @param Office.MsoRelativeNodePosition [Pos=-1] */
SwapNode(TargetNode: DiagramNode, Pos?: Office.MsoRelativeNodePosition): void;
readonly TextShape: Shape;
TransferChildren(ReceivingNode: DiagramNode): void;
}
class DiagramNodeChildren {
private 'Word.DiagramNodeChildren_typekey': DiagramNodeChildren;
private constructor();
/**
* @param any [Index=-1]
* @param Office.MsoDiagramNodeType [NodeType=1]
*/
AddNode(Index?: any, NodeType?: Office.MsoDiagramNodeType): DiagramNode;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
readonly FirstChild: DiagramNode;
Item(Index: any): DiagramNode;
readonly LastChild: DiagramNode;
readonly Parent: any;
SelectAll(): void;
}
class DiagramNodes {
private 'Word.DiagramNodes_typekey': DiagramNodes;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): DiagramNode;
readonly Parent: any;
SelectAll(): void;
}
class Dialog {
private 'Word.Dialog_typekey': Dialog;
private constructor();
readonly Application: Application;
readonly CommandBarId: number;
readonly CommandName: string;
readonly Creator: number;
DefaultTab: WdWordDialogTab;
Display(TimeOut?: number): number;
Execute(): void;
readonly Parent: any;
Show(TimeOut?: any): number;
readonly Type: WdWordDialog;
Update(): void;
}
class Dialogs {
private 'Word.Dialogs_typekey': Dialogs;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: WdWordDialog): Dialog;
readonly Parent: any;
}
class Dictionaries {
private 'Word.Dictionaries_typekey': Dictionaries;
private constructor();
ActiveCustomDictionary: Dictionary;
Add(FileName: string): Dictionary;
readonly Application: Application;
ClearAll(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Dictionary;
readonly Maximum: number;
readonly Parent: any;
}
class Dictionary {
private 'Word.Dictionary_typekey': Dictionary;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
LanguageID: WdLanguageID;
LanguageSpecific: boolean;
readonly Name: string;
readonly Parent: any;
readonly Path: string;
readonly ReadOnly: boolean;
readonly Type: WdDictionaryType;
}
class Document {
private 'Word.Document_typekey': Document;
private constructor();
_CodeName: string;
AcceptAllRevisions(): void;
AcceptAllRevisionsShown(): void;
Activate(): void;
readonly ActiveTheme: string;
readonly ActiveThemeDisplayName: string;
readonly ActiveWindow: Window;
ActiveWritingStyle(LanguageID: any): string;
AddDocumentWorkspaceHeader(RichFormat: boolean, Url: string, Title: string, Description: string, ID: string): void;
AddMeetingWorkspaceHeader(SkipIfAbsent: boolean, Url: string, Title: string, Description: string, ID: string): void;
AddToFavorites(): void;
readonly Application: Application;
ApplyDocumentTheme(FileName: string): void;
ApplyQuickStyleSet(Name: string): void;
ApplyQuickStyleSet2(Style: any): void;
ApplyTheme(Name: string): void;
AttachedTemplate: Template;
AutoFormat(): void;
AutoFormatOverride: boolean;
AutoHyphenation: boolean;
AutoSummarize(Length?: any, Mode?: any, UpdateProperties?: any): Range;
Background: Shape;
readonly Bibliography: Bibliography;
readonly Bookmarks: Bookmarks;
readonly BuiltInDocumentProperties: Office.DocumentProperties<Application>;
CanCheckin(): boolean;
readonly Characters: Characters;
CheckConsistency(): void;
CheckGrammar(): void;
/**
* @param boolean [SaveChanges=true]
* @param boolean [MakePublic=false]
*/
CheckIn(SaveChanges?: boolean, Comments?: any, MakePublic?: boolean): void;
/**
* @param boolean [SaveChanges=true]
* @param boolean [MakePublic=false]
*/
CheckInWithVersion(SaveChanges?: boolean, Comments?: any, MakePublic?: boolean, VersionType?: any): void;
CheckNewSmartTags(): void;
CheckSpelling(
CustomDictionary?: any, IgnoreUppercase?: any, AlwaysSuggest?: any, CustomDictionary2?: any, CustomDictionary3?: any, CustomDictionary4?: any,
CustomDictionary5?: any, CustomDictionary6?: any, CustomDictionary7?: any, CustomDictionary8?: any, CustomDictionary9?: any, CustomDictionary10?: any): void;
readonly ChildNodeSuggestions: XMLChildNodeSuggestions;
ClickAndTypeParagraphStyle: any;
Close(SaveChanges?: any, OriginalFormat?: any, RouteDocument?: any): void;
ClosePrintPreview(): void;
readonly CoAuthoring: CoAuthoring;
readonly CodeName: string;
readonly CommandBars: Office.CommandBars;
readonly Comments: Comments;
Compare(
Name: string, AuthorName?: any, CompareTarget?: any, DetectFormatChanges?: any, IgnoreAllComparisonWarnings?: any, AddToRecentFiles?: any,
RemovePersonalInformation?: any, RemoveDateAndTime?: any): void;
Compare2000(Name: string): void;
Compare2002(Name: string, AuthorName?: any, CompareTarget?: any, DetectFormatChanges?: any, IgnoreAllComparisonWarnings?: any, AddToRecentFiles?: any): void;
Compatibility(Type: WdCompatibility): boolean;
readonly CompatibilityMode: number;
ComputeStatistics(Statistic: WdStatistic, IncludeFootnotesAndEndnotes?: any): number;
ConsecutiveHyphensLimit: number;
readonly Container: any;
readonly Content: Range;
readonly ContentControls: ContentControls;
readonly ContentTypeProperties: Office.MetaProperties;
Convert(): void;
ConvertAutoHyphens(): void;
ConvertNumbersToText(NumberType?: any): void;
ConvertVietDoc(CodePageOrigin: number): void;
CopyStylesFromTemplate(Template: string): void;
CountNumberedItems(NumberType?: any, Level?: any): number;
CreateLetterContent(
DateFormat: string, IncludeHeaderFooter: boolean, PageDesign: string, LetterStyle: WdLetterStyle, Letterhead: boolean,
LetterheadLocation: WdLetterheadLocation, LetterheadSize: number, RecipientName: string, RecipientAddress: string, Salutation: string,
SalutationType: WdSalutationType, RecipientReference: string, MailingInstructions: string, AttentionLine: string, Subject: string, CCList: string,
ReturnAddress: string, SenderName: string, Closing: string, SenderCompany: string, SenderJobTitle: string, SenderInitials: string, EnclosureNumber: number,
InfoBlock?: any, RecipientCode?: any, RecipientGender?: any, ReturnAddressShortForm?: any, SenderCity?: any, SenderCode?: any, SenderGender?: any, SenderReference?: any): LetterContent;
readonly Creator: number;
readonly CurrentRsid: number;
readonly CustomDocumentProperties: Office.DocumentProperties<Application>;
readonly CustomXMLParts: Office.CustomXMLParts;
DataForm(): void;
readonly DefaultTableStyle: any;
DefaultTabStop: number;
DefaultTargetFrame: string;
DeleteAllComments(): void;
DeleteAllCommentsShown(): void;
DeleteAllEditableRanges(EditorID?: any): void;
DeleteAllInkAnnotations(): void;
DetectLanguage(): void;
DisableFeatures: boolean;
DisableFeaturesIntroducedAfter: WdDisableFeaturesIntroducedAfter;
readonly DocID: number;
readonly DocumentInspectors: Office.DocumentInspectors;
readonly DocumentLibraryVersions: Office.DocumentLibraryVersions;
readonly DocumentTheme: Office.OfficeTheme;
DoNotEmbedSystemFonts: boolean;
DowngradeDocument(): void;
readonly Dummy1: undefined;
Dummy2(): void;
readonly Dummy3: undefined;
Dummy4(): void;
EditionOptions(Type: WdEditionType, Option: WdEditionOption, Name: string, Format?: any): void;
readonly Email: Email;
EmbedLinguisticData: boolean;
EmbedSmartTags: boolean;
EmbedTrueTypeFonts: boolean;
EncryptionProvider: string;
readonly Endnotes: Endnotes;
EndReview(): void;
EnforceStyle: boolean;
readonly Envelope: Envelope;
/**
* @param boolean [OpenAfterExport=false]
* @param Word.WdExportOptimizeFor [OptimizeFor=0]
* @param Word.WdExportRange [Range=0]
* @param number [From=1]
* @param number [To=1]
* @param Word.WdExportItem [Item=0]
* @param boolean [IncludeDocProps=false]
* @param boolean [KeepIRM=true]
* @param Word.WdExportCreateBookmarks [CreateBookmarks=0]
* @param boolean [DocStructureTags=true]
* @param boolean [BitmapMissingFonts=true]
* @param boolean [UseISO19005_1=false]
*/
ExportAsFixedFormat(
OutputFileName: string, ExportFormat: WdExportFormat, OpenAfterExport?: boolean, OptimizeFor?: WdExportOptimizeFor, Range?: WdExportRange, From?: number,
To?: number, Item?: WdExportItem, IncludeDocProps?: boolean, KeepIRM?: boolean, CreateBookmarks?: WdExportCreateBookmarks, DocStructureTags?: boolean,
BitmapMissingFonts?: boolean, UseISO19005_1?: boolean, FixedFormatExtClassPtr?: any): void;
FarEastLineBreakLanguage: WdFarEastLineBreakLanguageID;
FarEastLineBreakLevel: WdFarEastLineBreakLevel;
readonly Fields: Fields;
Final: boolean;
FitToPages(): void;
FollowHyperlink(Address?: any, SubAddress?: any, NewWindow?: any, AddHistory?: any, ExtraInfo?: any, Method?: any, HeaderInfo?: any): void;
readonly Footnotes: Footnotes;
FormattingShowClear: boolean;
FormattingShowFilter: WdShowFilter;
FormattingShowFont: boolean;
FormattingShowNextLevel: boolean;
FormattingShowNumbering: boolean;
FormattingShowParagraph: boolean;
FormattingShowUserStyleName: boolean;
readonly FormFields: FormFields;
readonly FormsDesign: boolean;
ForwardMailer(): void;
readonly Frames: Frames;
readonly Frameset: Frameset;
FreezeLayout(): void;
readonly FullName: string;
GetCrossReferenceItems(ReferenceType: any): any;
GetLetterContent(): LetterContent;
GetWorkflowTasks(): Office.WorkflowTasks;
GetWorkflowTemplates(): Office.WorkflowTemplates;
GoTo(What?: any, Which?: any, Count?: any, Name?: any): Range;
GrammarChecked: boolean;
readonly GrammaticalErrors: ProofreadingErrors;
GridDistanceHorizontal: number;
GridDistanceVertical: number;
GridOriginFromMargin: boolean;
GridOriginHorizontal: number;
GridOriginVertical: number;
GridSpaceBetweenHorizontalLines: number;
GridSpaceBetweenVerticalLines: number;
HasMailer: boolean;
readonly HasPassword: boolean;
HasRoutingSlip: boolean;
readonly HasVBProject: boolean;
readonly HTMLDivisions: HTMLDivisions;
readonly HTMLProject: Office.HTMLProject;
readonly Hyperlinks: Hyperlinks;
HyphenateCaps: boolean;
HyphenationZone: number;
readonly Indexes: Indexes;
readonly InlineShapes: InlineShapes;
readonly IsMasterDocument: boolean;
readonly IsSubdocument: boolean;
JustificationMode: WdJustificationMode;
KerningByAlgorithm: boolean;
Kind: WdDocumentKind;
LanguageDetected: boolean;
readonly ListParagraphs: ListParagraphs;
readonly Lists: Lists;
readonly ListTemplates: ListTemplates;
LockQuickStyleSet: boolean;
LockServerFile(): void;
LockTheme: boolean;
readonly MailEnvelope: Office.MsoEnvelope;
readonly Mailer: Mailer;
readonly MailMerge: MailMerge;
MakeCompatibilityDefault(): void;
ManualHyphenation(): void;
Merge(FileName: string, MergeTarget?: any, DetectFormatChanges?: any, UseFormattingFrom?: any, AddToRecentFiles?: any): void;
Merge2000(FileName: string): void;
readonly Name: string;
NoLineBreakAfter: string;
NoLineBreakBefore: string;
OMathBreakBin: WdOMathBreakBin;
OMathBreakSub: WdOMathBreakSub;
OMathFontName: string;
OMathIntSubSupLim: boolean;
OMathJc: WdOMathJc;
OMathLeftMargin: number;
OMathNarySupSubLim: boolean;
OMathRightMargin: number;
readonly OMaths: OMaths;
OMathSmallFrac: boolean;
OMathWrap: number;
readonly OpenEncoding: Office.MsoEncoding;
OptimizeForWord97: boolean;
readonly OriginalDocumentTitle: string;
PageSetup: PageSetup;
readonly Paragraphs: Paragraphs;
readonly Parent: any;
readonly Password: string;
readonly PasswordEncryptionAlgorithm: string;
readonly PasswordEncryptionFileProperties: boolean;
readonly PasswordEncryptionKeyLength: number;
readonly PasswordEncryptionProvider: string;
readonly Path: string;
readonly Permission: Office.Permission;
Post(): void;
PresentIt(): void;
PrintFormsData: boolean;
PrintFractionalWidths: boolean;
PrintOut(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any, PrintZoomColumn?: any, PrintZoomRow?: any, PrintZoomPaperWidth?: any,
PrintZoomPaperHeight?: any): void;
PrintOut2000(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any, PrintZoomColumn?: any, PrintZoomRow?: any, PrintZoomPaperWidth?: any,
PrintZoomPaperHeight?: any): void;
PrintOutOld(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any): void;
PrintPostScriptOverText: boolean;
PrintPreview(): void;
PrintRevisions: boolean;
Protect(Type: WdProtectionType, NoReset?: any, Password?: any, UseIRM?: any, EnforceStyleLock?: any): void;
Protect2002(Type: WdProtectionType, NoReset?: any, Password?: any): void;
readonly ProtectionType: WdProtectionType;
Range(Start?: number, End?: number): Range;
readonly ReadabilityStatistics: ReadabilityStatistics;
ReadingLayoutSizeX: number;
ReadingLayoutSizeY: number;
ReadingModeLayoutFrozen: boolean;
readonly ReadOnly: boolean;
ReadOnlyRecommended: boolean;
RecheckSmartTags(): void;
Redo(Times?: any): boolean;
RejectAllRevisions(): void;
RejectAllRevisionsShown(): void;
Reload(): void;
ReloadAs(Encoding: Office.MsoEncoding): void;
RemoveDateAndTime: boolean;
RemoveDocumentInformation(RemoveDocInfoType: WdRemoveDocInfoType): void;
RemoveDocumentWorkspaceHeader(ID: string): void;
RemoveLockedStyles(): void;
RemoveNumbers(NumberType?: any): void;
RemovePersonalInformation: boolean;
RemoveSmartTags(): void;
RemoveTheme(): void;
Repaginate(): void;
Reply(): void;
ReplyAll(): void;
ReplyWithChanges(ShowMessage?: any): void;
readonly Research: Research;
ResetFormFields(): void;
readonly RevisedDocumentTitle: string;
readonly Revisions: Revisions;
Route(): void;
readonly Routed: boolean;
readonly RoutingSlip: RoutingSlip;
RunAutoMacro(Which: WdAutoMacros): void;
RunLetterWizard(LetterContent?: any, WizardMode?: any): void;
Save(): void;
SaveAs(
FileName?: any, FileFormat?: any, LockComments?: any, Password?: any, AddToRecentFiles?: any, WritePassword?: any, ReadOnlyRecommended?: any,
EmbedTrueTypeFonts?: any, SaveNativePictureFormat?: any, SaveFormsData?: any, SaveAsAOCELetter?: any, Encoding?: any, InsertLineBreaks?: any,
AllowSubstitutions?: any, LineEnding?: any, AddBiDiMarks?: any): void;
SaveAs2(
FileName?: any, FileFormat?: any, LockComments?: any, Password?: any, AddToRecentFiles?: any, WritePassword?: any, ReadOnlyRecommended?: any,
EmbedTrueTypeFonts?: any, SaveNativePictureFormat?: any, SaveFormsData?: any, SaveAsAOCELetter?: any, Encoding?: any, InsertLineBreaks?: any,
AllowSubstitutions?: any, LineEnding?: any, AddBiDiMarks?: any, CompatibilityMode?: any): void;
SaveAs2000(
FileName?: any, FileFormat?: any, LockComments?: any, Password?: any, AddToRecentFiles?: any, WritePassword?: any, ReadOnlyRecommended?: any,
EmbedTrueTypeFonts?: any, SaveNativePictureFormat?: any, SaveFormsData?: any, SaveAsAOCELetter?: any): void;
SaveAsQuickStyleSet(FileName: string): void;
Saved: boolean;
SaveEncoding: Office.MsoEncoding;
readonly SaveFormat: number;
SaveFormsData: boolean;
SaveSubsetFonts: boolean;
sblt(s: string): void;
readonly Scripts: Office.Scripts;
readonly Sections: Sections;
Select(): void;
SelectAllEditableRanges(EditorID?: any): void;
SelectContentControlsByTag(Tag: string): ContentControls;
SelectContentControlsByTitle(Title: string): ContentControls;
SelectLinkedControls(Node: Office.CustomXMLNode): ContentControls;
/**
* @param string [PrefixMapping='']
* @param boolean [FastSearchSkippingTextNodes=true]
*/
SelectNodes(XPath: string, PrefixMapping?: string, FastSearchSkippingTextNodes?: boolean): XMLNodes;
/**
* @param string [PrefixMapping='']
* @param boolean [FastSearchSkippingTextNodes=true]
*/
SelectSingleNode(XPath: string, PrefixMapping?: string, FastSearchSkippingTextNodes?: boolean): XMLNode;
/** @param Office.CustomXMLPart [Stream=0] */
SelectUnlinkedControls(Stream?: Office.CustomXMLPart): ContentControls;
SendFax(Address: string, Subject?: any): void;
SendFaxOverInternet(Recipients?: any, Subject?: any, ShowMessage?: any): void;
SendForReview(Recipients?: any, Subject?: any, ShowMessage?: any, IncludeAttachment?: any): void;
SendMail(): void;
SendMailer(FileFormat?: any, Priority?: any): void;
readonly Sentences: Sentences;
readonly ServerPolicy: Office.ServerPolicy;
SetCompatibilityMode(Mode: number): void;
SetDefaultTableStyle(Style: any, SetInTemplate: boolean): void;
SetLetterContent(LetterContent: any): void;
SetPasswordEncryptionOptions(PasswordEncryptionProvider: string, PasswordEncryptionAlgorithm: string, PasswordEncryptionKeyLength: number, PasswordEncryptionFileProperties?: any): void;
readonly Shapes: Shapes;
readonly SharedWorkspace: Office.SharedWorkspace;
ShowGrammaticalErrors: boolean;
ShowRevisions: boolean;
ShowSpellingErrors: boolean;
ShowSummary: boolean;
readonly Signatures: Office.SignatureSet;
readonly SmartDocument: Office.SmartDocument;
readonly SmartTags: SmartTags;
SmartTagsAsXMLProps: boolean;
SnapToGrid: boolean;
SnapToShapes: boolean;
SpellingChecked: boolean;
readonly SpellingErrors: ProofreadingErrors;
readonly StoryRanges: StoryRanges;
readonly Styles: Styles;
readonly StyleSheets: StyleSheets;
StyleSortMethod: WdStyleSort;
readonly Subdocuments: Subdocuments;
SummaryLength: number;
SummaryViewMode: WdSummaryMode;
readonly Sync: Office.Sync;
readonly Tables: Tables;
readonly TablesOfAuthorities: TablesOfAuthorities;
readonly TablesOfAuthoritiesCategories: TablesOfAuthoritiesCategories;
readonly TablesOfContents: TablesOfContents;
readonly TablesOfFigures: TablesOfFigures;
TextEncoding: Office.MsoEncoding;
TextLineEnding: WdLineEndingType;
ToggleFormsDesign(): void;
TrackFormatting: boolean;
TrackMoves: boolean;
TrackRevisions: boolean;
/** @param boolean [DataOnly=true] */
TransformDocument(Path: string, DataOnly?: boolean): void;
readonly Type: WdDocumentType;
Undo(Times?: any): boolean;
UndoClear(): void;
UnfreezeLayout(): void;
Unprotect(Password?: any): void;
UpdateStyles(): void;
UpdateStylesOnOpen: boolean;
UpdateSummaryProperties(): void;
UseMathDefaults: boolean;
UserControl: boolean;
readonly Variables: Variables;
readonly VBASigned: boolean;
readonly VBProject: VBIDE.VBProject;
readonly Versions: Versions;
ViewCode(): void;
ViewPropertyBrowser(): void;
readonly WebOptions: WebOptions;
WebPagePreview(): void;
readonly Windows: Windows;
readonly WordOpenXML: string;
readonly Words: Words;
readonly WritePassword: string;
readonly WriteReserved: boolean;
XMLHideNamespaces: boolean;
readonly XMLNodes: XMLNodes;
XMLSaveDataOnly: boolean;
XMLSaveThroughXSLT: string;
readonly XMLSchemaReferences: XMLSchemaReferences;
readonly XMLSchemaViolations: XMLNodes;
XMLShowAdvancedErrors: boolean;
XMLUseXSLTWhenSaving: boolean;
}
class Documents {
private 'Word.Documents_typekey': Documents;
private constructor();
Add(Template?: string, NewTemplate?: boolean, DocumentType?: WdNewDocumentType, Visible?: boolean): Document;
/** @param string [PostID=''] */
AddBlogDocument(ProviderID: string, PostURL: string, BlogName: string, PostID?: string): Document;
AddOld(Template?: any, NewTemplate?: any): Document;
readonly Application: Application;
CanCheckOut(FileName: string): boolean;
CheckOut(FileName: string): void;
Close(SaveChanges?: any, OriginalFormat?: any, RouteDocument?: any): void;
readonly Count: number;
readonly Creator: number;
Item(Index: number | string): Document;
Open(
FileName: any, ConfirmConversions?: any, ReadOnly?: any, AddToRecentFiles?: any, PasswordDocument?: any, PasswordTemplate?: any, Revert?: any,
WritePasswordDocument?: any, WritePasswordTemplate?: any, Format?: any, Encoding?: any, Visible?: any, OpenAndRepair?: any, DocumentDirection?: any,
NoEncodingDialog?: any, XMLTransform?: any): Document;
Open2000(
FileName: any, ConfirmConversions?: any, ReadOnly?: any, AddToRecentFiles?: any, PasswordDocument?: any, PasswordTemplate?: any, Revert?: any,
WritePasswordDocument?: any, WritePasswordTemplate?: any, Format?: any, Encoding?: any, Visible?: any): Document;
Open2002(
FileName: any, ConfirmConversions?: any, ReadOnly?: any, AddToRecentFiles?: any, PasswordDocument?: any, PasswordTemplate?: any, Revert?: any,
WritePasswordDocument?: any, WritePasswordTemplate?: any, Format?: any, Encoding?: any, Visible?: any, OpenAndRepair?: any, DocumentDirection?: any, NoEncodingDialog?: any): Document;
OpenNoRepairDialog(
FileName: any, ConfirmConversions?: any, ReadOnly?: any, AddToRecentFiles?: any, PasswordDocument?: any, PasswordTemplate?: any, Revert?: any,
WritePasswordDocument?: any, WritePasswordTemplate?: any, Format?: any, Encoding?: any, Visible?: any, OpenAndRepair?: any, DocumentDirection?: any,
NoEncodingDialog?: any, XMLTransform?: any): Document;
OpenOld(
FileName: any, ConfirmConversions?: any, ReadOnly?: any, AddToRecentFiles?: any, PasswordDocument?: any, PasswordTemplate?: any, Revert?: any,
WritePasswordDocument?: any, WritePasswordTemplate?: any, Format?: any): Document;
readonly Parent: any;
Save(NoPrompt?: any, OriginalFormat?: any): void;
}
class DownBars {
private 'Word.DownBars_typekey': DownBars;
private constructor();
readonly Application: any;
readonly Border: ChartBorder;
readonly Creator: number;
Delete(): any;
readonly Fill: ChartFillFormat;
readonly Format: ChartFormat;
readonly Interior: Interior;
readonly Name: string;
readonly Parent: any;
Select(): any;
}
class DropCap {
private 'Word.DropCap_typekey': DropCap;
private constructor();
readonly Application: Application;
Clear(): void;
readonly Creator: number;
DistanceFromText: number;
Enable(): void;
FontName: string;
LinesToDrop: number;
readonly Parent: any;
Position: WdDropPosition;
}
class DropDown {
private 'Word.DropDown_typekey': DropDown;
private constructor();
readonly Application: Application;
readonly Creator: number;
Default: number;
readonly ListEntries: ListEntries;
readonly Parent: any;
readonly Valid: boolean;
Value: number;
}
class DropLines {
private 'Word.DropLines_typekey': DropLines;
private constructor();
readonly Application: any;
readonly Border: ChartBorder;
readonly Creator: number;
Delete(): void;
readonly Format: ChartFormat;
readonly Name: string;
readonly Parent: any;
Select(): void;
}
class Editor {
private 'Word.Editor_typekey': Editor;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
DeleteAll(): void;
readonly ID: string;
readonly Name: string;
readonly NextRange: Range;
readonly Parent: any;
readonly Range: Range;
SelectAll(): void;
}
class Editors {
private 'Word.Editors_typekey': Editors;
private constructor();
Add(EditorID: any): Editor;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Editor;
readonly Parent: any;
}
class Email {
private 'Word.Email_typekey': Email;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly CurrentEmailAuthor: EmailAuthor;
readonly Parent: any;
}
class EmailAuthor {
private 'Word.EmailAuthor_typekey': EmailAuthor;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Parent: any;
readonly Style: Style;
}
class EmailOptions {
private 'Word.EmailOptions_typekey': EmailOptions;
private constructor();
readonly Application: Application;
AutoFormatAsYouTypeApplyBorders: boolean;
AutoFormatAsYouTypeApplyBulletedLists: boolean;
AutoFormatAsYouTypeApplyClosings: boolean;
AutoFormatAsYouTypeApplyDates: boolean;
AutoFormatAsYouTypeApplyFirstIndents: boolean;
AutoFormatAsYouTypeApplyHeadings: boolean;
AutoFormatAsYouTypeApplyNumberedLists: boolean;
AutoFormatAsYouTypeApplyTables: boolean;
AutoFormatAsYouTypeAutoLetterWizard: boolean;
AutoFormatAsYouTypeDefineStyles: boolean;
AutoFormatAsYouTypeDeleteAutoSpaces: boolean;
AutoFormatAsYouTypeFormatListItemBeginning: boolean;
AutoFormatAsYouTypeInsertClosings: boolean;
AutoFormatAsYouTypeInsertOvers: boolean;
AutoFormatAsYouTypeMatchParentheses: boolean;
AutoFormatAsYouTypeReplaceFarEastDashes: boolean;
AutoFormatAsYouTypeReplaceFractions: boolean;
AutoFormatAsYouTypeReplaceHyperlinks: boolean;
AutoFormatAsYouTypeReplaceOrdinals: boolean;
AutoFormatAsYouTypeReplacePlainTextEmphasis: boolean;
AutoFormatAsYouTypeReplaceQuotes: boolean;
AutoFormatAsYouTypeReplaceSymbols: boolean;
readonly ComposeStyle: Style;
readonly Creator: number;
readonly Dummy1: boolean;
readonly Dummy2: boolean;
Dummy3(): void;
readonly EmailSignature: EmailSignature;
EmbedSmartTag: boolean;
HTMLFidelity: WdEmailHTMLFidelity;
MarkComments: boolean;
MarkCommentsWith: string;
NewColorOnReply: boolean;
readonly Parent: any;
readonly PlainTextStyle: Style;
RelyOnCSS: boolean;
readonly ReplyStyle: Style;
TabIndentKey: boolean;
ThemeName: string;
UseThemeStyle: boolean;
UseThemeStyleOnReply: boolean;
}
class EmailSignature {
private 'Word.EmailSignature_typekey': EmailSignature;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly EmailSignatureEntries: EmailSignatureEntries;
NewMessageSignature: string;
readonly Parent: any;
ReplyMessageSignature: string;
}
class EmailSignatureEntries {
private 'Word.EmailSignatureEntries_typekey': EmailSignatureEntries;
private constructor();
Add(Name: string, Range: Range): EmailSignatureEntry;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): EmailSignatureEntry;
readonly Parent: any;
}
class EmailSignatureEntry {
private 'Word.EmailSignatureEntry_typekey': EmailSignatureEntry;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
Name: string;
readonly Parent: any;
}
class Endnote {
private 'Word.Endnote_typekey': Endnote;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Parent: any;
readonly Range: Range;
readonly Reference: Range;
}
class EndnoteOptions {
private 'Word.EndnoteOptions_typekey': EndnoteOptions;
private constructor();
readonly Application: Application;
readonly Creator: number;
Location: WdEndnoteLocation;
NumberingRule: WdNumberingRule;
NumberStyle: WdNoteNumberStyle;
readonly Parent: any;
StartingNumber: number;
}
class Endnotes {
private 'Word.Endnotes_typekey': Endnotes;
private constructor();
Add(Range: Range, Reference?: any, Text?: any): Endnote;
readonly Application: Application;
readonly ContinuationNotice: Range;
readonly ContinuationSeparator: Range;
Convert(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Endnote;
Location: WdEndnoteLocation;
NumberingRule: WdNumberingRule;
NumberStyle: WdNoteNumberStyle;
readonly Parent: any;
ResetContinuationNotice(): void;
ResetContinuationSeparator(): void;
ResetSeparator(): void;
readonly Separator: Range;
StartingNumber: number;
SwapWithFootnotes(): void;
}
class Envelope {
private 'Word.Envelope_typekey': Envelope;
private constructor();
readonly Address: Range;
AddressFromLeft: number;
AddressFromTop: number;
readonly AddressStyle: Style;
readonly Application: Application;
readonly Creator: number;
DefaultFaceUp: boolean;
DefaultHeight: number;
DefaultOmitReturnAddress: boolean;
DefaultOrientation: WdEnvelopeOrientation;
DefaultPrintBarCode: boolean;
DefaultPrintFIMA: boolean;
DefaultSize: string;
DefaultWidth: number;
FeedSource: WdPaperTray;
Insert(
ExtractAddress?: any, Address?: any, AutoText?: any, OmitReturnAddress?: any, ReturnAddress?: any, ReturnAutoText?: any, PrintBarCode?: any, PrintFIMA?: any,
Size?: any, Height?: any, Width?: any, FeedSource?: any, AddressFromLeft?: any, AddressFromTop?: any, ReturnAddressFromLeft?: any, ReturnAddressFromTop?: any,
DefaultFaceUp?: any, DefaultOrientation?: any, PrintEPostage?: any, Vertical?: any, RecipientNamefromLeft?: any, RecipientNamefromTop?: any,
RecipientPostalfromLeft?: any, RecipientPostalfromTop?: any, SenderNamefromLeft?: any, SenderNamefromTop?: any, SenderPostalfromLeft?: any, SenderPostalfromTop?: any): void;
Insert2000(
ExtractAddress?: any, Address?: any, AutoText?: any, OmitReturnAddress?: any, ReturnAddress?: any, ReturnAutoText?: any, PrintBarCode?: any, PrintFIMA?: any,
Size?: any, Height?: any, Width?: any, FeedSource?: any, AddressFromLeft?: any, AddressFromTop?: any, ReturnAddressFromLeft?: any, ReturnAddressFromTop?: any,
DefaultFaceUp?: any, DefaultOrientation?: any): void;
Options(): void;
readonly Parent: any;
PrintOut(
ExtractAddress?: any, Address?: any, AutoText?: any, OmitReturnAddress?: any, ReturnAddress?: any, ReturnAutoText?: any, PrintBarCode?: any, PrintFIMA?: any,
Size?: any, Height?: any, Width?: any, FeedSource?: any, AddressFromLeft?: any, AddressFromTop?: any, ReturnAddressFromLeft?: any, ReturnAddressFromTop?: any,
DefaultFaceUp?: any, DefaultOrientation?: any, PrintEPostage?: any, Vertical?: any, RecipientNamefromLeft?: any, RecipientNamefromTop?: any,
RecipientPostalfromLeft?: any, RecipientPostalfromTop?: any, SenderNamefromLeft?: any, SenderNamefromTop?: any, SenderPostalfromLeft?: any, SenderPostalfromTop?: any): void;
PrintOut2000(
ExtractAddress?: any, Address?: any, AutoText?: any, OmitReturnAddress?: any, ReturnAddress?: any, ReturnAutoText?: any, PrintBarCode?: any, PrintFIMA?: any,
Size?: any, Height?: any, Width?: any, FeedSource?: any, AddressFromLeft?: any, AddressFromTop?: any, ReturnAddressFromLeft?: any, ReturnAddressFromTop?: any,
DefaultFaceUp?: any, DefaultOrientation?: any): void;
RecipientNamefromLeft: number;
RecipientNamefromTop: number;
RecipientPostalfromLeft: number;
RecipientPostalfromTop: number;
readonly ReturnAddress: Range;
ReturnAddressFromLeft: number;
ReturnAddressFromTop: number;
readonly ReturnAddressStyle: Style;
SenderNamefromLeft: number;
SenderNamefromTop: number;
SenderPostalfromLeft: number;
SenderPostalfromTop: number;
UpdateDocument(): void;
Vertical: boolean;
}
class Field {
private 'Word.Field_typekey': Field;
private constructor();
readonly Application: Application;
Code: Range;
Copy(): void;
readonly Creator: number;
Cut(): void;
Data: string;
Delete(): void;
DoClick(): void;
readonly Index: number;
readonly InlineShape: InlineShape;
readonly Kind: WdFieldKind;
readonly LinkFormat: LinkFormat;
Locked: boolean;
readonly Next: Field;
readonly OLEFormat: OLEFormat;
readonly Parent: any;
readonly Previous: Field;
Result: Range;
Select(): void;
ShowCodes: boolean;
readonly Type: WdFieldType;
Unlink(): void;
Update(): boolean;
UpdateSource(): void;
}
class Fields {
private 'Word.Fields_typekey': Fields;
private constructor();
Add(Range: Range, Type?: any, Text?: any, PreserveFormatting?: any): Field;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Field;
Locked: number;
readonly Parent: any;
ToggleShowCodes(): void;
Unlink(): void;
Update(): number;
UpdateSource(): void;
}
class FileConverter {
private 'Word.FileConverter_typekey': FileConverter;
private constructor();
readonly Application: Application;
readonly CanOpen: boolean;
readonly CanSave: boolean;
readonly ClassName: string;
readonly Creator: number;
readonly Extensions: string;
readonly FormatName: string;
readonly Name: string;
readonly OpenFormat: number;
readonly Parent: any;
readonly Path: string;
readonly SaveFormat: number;
}
class FileConverters {
private 'Word.FileConverters_typekey': FileConverters;
private constructor();
readonly Application: Application;
ConvertMacWordChevrons: WdChevronConvertRule;
readonly Count: number;
readonly Creator: number;
Item(Index: any): FileConverter;
readonly Parent: any;
}
class FillFormat {
private 'Word.FillFormat_typekey': FillFormat;
private constructor();
readonly Application: Application;
readonly BackColor: ColorFormat;
Background(): void;
readonly Creator: number;
readonly ForeColor: ColorFormat;
GradientAngle: number;
readonly GradientColorType: Office.MsoGradientColorType;
readonly GradientDegree: number;
readonly GradientStops: Office.GradientStops;
readonly GradientStyle: Office.MsoGradientStyle;
readonly GradientVariant: number;
OneColorGradient(Style: Office.MsoGradientStyle, Variant: number, Degree: number): void;
readonly Parent: any;
readonly Pattern: Office.MsoPatternType;
Patterned(Pattern: Office.MsoPatternType): void;
readonly PictureEffects: Office.PictureEffects;
PresetGradient(Style: Office.MsoGradientStyle, Variant: number, PresetGradientType: Office.MsoPresetGradientType): void;
readonly PresetGradientType: Office.MsoPresetGradientType;
readonly PresetTexture: Office.MsoPresetTexture;
PresetTextured(PresetTexture: Office.MsoPresetTexture): void;
RotateWithObject: Office.MsoTriState;
Solid(): void;
TextureAlignment: Office.MsoTextureAlignment;
TextureHorizontalScale: number;
readonly TextureName: string;
TextureOffsetX: number;
TextureOffsetY: number;
TextureTile: Office.MsoTriState;
readonly TextureType: Office.MsoTextureType;
TextureVerticalScale: number;
Transparency: number;
TwoColorGradient(Style: Office.MsoGradientStyle, Variant: number): void;
readonly Type: Office.MsoFillType;
UserPicture(PictureFile: string): void;
UserTextured(TextureFile: string): void;
Visible: Office.MsoTriState;
}
class Find<TParent = Range | Selection> {
private 'Word.Find_typekey': Find;
private constructor();
readonly Application: Application;
ClearAllFuzzyOptions(): void;
ClearFormatting(): void;
ClearHitHighlight(): boolean;
CorrectHangulEndings: boolean;
readonly Creator: number;
Execute(
FindText?: string, MatchCase?: boolean, MatchWholeWord?: boolean, MatchWildcards?: boolean, MatchSoundsLike?: boolean, MatchAllWordForms?: boolean, Forward?: boolean, Wrap?: WdFindWrap,
Format?: boolean, ReplaceWith?: string, Replace?: WdReplace, MatchKashida?: boolean, MatchDiacritics?: boolean, MatchAlefHamza?: boolean, MatchControl?: boolean): boolean;
Execute2007(
FindText?: string, MatchCase?: boolean, MatchWholeWord?: boolean, MatchWildcards?: boolean, MatchSoundsLike?: boolean, MatchAllWordForms?: boolean, Forward?: boolean, Wrap?: WdFindWrap,
Format?: boolean, ReplaceWith?: string, Replace?: WdReplace, MatchKashida?: boolean, MatchDiacritics?: boolean, MatchAlefHamza?: boolean, MatchControl?: boolean, MatchPrefix?: boolean,
MatchSuffix?: boolean, MatchPhrase?: boolean, IgnoreSpace?: boolean, IgnorePunct?: boolean): boolean;
ExecuteOld(
FindText?: string, MatchCase?: boolean, MatchWholeWord?: boolean, MatchWildcards?: boolean, MatchSoundsLike?: boolean, MatchAllWordForms?: boolean, Forward?: boolean, Wrap?: WdFindWrap,
Format?: boolean, ReplaceWith?: string, Replace?: WdReplace): boolean;
Font: Font;
Format: boolean;
Forward: boolean;
readonly Found: boolean;
readonly Frame: Frame;
HanjaPhoneticHangul: boolean;
Highlight: number;
HitHighlight(
FindText: any, HighlightColor?: any, TextColor?: any, MatchCase?: any, MatchWholeWord?: any, MatchPrefix?: any, MatchSuffix?: any, MatchPhrase?: any,
MatchWildcards?: any, MatchSoundsLike?: any, MatchAllWordForms?: any, MatchByte?: any, MatchFuzzy?: any, MatchKashida?: any, MatchDiacritics?: any,
MatchAlefHamza?: any, MatchControl?: any, IgnoreSpace?: any, IgnorePunct?: any, HanjaPhoneticHangul?: any): boolean;
IgnorePunct: boolean;
IgnoreSpace: boolean;
LanguageID: WdLanguageID;
LanguageIDFarEast: WdLanguageID;
LanguageIDOther: WdLanguageID;
MatchAlefHamza: boolean;
MatchAllWordForms: boolean;
MatchByte: boolean;
MatchCase: boolean;
MatchControl: boolean;
MatchDiacritics: boolean;
MatchFuzzy: boolean;
MatchKashida: boolean;
MatchPhrase: boolean;
MatchPrefix: boolean;
MatchSoundsLike: boolean;
MatchSuffix: boolean;
MatchWholeWord: boolean;
MatchWildcards: boolean;
NoProofing: number;
ParagraphFormat: ParagraphFormat;
readonly Parent: TParent;
readonly Replacement: Replacement;
SetAllFuzzyOptions(): void;
Style: any;
Text: string;
Wrap: WdFindWrap;
}
class FirstLetterException {
private 'Word.FirstLetterException_typekey': FirstLetterException;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
}
class FirstLetterExceptions {
private 'Word.FirstLetterExceptions_typekey': FirstLetterExceptions;
private constructor();
Add(Name: string): FirstLetterException;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): FirstLetterException;
readonly Parent: any;
}
class Floor {
private 'Word.Floor_typekey': Floor;
private constructor();
readonly Application: any;
readonly Border: ChartBorder;
ClearFormats(): any;
readonly Creator: number;
readonly Fill: ChartFillFormat;
readonly Format: ChartFormat;
readonly Interior: Interior;
readonly Name: string;
readonly Parent: any;
Paste(): void;
PictureType: any;
Select(): any;
Thickness: number;
}
class Font {
private 'Word.Font_typekey': Font;
private constructor();
AllCaps: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
Animation: WdAnimation;
readonly Application: Application;
Bold: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
BoldBi: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
Borders: Borders;
Color: WdColor;
ColorIndex: WdColorIndex;
ColorIndexBi: WdColorIndex;
ContextualAlternates: number;
readonly Creator: number;
DiacriticColor: WdColor;
DisableCharacterSpaceGrid: boolean;
DoubleStrikeThrough: number;
readonly Duplicate: Font;
Emboss: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
EmphasisMark: WdEmphasisMark;
Engrave: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
Fill: FillFormat;
Glow: GlowFormat;
Grow(): void;
Hidden: number;
Italic: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
ItalicBi: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
Kerning: number;
Ligatures: WdLigatures;
Line: LineFormat;
Name: string;
NameAscii: string;
NameBi: string;
NameFarEast: string;
NameOther: string;
NumberForm: WdNumberForm;
NumberSpacing: WdNumberSpacing;
Outline: number;
readonly Parent: any;
Position: number;
Reflection: ReflectionFormat;
Reset(): void;
Scaling: number;
SetAsTemplateDefault(): void;
readonly Shading: Shading;
Shadow: number;
Shrink(): void;
Size: number;
SizeBi: number;
SmallCaps: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
Spacing: number;
StrikeThrough: number;
StylisticSet: WdStylisticSet;
Subscript: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
Superscript: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
readonly TextColor: ColorFormat;
TextShadow: ShadowFormat;
ThreeD: ThreeDFormat;
Underline: WdUnderline;
UnderlineColor: WdColor;
}
class FontNames {
private 'Word.FontNames_typekey': FontNames;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): string;
readonly Parent: any;
}
class Footnote {
private 'Word.Footnote_typekey': Footnote;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Parent: any;
readonly Range: Range;
readonly Reference: Range;
}
class FootnoteOptions {
private 'Word.FootnoteOptions_typekey': FootnoteOptions;
private constructor();
readonly Application: Application;
readonly Creator: number;
Location: WdFootnoteLocation;
NumberingRule: WdNumberingRule;
NumberStyle: WdNoteNumberStyle;
readonly Parent: any;
StartingNumber: number;
}
class Footnotes {
private 'Word.Footnotes_typekey': Footnotes;
private constructor();
Add(Range: Range, Reference?: any, Text?: any): Footnote;
readonly Application: Application;
readonly ContinuationNotice: Range;
readonly ContinuationSeparator: Range;
Convert(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Footnote;
Location: WdFootnoteLocation;
NumberingRule: WdNumberingRule;
NumberStyle: WdNoteNumberStyle;
readonly Parent: any;
ResetContinuationNotice(): void;
ResetContinuationSeparator(): void;
ResetSeparator(): void;
readonly Separator: Range;
StartingNumber: number;
SwapWithEndnotes(): void;
}
class FormField {
private 'Word.FormField_typekey': FormField;
private constructor();
readonly Application: Application;
CalculateOnExit: boolean;
readonly CheckBox: CheckBox;
Copy(): void;
readonly Creator: number;
Cut(): void;
Delete(): void;
readonly DropDown: DropDown;
Enabled: boolean;
EntryMacro: string;
ExitMacro: string;
HelpText: string;
Name: string;
readonly Next: FormField;
OwnHelp: boolean;
OwnStatus: boolean;
readonly Parent: any;
readonly Previous: FormField;
readonly Range: Range;
Result: string;
Select(): void;
StatusText: string;
readonly TextInput: TextInput;
readonly Type: WdFieldType;
}
class FormFields {
private 'Word.FormFields_typekey': FormFields;
private constructor();
Add(Range: Range, Type: WdFieldType): FormField;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): FormField;
readonly Parent: any;
Shaded: boolean;
}
class Frame {
private 'Word.Frame_typekey': Frame;
private constructor();
readonly Application: Application;
Borders: Borders;
Copy(): void;
readonly Creator: number;
Cut(): void;
Delete(): void;
Height: number;
HeightRule: WdFrameSizeRule;
HorizontalDistanceFromText: number;
HorizontalPosition: number;
LockAnchor: boolean;
readonly Parent: any;
readonly Range: Range;
RelativeHorizontalPosition: WdRelativeHorizontalPosition;
RelativeVerticalPosition: WdRelativeVerticalPosition;
Select(): void;
readonly Shading: Shading;
TextWrap: boolean;
VerticalDistanceFromText: number;
VerticalPosition: number;
Width: number;
WidthRule: WdFrameSizeRule;
}
class Frames {
private 'Word.Frames_typekey': Frames;
private constructor();
Add(Range: Range): Frame;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Delete(): void;
Item(Index: number): Frame;
readonly Parent: any;
}
class Frameset {
private 'Word.Frameset_typekey': Frameset;
private constructor();
AddNewFrame(Where: WdFramesetNewFrameLocation): Frameset;
readonly Application: Application;
readonly ChildFramesetCount: number;
ChildFramesetItem(Index: number): Frameset;
readonly Creator: number;
Delete(): void;
FrameDefaultURL: string;
FrameDisplayBorders: boolean;
FrameLinkToFile: boolean;
FrameName: string;
FrameResizable: boolean;
FrameScrollbarType: WdScrollbarType;
FramesetBorderColor: WdColor;
FramesetBorderWidth: number;
Height: number;
HeightType: WdFramesetSizeType;
readonly Parent: any;
readonly ParentFrameset: Frameset;
readonly Type: WdFramesetType;
Width: number;
WidthType: WdFramesetSizeType;
}
class FreeformBuilder {
private 'Word.FreeformBuilder_typekey': FreeformBuilder;
private constructor();
/**
* @param number [X2=0]
* @param number [Y2=0]
* @param number [X3=0]
* @param number [Y3=0]
*/
AddNodes(SegmentType: Office.MsoSegmentType, EditingType: Office.MsoEditingType, X1: number, Y1: number, X2?: number, Y2?: number, X3?: number, Y3?: number): void;
readonly Application: Application;
ConvertToShape(Anchor?: any): Shape;
readonly Creator: number;
readonly Parent: any;
}
class Global {
private 'Word.Global_typekey': Global;
private constructor();
readonly ActiveDocument: Document;
ActivePrinter: string;
readonly ActiveProtectedViewWindow: ProtectedViewWindow;
readonly ActiveWindow: Window;
readonly AddIns: AddIns;
readonly AnswerWizard: Office.AnswerWizard;
readonly Application: Application;
readonly Assistant: Office.Assistant;
readonly AutoCaptions: AutoCaptions;
readonly AutoCorrect: AutoCorrect;
readonly AutoCorrectEmail: AutoCorrect;
BuildKeyCode(Arg1: WdKey, Arg2?: any, Arg3?: any, Arg4?: any): number;
readonly CaptionLabels: CaptionLabels;
CentimetersToPoints(Centimeters: number): number;
ChangeFileOpenDirectory(Path: string): void;
CheckSpelling(
Word: string, CustomDictionary?: any, IgnoreUppercase?: any, MainDictionary?: any, CustomDictionary2?: any, CustomDictionary3?: any, CustomDictionary4?: any,
CustomDictionary5?: any, CustomDictionary6?: any, CustomDictionary7?: any, CustomDictionary8?: any, CustomDictionary9?: any, CustomDictionary10?: any): boolean;
CleanString(String: string): string;
readonly CommandBars: Office.CommandBars;
readonly Creator: number;
readonly CustomDictionaries: Dictionaries;
CustomizationContext: any;
DDEExecute(Channel: number, Command: string): void;
DDEInitiate(App: string, Topic: string): number;
DDEPoke(Channel: number, Item: string, Data: string): void;
DDERequest(Channel: number, Item: string): string;
DDETerminate(Channel: number): void;
DDETerminateAll(): void;
readonly Dialogs: Dialogs;
readonly Documents: Documents;
readonly FileConverters: FileConverters;
FindKey(KeyCode: number, KeyCode2?: any): KeyBinding;
readonly FontNames: FontNames;
GetSpellingSuggestions(
Word: string, CustomDictionary?: any, IgnoreUppercase?: any, MainDictionary?: any, SuggestionMode?: any, CustomDictionary2?: any, CustomDictionary3?: any,
CustomDictionary4?: any, CustomDictionary5?: any, CustomDictionary6?: any, CustomDictionary7?: any, CustomDictionary8?: any, CustomDictionary9?: any,
CustomDictionary10?: any): SpellingSuggestions;
readonly HangulHanjaDictionaries: HangulHanjaConversionDictionaries;
Help(HelpType: any): void;
InchesToPoints(Inches: number): number;
IsObjectValid(Object: any): boolean;
readonly IsSandboxed: boolean;
readonly KeyBindings: KeyBindings;
KeysBoundTo(KeyCategory: WdKeyCategory, Command: string, CommandParameter?: any): KeysBoundTo;
KeyString(KeyCode: number, KeyCode2?: any): string;
readonly LandscapeFontNames: FontNames;
readonly Languages: Languages;
readonly LanguageSettings: Office.LanguageSettings;
LinesToPoints(Lines: number): number;
readonly ListGalleries: ListGalleries;
readonly MacroContainer: any;
MillimetersToPoints(Millimeters: number): number;
readonly Name: string;
NewWindow(): Window;
readonly NormalTemplate: Template;
readonly Options: Options;
readonly Parent: any;
PicasToPoints(Picas: number): number;
PixelsToPoints(Pixels: number, fVertical?: any): number;
PointsToCentimeters(Points: number): number;
PointsToInches(Points: number): number;
PointsToLines(Points: number): number;
PointsToMillimeters(Points: number): number;
PointsToPicas(Points: number): number;
PointsToPixels(Points: number, fVertical?: any): number;
readonly PortraitFontNames: FontNames;
PrintPreview: boolean;
readonly ProtectedViewWindows: ProtectedViewWindows;
readonly RecentFiles: RecentFiles;
Repeat(Times?: any): boolean;
readonly Selection: Selection;
ShowVisualBasicEditor: boolean;
readonly StatusBar: string;
SynonymInfo(Word: string, LanguageID?: any): SynonymInfo;
readonly System: System;
readonly Tasks: Tasks;
readonly Templates: Templates;
readonly VBE: VBIDE.VBE;
readonly Windows: Windows;
readonly WordBasic: any;
}
class GlowFormat {
private 'Word.GlowFormat_typekey': GlowFormat;
private constructor();
readonly Application: Application;
readonly Color: ColorFormat;
readonly Creator: number;
readonly Parent: any;
Radius: number;
Transparency: number;
}
class GroupShapes {
private 'Word.GroupShapes_typekey': GroupShapes;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Shape;
readonly Parent: any;
Range(Index: any): ShapeRange;
}
class HangulAndAlphabetException {
private 'Word.HangulAndAlphabetException_typekey': HangulAndAlphabetException;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
}
class HangulAndAlphabetExceptions {
private 'Word.HangulAndAlphabetExceptions_typekey': HangulAndAlphabetExceptions;
private constructor();
Add(Name: string): HangulAndAlphabetException;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): HangulAndAlphabetException;
readonly Parent: any;
}
class HangulHanjaConversionDictionaries {
private 'Word.HangulHanjaConversionDictionaries_typekey': HangulHanjaConversionDictionaries;
private constructor();
ActiveCustomDictionary: Dictionary;
Add(FileName: string): Dictionary;
readonly Application: Application;
readonly BuiltinDictionary: Dictionary;
ClearAll(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Dictionary;
readonly Maximum: number;
readonly Parent: any;
}
class HeaderFooter {
private 'Word.HeaderFooter_typekey': HeaderFooter;
private constructor();
readonly Application: Application;
readonly Creator: number;
Exists: boolean;
readonly Index: WdHeaderFooterIndex;
readonly IsHeader: boolean;
LinkToPrevious: boolean;
readonly PageNumbers: PageNumbers;
readonly Parent: any;
readonly Range: Range;
readonly Shapes: Shapes;
}
class HeadersFooters {
private 'Word.HeadersFooters_typekey': HeadersFooters;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: WdHeaderFooterIndex): HeaderFooter;
readonly Parent: any;
}
class HeadingStyle {
private 'Word.HeadingStyle_typekey': HeadingStyle;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
Level: number;
readonly Parent: any;
Style: any;
}
class HeadingStyles {
private 'Word.HeadingStyles_typekey': HeadingStyles;
private constructor();
Add(Style: any, Level: number): HeadingStyle;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): HeadingStyle;
readonly Parent: any;
}
class HiLoLines {
private 'Word.HiLoLines_typekey': HiLoLines;
private constructor();
readonly Application: any;
readonly Border: ChartBorder;
readonly Creator: number;
Delete(): void;
readonly Format: ChartFormat;
readonly Name: string;
readonly Parent: any;
Select(): void;
}
class HorizontalLineFormat {
private 'Word.HorizontalLineFormat_typekey': HorizontalLineFormat;
private constructor();
Alignment: WdHorizontalLineAlignment;
readonly Application: Application;
readonly Creator: number;
NoShade: boolean;
readonly Parent: any;
PercentWidth: number;
WidthType: WdHorizontalLineWidthType;
}
class HTMLDivision {
private 'Word.HTMLDivision_typekey': HTMLDivision;
private constructor();
readonly Application: Application;
readonly Borders: Borders;
readonly Creator: number;
Delete(): void;
HTMLDivisionParent(LevelsUp?: any): HTMLDivision;
readonly HTMLDivisions: HTMLDivisions;
LeftIndent: number;
readonly Parent: any;
readonly Range: Range;
RightIndent: number;
SpaceAfter: number;
SpaceBefore: number;
}
class HTMLDivisions {
private 'Word.HTMLDivisions_typekey': HTMLDivisions;
private constructor();
Add(Range?: any): HTMLDivision;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): HTMLDivision;
readonly NestingLevel: number;
readonly Parent: any;
}
class Hyperlink {
private 'Word.Hyperlink_typekey': Hyperlink;
private constructor();
Address: string;
readonly AddressOld: string;
AddToFavorites(): void;
readonly Application: Application;
CreateNewDocument(FileName: string, EditNow: boolean, Overwrite: boolean): void;
readonly Creator: number;
Delete(): void;
EmailSubject: string;
readonly ExtraInfoRequired: boolean;
Follow(NewWindow?: any, AddHistory?: any, ExtraInfo?: any, Method?: any, HeaderInfo?: any): void;
readonly Name: string;
readonly Parent: any;
readonly Range: Range;
ScreenTip: string;
readonly Shape: Shape;
SubAddress: string;
readonly SubAddressOld: string;
Target: string;
TextToDisplay: string;
readonly Type: Office.MsoHyperlinkType;
}
class Hyperlinks {
private 'Word.Hyperlinks_typekey': Hyperlinks;
private constructor();
_Add(Anchor: any, Address?: any, SubAddress?: any): Hyperlink;
Add(Anchor: any, Address?: any, SubAddress?: any, ScreenTip?: any, TextToDisplay?: any, Target?: any): Hyperlink;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Hyperlink;
readonly Parent: any;
}
class Index {
private 'Word.Index_typekey': Index;
private constructor();
AccentedLetters: boolean;
readonly Application: Application;
readonly Creator: number;
Delete(): void;
Filter: WdIndexFilter;
HeadingSeparator: WdHeadingSeparator;
IndexLanguage: WdLanguageID;
NumberOfColumns: number;
readonly Parent: any;
readonly Range: Range;
RightAlignPageNumbers: boolean;
SortBy: WdIndexSortBy;
TabLeader: WdTabLeader;
Type: WdIndexType;
Update(): void;
}
class Indexes {
private 'Word.Indexes_typekey': Indexes;
private constructor();
Add(Range: Range, HeadingSeparator?: any, RightAlignPageNumbers?: any, Type?: any, NumberOfColumns?: any, AccentedLetters?: any, SortBy?: any, IndexLanguage?: any): Index;
AddOld(Range: Range, HeadingSeparator?: any, RightAlignPageNumbers?: any, Type?: any, NumberOfColumns?: any, AccentedLetters?: any): Index;
readonly Application: Application;
AutoMarkEntries(ConcordanceFileName: string): void;
readonly Count: number;
readonly Creator: number;
Format: WdIndexFormat;
Item(Index: number): Index;
MarkAllEntries(Range: Range, Entry?: any, EntryAutoText?: any, CrossReference?: any, CrossReferenceAutoText?: any, BookmarkName?: any, Bold?: any, Italic?: any): void;
MarkEntry(Range: Range, Entry?: any, EntryAutoText?: any, CrossReference?: any, CrossReferenceAutoText?: any, BookmarkName?: any, Bold?: any, Italic?: any, Reading?: any): Field;
readonly Parent: any;
}
class InlineShape {
private 'Word.InlineShape_typekey': InlineShape;
private constructor();
Activate(): void;
AlternativeText: string;
readonly AnchorID: number;
readonly Application: Application;
Borders: Borders;
readonly Chart: Chart;
ConvertToShape(): Shape;
readonly Creator: number;
Delete(): void;
readonly EditID: number;
readonly Field: Field;
readonly Fill: FillFormat;
readonly Glow: GlowFormat;
readonly GroupItems: GroupShapes;
readonly HasChart: Office.MsoTriState;
readonly HasSmartArt: Office.MsoTriState;
Height: number;
readonly HorizontalLineFormat: HorizontalLineFormat;
readonly Hyperlink: Hyperlink;
readonly IsPictureBullet: boolean;
readonly Line: LineFormat;
readonly LinkFormat: LinkFormat;
LockAspectRatio: Office.MsoTriState;
readonly OLEFormat: OLEFormat;
readonly OWSAnchor: number;
readonly Parent: any;
PictureFormat: PictureFormat;
readonly Range: Range;
readonly Reflection: ReflectionFormat;
Reset(): void;
ScaleHeight: number;
ScaleWidth: number;
readonly Script: Office.Script;
Select(): void;
readonly Shadow: ShadowFormat;
readonly SmartArt: Office.SmartArt;
readonly SoftEdge: SoftEdgeFormat;
TextEffect: TextEffectFormat;
Title: string;
readonly Type: WdInlineShapeType;
Width: number;
}
class InlineShapes {
private 'Word.InlineShapes_typekey': InlineShapes;
private constructor();
/** @param Office.XlChartType [Type=-1] */
AddChart(Type?: Office.XlChartType, Range?: any): InlineShape;
AddHorizontalLine(FileName: string, Range?: any): InlineShape;
AddHorizontalLineStandard(Range?: any): InlineShape;
AddOLEControl(ClassType?: any, Range?: any): InlineShape;
AddOLEObject(ClassType?: any, FileName?: any, LinkToFile?: any, DisplayAsIcon?: any, IconFileName?: any, IconIndex?: any, IconLabel?: any, Range?: any): InlineShape;
AddPicture(FileName: string, LinkToFile?: any, SaveWithDocument?: any, Range?: any): InlineShape;
AddPictureBullet(FileName: string, Range?: any): InlineShape;
AddSmartArt(Layout: Office.SmartArtLayout, Range?: any): InlineShape;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): InlineShape;
New(Range: Range): InlineShape;
readonly Parent: any;
}
class Interior {
private 'Word.Interior_typekey': Interior;
private constructor();
readonly Application: any;
Color: any;
ColorIndex: any;
readonly Creator: number;
InvertIfNegative: any;
readonly Parent: any;
Pattern: any;
PatternColor: any;
PatternColorIndex: any;
}
class KeyBinding {
private 'Word.KeyBinding_typekey': KeyBinding;
private constructor();
readonly Application: Application;
Clear(): void;
readonly Command: string;
readonly CommandParameter: string;
readonly Context: any;
readonly Creator: number;
Disable(): void;
Execute(): void;
readonly KeyCategory: WdKeyCategory;
readonly KeyCode: number;
readonly KeyCode2: number;
readonly KeyString: string;
readonly Parent: any;
readonly Protected: boolean;
Rebind(KeyCategory: WdKeyCategory, Command: string, CommandParameter?: any): void;
}
class KeyBindings {
private 'Word.KeyBindings_typekey': KeyBindings;
private constructor();
Add(KeyCategory: WdKeyCategory, Command: string, KeyCode: number, KeyCode2?: any, CommandParameter?: any): KeyBinding;
readonly Application: Application;
ClearAll(): void;
readonly Context: any;
readonly Count: number;
readonly Creator: number;
Item(Index: number): KeyBinding;
Key(KeyCode: number, KeyCode2?: any): KeyBinding;
readonly Parent: any;
}
class KeysBoundTo {
private 'Word.KeysBoundTo_typekey': KeysBoundTo;
private constructor();
readonly Application: Application;
readonly Command: string;
readonly CommandParameter: string;
readonly Context: any;
readonly Count: number;
readonly Creator: number;
Item(Index: number): KeyBinding;
Key(KeyCode: number, KeyCode2?: any): KeyBinding;
readonly KeyCategory: WdKeyCategory;
readonly Parent: any;
}
class Language {
private 'Word.Language_typekey': Language;
private constructor();
readonly ActiveGrammarDictionary: Dictionary;
readonly ActiveHyphenationDictionary: Dictionary;
readonly ActiveSpellingDictionary: Dictionary;
readonly ActiveThesaurusDictionary: Dictionary;
readonly Application: Application;
readonly Creator: number;
DefaultWritingStyle: string;
readonly ID: WdLanguageID;
readonly Name: string;
readonly NameLocal: string;
readonly Parent: any;
SpellingDictionaryType: WdDictionaryType;
readonly WritingStyleList: any;
}
class Languages {
private 'Word.Languages_typekey': Languages;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Language;
readonly Parent: any;
}
class Legend {
private 'Word.Legend_typekey': Legend;
private constructor();
readonly Application: any;
AutoScaleFont: any;
readonly Border: ChartBorder;
Clear(): any;
readonly Creator: number;
Delete(): any;
readonly Fill: ChartFillFormat;
readonly Font: ChartFont;
readonly Format: ChartFormat;
Height: number;
IncludeInLayout: boolean;
readonly Interior: Interior;
Left: number;
LegendEntries(Index?: any): any;
readonly Name: string;
readonly Parent: any;
Position: XlLegendPosition;
Select(): any;
Shadow: boolean;
Top: number;
Width: number;
}
class LetterContent {
private 'Word.LetterContent_typekey': LetterContent;
private constructor();
readonly Application: Application;
AttentionLine: string;
CCList: string;
Closing: string;
readonly Creator: number;
DateFormat: string;
readonly Duplicate: LetterContent;
EnclosureNumber: number;
IncludeHeaderFooter: boolean;
InfoBlock: boolean;
Letterhead: boolean;
LetterheadLocation: WdLetterheadLocation;
LetterheadSize: number;
LetterStyle: WdLetterStyle;
MailingInstructions: string;
PageDesign: string;
readonly Parent: any;
RecipientAddress: string;
RecipientCode: string;
RecipientGender: WdSalutationGender;
RecipientName: string;
RecipientReference: string;
ReturnAddress: string;
ReturnAddressShortForm: string;
Salutation: string;
SalutationType: WdSalutationType;
SenderCity: string;
SenderCode: string;
SenderCompany: string;
SenderGender: WdSalutationGender;
SenderInitials: string;
SenderJobTitle: string;
SenderName: string;
SenderReference: string;
Subject: string;
}
class Line {
private 'Word.Line_typekey': Line;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Height: number;
readonly Left: number;
readonly LineType: WdLineType;
readonly Parent: any;
readonly Range: Range;
readonly Rectangles: Rectangles;
readonly Top: number;
readonly Width: number;
}
class LineFormat {
private 'Word.LineFormat_typekey': LineFormat;
private constructor();
readonly Application: Application;
readonly BackColor: ColorFormat;
BeginArrowheadLength: Office.MsoArrowheadLength;
BeginArrowheadStyle: Office.MsoArrowheadStyle;
BeginArrowheadWidth: Office.MsoArrowheadWidth;
readonly Creator: number;
DashStyle: Office.MsoLineDashStyle;
EndArrowheadLength: Office.MsoArrowheadLength;
EndArrowheadStyle: Office.MsoArrowheadStyle;
EndArrowheadWidth: Office.MsoArrowheadWidth;
readonly ForeColor: ColorFormat;
InsetPen: Office.MsoTriState;
readonly Parent: any;
Pattern: Office.MsoPatternType;
Style: Office.MsoLineStyle;
Transparency: number;
Visible: Office.MsoTriState;
Weight: number;
}
class LineNumbering {
private 'Word.LineNumbering_typekey': LineNumbering;
private constructor();
Active: number;
readonly Application: Application;
CountBy: number;
readonly Creator: number;
DistanceFromText: number;
readonly Parent: any;
RestartMode: WdNumberingRule;
StartingNumber: number;
}
class Lines {
private 'Word.Lines_typekey': Lines;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Line;
readonly Parent: any;
}
class LinkFormat {
private 'Word.LinkFormat_typekey': LinkFormat;
private constructor();
readonly Application: Application;
AutoUpdate: boolean;
BreakLink(): void;
readonly Creator: number;
Locked: boolean;
readonly Parent: any;
SavePictureWithDocument: boolean;
SourceFullName: string;
readonly SourceName: string;
readonly SourcePath: string;
readonly Type: WdLinkType;
Update(): void;
}
class List {
private 'Word.List_typekey': List;
private constructor();
readonly Application: Application;
ApplyListTemplate(ListTemplate: ListTemplate, ContinuePreviousList?: any, DefaultListBehavior?: any): void;
ApplyListTemplateOld(ListTemplate: ListTemplate, ContinuePreviousList?: any): void;
ApplyListTemplateWithLevel(ListTemplate: ListTemplate, ContinuePreviousList?: any, DefaultListBehavior?: any, ApplyLevel?: any): void;
CanContinuePreviousList(ListTemplate: ListTemplate): WdContinue;
ConvertNumbersToText(NumberType?: any): void;
CountNumberedItems(NumberType?: any, Level?: any): number;
readonly Creator: number;
readonly ListParagraphs: ListParagraphs;
readonly Parent: any;
readonly Range: Range;
RemoveNumbers(NumberType?: any): void;
readonly SingleListTemplate: boolean;
readonly StyleName: string;
}
class ListEntries {
private 'Word.ListEntries_typekey': ListEntries;
private constructor();
Add(Name: string, Index?: any): ListEntry;
readonly Application: Application;
Clear(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: any): ListEntry;
readonly Parent: any;
}
class ListEntry {
private 'Word.ListEntry_typekey': ListEntry;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
Name: string;
readonly Parent: any;
}
class ListFormat {
private 'Word.ListFormat_typekey': ListFormat;
private constructor();
readonly Application: Application;
ApplyBulletDefault(DefaultListBehavior?: any): void;
ApplyBulletDefaultOld(): void;
ApplyListTemplate(ListTemplate: ListTemplate, ContinuePreviousList?: any, ApplyTo?: any, DefaultListBehavior?: any): void;
ApplyListTemplateOld(ListTemplate: ListTemplate, ContinuePreviousList?: any, ApplyTo?: any): void;
ApplyListTemplateWithLevel(ListTemplate: ListTemplate, ContinuePreviousList?: any, ApplyTo?: any, DefaultListBehavior?: any, ApplyLevel?: any): void;
ApplyNumberDefault(DefaultListBehavior?: any): void;
ApplyNumberDefaultOld(): void;
ApplyOutlineNumberDefault(DefaultListBehavior?: any): void;
ApplyOutlineNumberDefaultOld(): void;
CanContinuePreviousList(ListTemplate: ListTemplate): WdContinue;
ConvertNumbersToText(NumberType?: any): void;
CountNumberedItems(NumberType?: any, Level?: any): number;
readonly Creator: number;
readonly List: List;
ListIndent(): void;
ListLevelNumber: number;
ListOutdent(): void;
readonly ListPictureBullet: InlineShape;
readonly ListString: string;
readonly ListTemplate: ListTemplate;
readonly ListType: WdListType;
readonly ListValue: number;
readonly Parent: any;
RemoveNumbers(NumberType?: any): void;
readonly SingleList: boolean;
readonly SingleListTemplate: boolean;
}
class ListGalleries {
private 'Word.ListGalleries_typekey': ListGalleries;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: WdListGalleryType): ListGallery;
readonly Parent: any;
}
class ListGallery {
private 'Word.ListGallery_typekey': ListGallery;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly ListTemplates: ListTemplates;
Modified(Index: number): boolean;
readonly Parent: any;
Reset(Index: number): void;
}
class ListLevel {
private 'Word.ListLevel_typekey': ListLevel;
private constructor();
Alignment: WdListLevelAlignment;
readonly Application: Application;
ApplyPictureBullet(FileName: string): InlineShape;
readonly Creator: number;
Font: Font;
readonly Index: number;
LinkedStyle: string;
NumberFormat: string;
NumberPosition: number;
NumberStyle: WdListNumberStyle;
readonly Parent: any;
readonly PictureBullet: InlineShape;
ResetOnHigher: number;
ResetOnHigherOld: boolean;
StartAt: number;
TabPosition: number;
TextPosition: number;
TrailingCharacter: WdTrailingCharacter;
}
class ListLevels {
private 'Word.ListLevels_typekey': ListLevels;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): ListLevel;
readonly Parent: any;
}
class ListParagraphs {
private 'Word.ListParagraphs_typekey': ListParagraphs;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Paragraph;
readonly Parent: any;
}
class Lists {
private 'Word.Lists_typekey': Lists;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): List;
readonly Parent: any;
}
class ListTemplate {
private 'Word.ListTemplate_typekey': ListTemplate;
private constructor();
readonly Application: Application;
Convert(Level?: any): ListTemplate;
readonly Creator: number;
readonly ListLevels: ListLevels;
Name: string;
OutlineNumbered: boolean;
readonly Parent: any;
}
class ListTemplates {
private 'Word.ListTemplates_typekey': ListTemplates;
private constructor();
Add(OutlineNumbered?: any, Name?: any): ListTemplate;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): ListTemplate;
readonly Parent: any;
}
class Mailer {
private 'Word.Mailer_typekey': Mailer;
private constructor();
readonly Application: Application;
BCCRecipients: any;
CCRecipients: any;
readonly Creator: number;
Enclosures: any;
readonly Parent: any;
readonly Received: boolean;
Recipients: any;
readonly SendDateTime: VarDate;
readonly Sender: string;
Subject: string;
}
class MailingLabel {
private 'Word.MailingLabel_typekey': MailingLabel;
private constructor();
readonly Application: Application;
CreateNewDocument(Name?: any, Address?: any, AutoText?: any, ExtractAddress?: any, LaserTray?: any, PrintEPostageLabel?: any, Vertical?: any): Document;
CreateNewDocument2000(Name?: any, Address?: any, AutoText?: any, ExtractAddress?: any, LaserTray?: any): Document;
CreateNewDocumentByID(LabelID?: any, Address?: any, AutoText?: any, ExtractAddress?: any, LaserTray?: any, PrintEPostageLabel?: any, Vertical?: any): Document;
readonly Creator: number;
readonly CustomLabels: CustomLabels;
DefaultLabelName: string;
DefaultLaserTray: WdPaperTray;
DefaultPrintBarCode: boolean;
LabelOptions(): void;
readonly Parent: any;
PrintOut(Name?: any, Address?: any, ExtractAddress?: any, LaserTray?: any, SingleLabel?: any, Row?: any, Column?: any, PrintEPostageLabel?: any, Vertical?: any): void;
PrintOut2000(Name?: any, Address?: any, ExtractAddress?: any, LaserTray?: any, SingleLabel?: any, Row?: any, Column?: any): void;
PrintOutByID(LabelID?: any, Address?: any, ExtractAddress?: any, LaserTray?: any, SingleLabel?: any, Row?: any, Column?: any, PrintEPostageLabel?: any, Vertical?: any): void;
Vertical: boolean;
}
class MailMerge {
private 'Word.MailMerge_typekey': MailMerge;
private constructor();
readonly Application: Application;
Check(): void;
CreateDataSource(
Name?: any, PasswordDocument?: any, WritePasswordDocument?: any, HeaderRecord?: any, MSQuery?: any, SQLStatement?: any, SQLStatement1?: any, Connection?: any, LinkToSource?: any): void;
CreateHeaderSource(Name: string, PasswordDocument?: any, WritePasswordDocument?: any, HeaderRecord?: any): void;
readonly Creator: number;
readonly DataSource: MailMergeDataSource;
Destination: WdMailMergeDestination;
EditDataSource(): void;
EditHeaderSource(): void;
EditMainDocument(): void;
Execute(Pause?: any): void;
readonly Fields: MailMergeFields;
HighlightMergeFields: boolean;
MailAddressFieldName: string;
MailAsAttachment: boolean;
MailFormat: WdMailMergeMailFormat;
MailSubject: string;
MainDocumentType: WdMailMergeMainDocType;
OpenDataSource(
Name: string, Format?: any, ConfirmConversions?: any, ReadOnly?: any, LinkToSource?: any, AddToRecentFiles?: any, PasswordDocument?: any,
PasswordTemplate?: any, Revert?: any, WritePasswordDocument?: any, WritePasswordTemplate?: any, Connection?: any, SQLStatement?: any, SQLStatement1?: any,
OpenExclusive?: any, SubType?: any): void;
OpenDataSource2000(
Name: string, Format?: any, ConfirmConversions?: any, ReadOnly?: any, LinkToSource?: any, AddToRecentFiles?: any, PasswordDocument?: any,
PasswordTemplate?: any, Revert?: any, WritePasswordDocument?: any, WritePasswordTemplate?: any, Connection?: any, SQLStatement?: any, SQLStatement1?: any): void;
OpenHeaderSource(
Name: string, Format?: any, ConfirmConversions?: any, ReadOnly?: any, AddToRecentFiles?: any, PasswordDocument?: any, PasswordTemplate?: any, Revert?: any,
WritePasswordDocument?: any, WritePasswordTemplate?: any, OpenExclusive?: any): void;
OpenHeaderSource2000(
Name: string, Format?: any, ConfirmConversions?: any, ReadOnly?: any, AddToRecentFiles?: any, PasswordDocument?: any, PasswordTemplate?: any, Revert?: any,
WritePasswordDocument?: any, WritePasswordTemplate?: any): void;
readonly Parent: any;
ShowSendToCustom: string;
ShowWizard(InitialState: any, ShowDocumentStep?: any, ShowTemplateStep?: any, ShowDataStep?: any, ShowWriteStep?: any, ShowPreviewStep?: any, ShowMergeStep?: any): void;
readonly State: WdMailMergeState;
SuppressBlankLines: boolean;
UseAddressBook(Type: string): void;
ViewMailMergeFieldCodes: number;
WizardState: number;
}
class MailMergeDataField {
private 'Word.MailMergeDataField_typekey': MailMergeDataField;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
readonly Value: string;
}
class MailMergeDataFields {
private 'Word.MailMergeDataFields_typekey': MailMergeDataFields;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): MailMergeDataField;
readonly Parent: any;
}
class MailMergeDataSource {
private 'Word.MailMergeDataSource_typekey': MailMergeDataSource;
private constructor();
ActiveRecord: WdMailMergeActiveRecord;
readonly Application: Application;
Close(): void;
readonly ConnectString: string;
readonly Creator: number;
readonly DataFields: MailMergeDataFields;
readonly FieldNames: MailMergeFieldNames;
FindRecord(FindText: string, Field?: any): boolean;
FindRecord2000(FindText: string, Field: string): boolean;
FirstRecord: number;
readonly HeaderSourceName: string;
readonly HeaderSourceType: WdMailMergeDataSource;
Included: boolean;
InvalidAddress: boolean;
InvalidComments: string;
LastRecord: number;
readonly MappedDataFields: MappedDataFields;
readonly Name: string;
readonly Parent: any;
QueryString: string;
readonly RecordCount: number;
SetAllErrorFlags(Invalid: boolean, InvalidComment: string): void;
SetAllIncludedFlags(Included: boolean): void;
readonly TableName: string;
readonly Type: WdMailMergeDataSource;
}
class MailMergeField {
private 'Word.MailMergeField_typekey': MailMergeField;
private constructor();
readonly Application: Application;
Code: Range;
Copy(): void;
readonly Creator: number;
Cut(): void;
Delete(): void;
Locked: boolean;
readonly Next: MailMergeField;
readonly Parent: any;
readonly Previous: MailMergeField;
Select(): void;
readonly Type: WdFieldType;
}
class MailMergeFieldName {
private 'Word.MailMergeFieldName_typekey': MailMergeFieldName;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
}
class MailMergeFieldNames {
private 'Word.MailMergeFieldNames_typekey': MailMergeFieldNames;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): MailMergeFieldName;
readonly Parent: any;
}
class MailMergeFields {
private 'Word.MailMergeFields_typekey': MailMergeFields;
private constructor();
Add(Range: Range, Name: string): MailMergeField;
AddAsk(Range: Range, Name: string, Prompt?: any, DefaultAskText?: any, AskOnce?: any): MailMergeField;
AddFillIn(Range: Range, Prompt?: any, DefaultFillInText?: any, AskOnce?: any): MailMergeField;
AddIf(Range: Range, MergeField: string, Comparison: WdMailMergeComparison, CompareTo?: any, TrueAutoText?: any, TrueText?: any, FalseAutoText?: any, FalseText?: any): MailMergeField;
AddMergeRec(Range: Range): MailMergeField;
AddMergeSeq(Range: Range): MailMergeField;
AddNext(Range: Range): MailMergeField;
AddNextIf(Range: Range, MergeField: string, Comparison: WdMailMergeComparison, CompareTo?: any): MailMergeField;
AddSet(Range: Range, Name: string, ValueText?: any, ValueAutoText?: any): MailMergeField;
AddSkipIf(Range: Range, MergeField: string, Comparison: WdMailMergeComparison, CompareTo?: any): MailMergeField;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): MailMergeField;
readonly Parent: any;
}
class MailMessage {
private 'Word.MailMessage_typekey': MailMessage;
private constructor();
readonly Application: Application;
CheckName(): void;
readonly Creator: number;
Delete(): void;
DisplayMoveDialog(): void;
DisplayProperties(): void;
DisplaySelectNamesDialog(): void;
Forward(): void;
GoToNext(): void;
GoToPrevious(): void;
readonly Parent: any;
Reply(): void;
ReplyAll(): void;
ToggleHeader(): void;
}
class MappedDataField {
private 'Word.MappedDataField_typekey': MappedDataField;
private constructor();
readonly Application: Application;
readonly Creator: number;
DataFieldIndex: number;
readonly DataFieldName: string;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
readonly Value: string;
}
class MappedDataFields {
private 'Word.MappedDataFields_typekey': MappedDataFields;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: WdMappedDataFields): MappedDataField;
readonly Parent: any;
}
class OLEControl {
private 'Word.OLEControl_typekey': OLEControl;
private constructor();
Activate(): void;
AltHTML: string;
readonly Automation: any;
Copy(): void;
Cut(): void;
Delete(): void;
Height: number;
Left: number;
Name: string;
Select(): void;
Top: number;
Width: number;
}
class OLEFormat {
private 'Word.OLEFormat_typekey': OLEFormat;
private constructor();
Activate(): void;
ActivateAs(ClassType: string): void;
readonly Application: Application;
ClassType: string;
ConvertTo(ClassType?: any, DisplayAsIcon?: any, IconFileName?: any, IconIndex?: any, IconLabel?: any): void;
readonly Creator: number;
DisplayAsIcon: boolean;
DoVerb(VerbIndex?: any): void;
Edit(): void;
IconIndex: number;
IconLabel: string;
IconName: string;
readonly IconPath: string;
readonly Label: string;
readonly Object: any;
Open(): void;
readonly Parent: any;
PreserveFormattingOnUpdate: boolean;
readonly ProgID: string;
}
class OMath {
private 'Word.OMath_typekey': OMath;
private constructor();
AlignPoint: number;
readonly Application: Application;
readonly ArgIndex: number;
ArgSize: number;
readonly Breaks: OMathBreaks;
BuildUp(): void;
ConvertToLiteralText(): void;
ConvertToMathText(): void;
ConvertToNormalText(): void;
readonly Creator: number;
readonly Functions: OMathFunctions;
Justification: WdOMathJc;
Linearize(): void;
readonly NestingLevel: number;
readonly Parent: any;
readonly ParentArg: OMath;
readonly ParentCol: OMathMatCol;
readonly ParentFunction: OMathFunction;
readonly ParentOMath: OMath;
readonly ParentRow: OMathMatRow;
readonly Range: Range;
Remove(): void;
Type: WdOMathType;
}
class OMathAcc {
private 'Word.OMathAcc_typekey': OMathAcc;
private constructor();
readonly Application: Application;
Char: number;
readonly Creator: number;
readonly E: OMath;
readonly Parent: any;
}
class OMathArgs {
private 'Word.OMathArgs_typekey': OMathArgs;
private constructor();
Add(BeforeArg?: any): OMath;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): OMath;
readonly Parent: any;
}
class OMathAutoCorrect {
private 'Word.OMathAutoCorrect_typekey': OMathAutoCorrect;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Entries: OMathAutoCorrectEntries;
readonly Functions: OMathRecognizedFunctions;
readonly Parent: any;
ReplaceText: boolean;
UseOutsideOMath: boolean;
}
class OMathAutoCorrectEntries {
private 'Word.OMathAutoCorrectEntries_typekey': OMathAutoCorrectEntries;
private constructor();
Add(Name: string, Value: string): OMathAutoCorrectEntry;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): OMathAutoCorrectEntry;
readonly Parent: any;
}
class OMathAutoCorrectEntry {
private 'Word.OMathAutoCorrectEntry_typekey': OMathAutoCorrectEntry;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
Name: string;
readonly Parent: any;
Value: string;
}
class OMathBar {
private 'Word.OMathBar_typekey': OMathBar;
private constructor();
readonly Application: Application;
BarTop: boolean;
readonly Creator: number;
readonly E: OMath;
readonly Parent: any;
}
class OMathBorderBox {
private 'Word.OMathBorderBox_typekey': OMathBorderBox;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
HideBot: boolean;
HideLeft: boolean;
HideRight: boolean;
HideTop: boolean;
readonly Parent: any;
StrikeBLTR: boolean;
StrikeH: boolean;
StrikeTLBR: boolean;
StrikeV: boolean;
}
class OMathBox {
private 'Word.OMathBox_typekey': OMathBox;
private constructor();
readonly Application: Application;
readonly Creator: number;
Diff: boolean;
readonly E: OMath;
NoBreak: boolean;
OpEmu: boolean;
readonly Parent: any;
}
class OMathBreak {
private 'Word.OMathBreak_typekey': OMathBreak;
private constructor();
AlignAt: number;
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Parent: any;
readonly Range: Range;
}
class OMathBreaks {
private 'Word.OMathBreaks_typekey': OMathBreaks;
private constructor();
Add(Range: Range): OMathBreak;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): OMathBreak;
readonly Parent: any;
}
class OMathDelim {
private 'Word.OMathDelim_typekey': OMathDelim;
private constructor();
readonly Application: Application;
BegChar: number;
readonly Creator: number;
readonly E: OMathArgs;
EndChar: number;
Grow: boolean;
NoLeftChar: boolean;
NoRightChar: boolean;
readonly Parent: any;
SepChar: number;
Shape: WdOMathShapeType;
}
class OMathEqArray {
private 'Word.OMathEqArray_typekey': OMathEqArray;
private constructor();
Align: WdOMathVertAlignType;
readonly Application: Application;
readonly Creator: number;
readonly E: OMathArgs;
MaxDist: boolean;
ObjDist: boolean;
readonly Parent: any;
RowSpacing: number;
RowSpacingRule: WdOMathSpacingRule;
}
class OMathFrac {
private 'Word.OMathFrac_typekey': OMathFrac;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Den: OMath;
readonly Num: OMath;
readonly Parent: any;
Type: WdOMathFracType;
}
class OMathFunc {
private 'Word.OMathFunc_typekey': OMathFunc;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
readonly FName: OMath;
readonly Parent: any;
}
class OMathFunction {
private 'Word.OMathFunction_typekey': OMathFunction;
private constructor();
readonly Acc: OMathAcc;
readonly Application: Application;
readonly Args: OMathArgs;
readonly Bar: OMathBar;
readonly BorderBox: OMathBorderBox;
readonly Box: OMathBox;
readonly Creator: number;
readonly Delim: OMathDelim;
readonly EqArray: OMathEqArray;
readonly Frac: OMathFrac;
readonly Func: OMathFunc;
readonly GroupChar: OMathGroupChar;
readonly LimLow: OMathLimLow;
readonly LimUpp: OMathLimUpp;
readonly Mat: OMathMat;
readonly Nary: OMathNary;
readonly OMath: OMath;
readonly Parent: any;
readonly Phantom: OMathPhantom;
readonly Rad: OMathRad;
readonly Range: Range;
Remove(): OMathFunction;
readonly ScrPre: OMathScrPre;
readonly ScrSub: OMathScrSub;
readonly ScrSubSup: OMathScrSubSup;
readonly ScrSup: OMathScrSup;
readonly Type: WdOMathFunctionType;
}
class OMathFunctions {
private 'Word.OMathFunctions_typekey': OMathFunctions;
private constructor();
Add(Range: Range, Type: WdOMathFunctionType, NumArgs?: any, NumCols?: any): OMathFunction;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): OMathFunction;
readonly Parent: any;
}
class OMathGroupChar {
private 'Word.OMathGroupChar_typekey': OMathGroupChar;
private constructor();
AlignTop: boolean;
readonly Application: Application;
Char: number;
CharTop: boolean;
readonly Creator: number;
readonly E: OMath;
readonly Parent: any;
}
class OMathLimLow {
private 'Word.OMathLimLow_typekey': OMathLimLow;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
readonly Lim: OMath;
readonly Parent: any;
ToLimUpp(): OMathFunction;
}
class OMathLimUpp {
private 'Word.OMathLimUpp_typekey': OMathLimUpp;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
readonly Lim: OMath;
readonly Parent: any;
ToLimLow(): OMathFunction;
}
class OMathMat {
private 'Word.OMathMat_typekey': OMathMat;
private constructor();
Align: WdOMathVertAlignType;
readonly Application: Application;
Cell(Row: number, Col: number): OMath;
ColGap: number;
ColGapRule: WdOMathSpacingRule;
readonly Cols: OMathMatCols;
ColSpacing: number;
readonly Creator: number;
readonly Parent: any;
PlcHoldHidden: boolean;
readonly Rows: OMathMatRows;
RowSpacing: number;
RowSpacingRule: WdOMathSpacingRule;
}
class OMathMatCol {
private 'Word.OMathMatCol_typekey': OMathMatCol;
private constructor();
Align: WdOMathHorizAlignType;
readonly Application: Application;
readonly Args: OMathArgs;
readonly ColIndex: number;
readonly Creator: number;
Delete(): void;
readonly Parent: any;
}
class OMathMatCols {
private 'Word.OMathMatCols_typekey': OMathMatCols;
private constructor();
Add(BeforeCol?: any): OMathMatCol;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): OMathMatCol;
readonly Parent: any;
}
class OMathMatRow {
private 'Word.OMathMatRow_typekey': OMathMatRow;
private constructor();
readonly Application: Application;
readonly Args: OMathArgs;
readonly Creator: number;
Delete(): void;
readonly Parent: any;
readonly RowIndex: number;
}
class OMathMatRows {
private 'Word.OMathMatRows_typekey': OMathMatRows;
private constructor();
Add(BeforeRow?: any): OMathMatRow;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): OMathMatRow;
readonly Parent: any;
}
class OMathNary {
private 'Word.OMathNary_typekey': OMathNary;
private constructor();
readonly Application: Application;
Char: number;
readonly Creator: number;
readonly E: OMath;
Grow: boolean;
HideSub: boolean;
HideSup: boolean;
readonly Parent: any;
readonly Sub: OMath;
SubSupLim: boolean;
readonly Sup: OMath;
}
class OMathPhantom {
private 'Word.OMathPhantom_typekey': OMathPhantom;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
readonly Parent: any;
Show: boolean;
Smash: boolean;
Transp: boolean;
ZeroAsc: boolean;
ZeroDesc: boolean;
ZeroWid: boolean;
}
class OMathRad {
private 'Word.OMathRad_typekey': OMathRad;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Deg: OMath;
readonly E: OMath;
HideDeg: boolean;
readonly Parent: any;
}
class OMathRecognizedFunction {
private 'Word.OMathRecognizedFunction_typekey': OMathRecognizedFunction;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
}
class OMathRecognizedFunctions {
private 'Word.OMathRecognizedFunctions_typekey': OMathRecognizedFunctions;
private constructor();
Add(Name: string): OMathRecognizedFunction;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): OMathRecognizedFunction;
readonly Parent: any;
}
class OMaths {
private 'Word.OMaths_typekey': OMaths;
private constructor();
Add(Range: Range): Range;
readonly Application: Application;
BuildUp(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: number): OMath;
Linearize(): void;
readonly Parent: any;
}
class OMathScrPre {
private 'Word.OMathScrPre_typekey': OMathScrPre;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
readonly Parent: any;
readonly Sub: OMath;
readonly Sup: OMath;
ToScrSubSup(): OMathFunction;
}
class OMathScrSub {
private 'Word.OMathScrSub_typekey': OMathScrSub;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
readonly Parent: any;
readonly Sub: OMath;
}
class OMathScrSubSup {
private 'Word.OMathScrSubSup_typekey': OMathScrSubSup;
private constructor();
AlignScripts: boolean;
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
readonly Parent: any;
RemoveSub(): OMathFunction;
RemoveSup(): OMathFunction;
readonly Sub: OMath;
readonly Sup: OMath;
ToScrPre(): OMathFunction;
}
class OMathScrSup {
private 'Word.OMathScrSup_typekey': OMathScrSup;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly E: OMath;
readonly Parent: any;
readonly Sup: OMath;
}
class Options {
private 'Word.Options_typekey': Options;
private constructor();
AddBiDirectionalMarksWhenSavingTextFile: boolean;
AddControlCharacters: boolean;
AddHebDoubleQuote: boolean;
AllowAccentedUppercase: boolean;
AllowClickAndTypeMouse: boolean;
AllowCombinedAuxiliaryForms: boolean;
AllowCompoundNounProcessing: boolean;
AllowDragAndDrop: boolean;
AllowFastSave: boolean;
AllowOpenInDraftView: boolean;
AllowPixelUnits: boolean;
AllowReadingMode: boolean;
AlwaysUseClearType: boolean;
AnimateScreenMovements: boolean;
readonly Application: Application;
ApplyFarEastFontsToAscii: boolean;
ArabicMode: WdAraSpeller;
ArabicNumeral: WdArabicNumeral;
AutoCreateNewDrawings: boolean;
AutoFormatApplyBulletedLists: boolean;
AutoFormatApplyFirstIndents: boolean;
AutoFormatApplyHeadings: boolean;
AutoFormatApplyLists: boolean;
AutoFormatApplyOtherParas: boolean;
AutoFormatAsYouTypeApplyBorders: boolean;
AutoFormatAsYouTypeApplyBulletedLists: boolean;
AutoFormatAsYouTypeApplyClosings: boolean;
AutoFormatAsYouTypeApplyDates: boolean;
AutoFormatAsYouTypeApplyFirstIndents: boolean;
AutoFormatAsYouTypeApplyHeadings: boolean;
AutoFormatAsYouTypeApplyNumberedLists: boolean;
AutoFormatAsYouTypeApplyTables: boolean;
AutoFormatAsYouTypeAutoLetterWizard: boolean;
AutoFormatAsYouTypeDefineStyles: boolean;
AutoFormatAsYouTypeDeleteAutoSpaces: boolean;
AutoFormatAsYouTypeFormatListItemBeginning: boolean;
AutoFormatAsYouTypeInsertClosings: boolean;
AutoFormatAsYouTypeInsertOvers: boolean;
AutoFormatAsYouTypeMatchParentheses: boolean;
AutoFormatAsYouTypeReplaceFarEastDashes: boolean;
AutoFormatAsYouTypeReplaceFractions: boolean;
AutoFormatAsYouTypeReplaceHyperlinks: boolean;
AutoFormatAsYouTypeReplaceOrdinals: boolean;
AutoFormatAsYouTypeReplacePlainTextEmphasis: boolean;
AutoFormatAsYouTypeReplaceQuotes: boolean;
AutoFormatAsYouTypeReplaceSymbols: boolean;
AutoFormatDeleteAutoSpaces: boolean;
AutoFormatMatchParentheses: boolean;
AutoFormatPlainTextWordMail: boolean;
AutoFormatPreserveStyles: boolean;
AutoFormatReplaceFarEastDashes: boolean;
AutoFormatReplaceFractions: boolean;
AutoFormatReplaceHyperlinks: boolean;
AutoFormatReplaceOrdinals: boolean;
AutoFormatReplacePlainTextEmphasis: boolean;
AutoFormatReplaceQuotes: boolean;
AutoFormatReplaceSymbols: boolean;
AutoKeyboardSwitching: boolean;
AutoWordSelection: boolean;
BackgroundOpen: boolean;
BackgroundSave: boolean;
BibliographySort: string;
BibliographyStyle: string;
BlueScreen: boolean;
BrazilReform: WdPortugueseReform;
ButtonFieldClicks: number;
CheckGrammarAsYouType: boolean;
CheckGrammarWithSpelling: boolean;
CheckHangulEndings: boolean;
CheckSpellingAsYouType: boolean;
CommentsColor: WdColorIndex;
ConfirmConversions: boolean;
ContextualSpeller: boolean;
ConvertHighAnsiToFarEast: boolean;
CreateBackup: boolean;
readonly Creator: number;
CtrlClickHyperlinkToOpen: boolean;
CursorMovement: WdCursorMovement;
DefaultBorderColor: WdColor;
DefaultBorderColorIndex: WdColorIndex;
DefaultBorderLineStyle: WdLineStyle;
DefaultBorderLineWidth: WdLineWidth;
DefaultEPostageApp: string;
DefaultFilePath(Path: WdDefaultFilePath): string;
DefaultHighlightColorIndex: WdColorIndex;
DefaultOpenFormat: WdOpenFormat;
DefaultTextEncoding: Office.MsoEncoding;
DefaultTray: string;
DefaultTrayID: number;
DeletedCellColor: WdCellColor;
DeletedTextColor: WdColorIndex;
DeletedTextMark: WdDeletedTextMark;
DiacriticColorVal: WdColor;
DisableFeaturesbyDefault: boolean;
DisableFeaturesIntroducedAfterbyDefault: WdDisableFeaturesIntroducedAfter;
DisplayGridLines: boolean;
DisplayPasteOptions: boolean;
DisplaySmartTagButtons: boolean;
DocumentViewDirection: WdDocumentViewDirection;
DoNotPromptForConvert: boolean;
EnableHangulHanjaRecentOrdering: boolean;
EnableLegacyIMEMode: boolean;
EnableLivePreview: boolean;
EnableMisusedWordsDictionary: boolean;
EnableSound: boolean;
readonly EnvelopeFeederInstalled: boolean;
FormatScanning: boolean;
FrenchReform: WdFrenchSpeller;
GridDistanceHorizontal: number;
GridDistanceVertical: number;
GridOriginHorizontal: number;
GridOriginVertical: number;
HangulHanjaFastConversion: boolean;
HebrewMode: WdHebSpellStart;
IgnoreInternetAndFileAddresses: boolean;
IgnoreMixedDigits: boolean;
IgnoreUppercase: boolean;
IMEAutomaticControl: boolean;
InlineConversion: boolean;
InsertedCellColor: WdCellColor;
InsertedTextColor: WdColorIndex;
InsertedTextMark: WdInsertedTextMark;
INSKeyForOvertype: boolean;
INSKeyForPaste: boolean;
InterpretHighAnsi: WdHighAnsiText;
LabelSmartTags: boolean;
LocalNetworkFile: boolean;
MapPaperSize: boolean;
MatchFuzzyAY: boolean;
MatchFuzzyBV: boolean;
MatchFuzzyByte: boolean;
MatchFuzzyCase: boolean;
MatchFuzzyDash: boolean;
MatchFuzzyDZ: boolean;
MatchFuzzyHF: boolean;
MatchFuzzyHiragana: boolean;
MatchFuzzyIterationMark: boolean;
MatchFuzzyKanji: boolean;
MatchFuzzyKiKu: boolean;
MatchFuzzyOldKana: boolean;
MatchFuzzyProlongedSoundMark: boolean;
MatchFuzzyPunctuation: boolean;
MatchFuzzySmallKana: boolean;
MatchFuzzySpace: boolean;
MatchFuzzyTC: boolean;
MatchFuzzyZJ: boolean;
MeasurementUnit: WdMeasurementUnits;
MergedCellColor: WdCellColor;
MonthNames: WdMonthNames;
MoveFromTextColor: WdColorIndex;
MoveFromTextMark: WdMoveFromTextMark;
MoveToTextColor: WdColorIndex;
MoveToTextMark: WdMoveToTextMark;
MultipleWordConversionsMode: WdMultipleWordConversionsMode;
OMathAutoBuildUp: boolean;
OMathCopyLF: boolean;
OptimizeForWord97byDefault: boolean;
Overtype: boolean;
Pagination: boolean;
readonly Parent: any;
PasteAdjustParagraphSpacing: boolean;
PasteAdjustTableFormatting: boolean;
PasteAdjustWordSpacing: boolean;
PasteFormatBetweenDocuments: WdPasteOptions;
PasteFormatBetweenStyledDocuments: WdPasteOptions;
PasteFormatFromExternalSource: WdPasteOptions;
PasteFormatWithinDocument: WdPasteOptions;
PasteMergeFromPPT: boolean;
PasteMergeFromXL: boolean;
PasteMergeLists: boolean;
PasteOptionKeepBulletsAndNumbers: boolean;
PasteSmartCutPaste: boolean;
PasteSmartStyleBehavior: boolean;
PictureEditor: string;
PictureWrapType: WdWrapTypeMerged;
PortugalReform: WdPortugueseReform;
PrecisePositioning: boolean;
PrintBackground: boolean;
PrintBackgrounds: boolean;
PrintComments: boolean;
PrintDraft: boolean;
PrintDrawingObjects: boolean;
PrintEvenPagesInAscendingOrder: boolean;
PrintFieldCodes: boolean;
PrintHiddenText: boolean;
PrintOddPagesInAscendingOrder: boolean;
PrintProperties: boolean;
PrintReverse: boolean;
PrintXMLTag: boolean;
PromptUpdateStyle: boolean;
RepeatWord: boolean;
ReplaceSelection: boolean;
RevisedLinesColor: WdColorIndex;
RevisedLinesMark: WdRevisedLinesMark;
RevisedPropertiesColor: WdColorIndex;
RevisedPropertiesMark: WdRevisedPropertiesMark;
RevisionsBalloonPrintOrientation: WdRevisionsBalloonPrintOrientation;
RTFInClipboard: boolean;
SaveInterval: number;
SaveNormalPrompt: boolean;
SavePropertiesPrompt: boolean;
SendMailAttach: boolean;
SequenceCheck: boolean;
SetWPHelpOptions(CommandKeyHelp?: any, DocNavigationKeys?: any, MouseSimulation?: any, DemoGuidance?: any, DemoSpeed?: any, HelpType?: any): void;
ShortMenuNames: boolean;
ShowControlCharacters: boolean;
ShowDevTools: boolean;
ShowDiacritics: boolean;
ShowFormatError: boolean;
ShowMarkupOpenSave: boolean;
ShowMenuFloaties: boolean;
ShowReadabilityStatistics: boolean;
ShowSelectionFloaties: boolean;
SmartCursoring: boolean;
SmartCutPaste: boolean;
SmartParaSelection: boolean;
SnapToGrid: boolean;
SnapToShapes: boolean;
SpanishMode: WdSpanishSpeller;
SplitCellColor: WdCellColor;
StoreRSIDOnSave: boolean;
StrictFinalYaa: boolean;
StrictInitialAlefHamza: boolean;
StrictRussianE: boolean;
StrictTaaMarboota: boolean;
SuggestFromMainDictionaryOnly: boolean;
SuggestSpellingCorrections: boolean;
TabIndentKey: boolean;
TypeNReplace: boolean;
UpdateFieldsAtPrint: boolean;
UpdateFieldsWithTrackedChangesAtPrint: boolean;
UpdateLinksAtOpen: boolean;
UpdateLinksAtPrint: boolean;
UpdateStyleListBehavior: WdUpdateStyleListBehavior;
UseCharacterUnit: boolean;
UseDiffDiacColor: boolean;
UseGermanSpellingReform: boolean;
UseNormalStyleForList: boolean;
VirusProtection: boolean;
VisualSelection: WdVisualSelection;
WarnBeforeSavingPrintingSendingMarkup: boolean;
WPDocNavKeys: boolean;
WPHelp: boolean;
}
class OtherCorrectionsException {
private 'Word.OtherCorrectionsException_typekey': OtherCorrectionsException;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
}
class OtherCorrectionsExceptions {
private 'Word.OtherCorrectionsExceptions_typekey': OtherCorrectionsExceptions;
private constructor();
Add(Name: string): OtherCorrectionsException;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): OtherCorrectionsException;
readonly Parent: any;
}
class Page {
private 'Word.Page_typekey': Page;
private constructor();
readonly Application: Application;
readonly Breaks: Breaks;
readonly Creator: number;
readonly EnhMetaFileBits: any;
readonly Height: number;
readonly Left: number;
readonly Parent: any;
readonly Rectangles: Rectangles;
readonly Top: number;
readonly Width: number;
}
class PageNumber {
private 'Word.PageNumber_typekey': PageNumber;
private constructor();
Alignment: WdPageNumberAlignment;
readonly Application: Application;
Copy(): void;
readonly Creator: number;
Cut(): void;
Delete(): void;
readonly Index: number;
readonly Parent: any;
Select(): void;
}
class PageNumbers {
private 'Word.PageNumbers_typekey': PageNumbers;
private constructor();
Add(PageNumberAlignment?: any, FirstPage?: any): PageNumber;
readonly Application: Application;
ChapterPageSeparator: WdSeparatorType;
readonly Count: number;
readonly Creator: number;
DoubleQuote: boolean;
HeadingLevelForChapter: number;
IncludeChapterNumber: boolean;
Item(Index: number): PageNumber;
NumberStyle: WdPageNumberStyle;
readonly Parent: any;
RestartNumberingAtSection: boolean;
ShowFirstPageNumber: boolean;
StartingNumber: number;
}
class Pages {
private 'Word.Pages_typekey': Pages;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Page;
readonly Parent: any;
}
class PageSetup {
private 'Word.PageSetup_typekey': PageSetup;
private constructor();
readonly Application: Application;
BookFoldPrinting: boolean;
BookFoldPrintingSheets: number;
BookFoldRevPrinting: boolean;
BottomMargin: number;
CharsLine: number;
readonly Creator: number;
DifferentFirstPageHeaderFooter: number;
FirstPageTray: WdPaperTray;
FooterDistance: number;
Gutter: number;
GutterOnTop: boolean;
GutterPos: WdGutterStyle;
GutterStyle: WdGutterStyleOld;
HeaderDistance: number;
LayoutMode: WdLayoutMode;
LeftMargin: number;
LineNumbering: LineNumbering;
LinesPage: number;
MirrorMargins: number;
OddAndEvenPagesHeaderFooter: number;
Orientation: WdOrientation;
OtherPagesTray: WdPaperTray;
PageHeight: number;
PageWidth: number;
PaperSize: WdPaperSize;
readonly Parent: any;
RightMargin: number;
SectionDirection: WdSectionDirection;
SectionStart: WdSectionStart;
SetAsTemplateDefault(): void;
ShowGrid: boolean;
SuppressEndnotes: number;
TextColumns: TextColumns;
TogglePortrait(): void;
TopMargin: number;
TwoPagesOnOne: boolean;
VerticalAlignment: WdVerticalAlignment;
}
class Pane {
private 'Word.Pane_typekey': Pane;
private constructor();
Activate(): void;
readonly Application: Application;
AutoScroll(Velocity: number): void;
BrowseToWindow: boolean;
readonly BrowseWidth: number;
Close(): void;
readonly Creator: number;
DisplayRulers: boolean;
DisplayVerticalRuler: boolean;
readonly Document: Document;
readonly Frameset: Frameset;
HorizontalPercentScrolled: number;
readonly Index: number;
LargeScroll(Down?: any, Up?: any, ToRight?: any, ToLeft?: any): void;
MinimumFontSize: number;
NewFrameset(): void;
readonly Next: Pane;
readonly Pages: Pages;
PageScroll(Down?: any, Up?: any): void;
readonly Parent: any;
readonly Previous: Pane;
readonly Selection: Selection;
SmallScroll(Down?: any, Up?: any, ToRight?: any, ToLeft?: any): void;
TOCInFrameset(): void;
VerticalPercentScrolled: number;
readonly View: View;
readonly Zooms: Zooms;
}
class Panes {
private 'Word.Panes_typekey': Panes;
private constructor();
Add(SplitVertical?: any): Pane;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Pane;
readonly Parent: any;
}
class Paragraph {
private 'Word.Paragraph_typekey': Paragraph;
private constructor();
AddSpaceBetweenFarEastAndAlpha: number;
AddSpaceBetweenFarEastAndDigit: number;
Alignment: WdParagraphAlignment;
readonly Application: Application;
AutoAdjustRightIndent: number;
BaseLineAlignment: WdBaselineAlignment;
Borders: Borders;
CharacterUnitFirstLineIndent: number;
CharacterUnitLeftIndent: number;
CharacterUnitRightIndent: number;
CloseUp(): void;
readonly Creator: number;
DisableLineHeightGrid: number;
readonly DropCap: DropCap;
FarEastLineBreakControl: number;
FirstLineIndent: number;
Format: ParagraphFormat;
HalfWidthPunctuationOnTopOfLine: number;
HangingPunctuation: number;
Hyphenation: number;
ID: string;
Indent(): void;
IndentCharWidth(Count: number): void;
IndentFirstLineCharWidth(Count: number): void;
readonly IsStyleSeparator: boolean;
JoinList(): void;
KeepTogether: number;
KeepWithNext: number;
LeftIndent: number;
LineSpacing: number;
LineSpacingRule: WdLineSpacing;
LineUnitAfter: number;
LineUnitBefore: number;
/**
* @param number [Level1=0]
* @param number [Level2=0]
* @param number [Level3=0]
* @param number [Level4=0]
* @param number [Level5=0]
* @param number [Level6=0]
* @param number [Level7=0]
* @param number [Level8=0]
* @param number [Level9=0]
*/
ListAdvanceTo(Level1?: number, Level2?: number, Level3?: number, Level4?: number, Level5?: number, Level6?: number, Level7?: number, Level8?: number, Level9?: number): void;
ListNumberOriginal(Level: number): number;
MirrorIndents: number;
Next(Count?: any): Paragraph;
NoLineNumber: number;
OpenOrCloseUp(): void;
OpenUp(): void;
Outdent(): void;
OutlineDemote(): void;
OutlineDemoteToBody(): void;
OutlineLevel: WdOutlineLevel;
OutlinePromote(): void;
PageBreakBefore: number;
readonly ParaID: number;
readonly Parent: any;
Previous(Count?: any): Paragraph;
readonly Range: Range;
ReadingOrder: WdReadingOrder;
Reset(): void;
ResetAdvanceTo(): void;
RightIndent: number;
SelectNumber(): void;
SeparateList(): void;
readonly Shading: Shading;
Space1(): void;
Space15(): void;
Space2(): void;
SpaceAfter: number;
SpaceAfterAuto: number;
SpaceBefore: number;
SpaceBeforeAuto: number;
Style: any;
TabHangingIndent(Count: number): void;
TabIndent(Count: number): void;
TabStops: TabStops;
TextboxTightWrap: WdTextboxTightWrap;
readonly TextID: number;
WidowControl: number;
WordWrap: number;
}
class ParagraphFormat {
private 'Word.ParagraphFormat_typekey': ParagraphFormat;
private constructor();
AddSpaceBetweenFarEastAndAlpha: number;
AddSpaceBetweenFarEastAndDigit: number;
Alignment: WdParagraphAlignment;
readonly Application: Application;
AutoAdjustRightIndent: number;
BaseLineAlignment: WdBaselineAlignment;
Borders: Borders;
CharacterUnitFirstLineIndent: number;
CharacterUnitLeftIndent: number;
CharacterUnitRightIndent: number;
CloseUp(): void;
readonly Creator: number;
DisableLineHeightGrid: number;
readonly Duplicate: ParagraphFormat;
FarEastLineBreakControl: number;
FirstLineIndent: number;
HalfWidthPunctuationOnTopOfLine: number;
HangingPunctuation: number;
Hyphenation: number;
IndentCharWidth(Count: number): void;
IndentFirstLineCharWidth(Count: number): void;
KeepTogether: number;
KeepWithNext: number;
LeftIndent: number;
LineSpacing: number;
LineSpacingRule: WdLineSpacing;
LineUnitAfter: number;
LineUnitBefore: number;
MirrorIndents: number;
NoLineNumber: number;
OpenOrCloseUp(): void;
OpenUp(): void;
OutlineLevel: WdOutlineLevel;
PageBreakBefore: number;
readonly Parent: any;
ReadingOrder: WdReadingOrder;
Reset(): void;
RightIndent: number;
readonly Shading: Shading;
Space1(): void;
Space15(): void;
Space2(): void;
SpaceAfter: number;
SpaceAfterAuto: number;
SpaceBefore: number;
SpaceBeforeAuto: number;
Style: any;
TabHangingIndent(Count: number): void;
TabIndent(Count: number): void;
TabStops: TabStops;
TextboxTightWrap: WdTextboxTightWrap;
WidowControl: number;
WordWrap: number;
}
class Paragraphs {
private 'Word.Paragraphs_typekey': Paragraphs;
private constructor();
Add(Range?: any): Paragraph;
AddSpaceBetweenFarEastAndAlpha: number;
AddSpaceBetweenFarEastAndDigit: number;
Alignment: WdParagraphAlignment;
readonly Application: Application;
AutoAdjustRightIndent: number;
BaseLineAlignment: WdBaselineAlignment;
Borders: Borders;
CharacterUnitFirstLineIndent: number;
CharacterUnitLeftIndent: number;
CharacterUnitRightIndent: number;
CloseUp(): void;
readonly Count: number;
readonly Creator: number;
DecreaseSpacing(): void;
DisableLineHeightGrid: number;
FarEastLineBreakControl: number;
readonly First: Paragraph;
FirstLineIndent: number;
Format: ParagraphFormat;
HalfWidthPunctuationOnTopOfLine: number;
HangingPunctuation: number;
Hyphenation: number;
IncreaseSpacing(): void;
Indent(): void;
IndentCharWidth(Count: number): void;
IndentFirstLineCharWidth(Count: number): void;
Item(Index: number): Paragraph;
KeepTogether: number;
KeepWithNext: number;
readonly Last: Paragraph;
LeftIndent: number;
LineSpacing: number;
LineSpacingRule: WdLineSpacing;
LineUnitAfter: number;
LineUnitBefore: number;
NoLineNumber: number;
OpenOrCloseUp(): void;
OpenUp(): void;
Outdent(): void;
OutlineDemote(): void;
OutlineDemoteToBody(): void;
OutlineLevel: WdOutlineLevel;
OutlinePromote(): void;
PageBreakBefore: number;
readonly Parent: any;
ReadingOrder: WdReadingOrder;
Reset(): void;
RightIndent: number;
readonly Shading: Shading;
Space1(): void;
Space15(): void;
Space2(): void;
SpaceAfter: number;
SpaceAfterAuto: number;
SpaceBefore: number;
SpaceBeforeAuto: number;
Style: any;
TabHangingIndent(Count: number): void;
TabIndent(Count: number): void;
TabStops: TabStops;
WidowControl: number;
WordWrap: number;
}
class PictureFormat {
private 'Word.PictureFormat_typekey': PictureFormat;
private constructor();
readonly Application: Application;
Brightness: number;
ColorType: Office.MsoPictureColorType;
Contrast: number;
readonly Creator: number;
Crop: Office.Crop;
CropBottom: number;
CropLeft: number;
CropRight: number;
CropTop: number;
IncrementBrightness(Increment: number): void;
IncrementContrast(Increment: number): void;
readonly Parent: any;
TransparencyColor: number;
TransparentBackground: Office.MsoTriState;
}
class PlotArea {
private 'Word.PlotArea_typekey': PlotArea;
private constructor();
readonly Application: any;
readonly Border: ChartBorder;
ClearFormats(): any;
readonly Creator: number;
readonly Fill: ChartFillFormat;
readonly Format: ChartFormat;
Height: number;
InsideHeight: number;
InsideLeft: number;
InsideTop: number;
InsideWidth: number;
readonly Interior: Interior;
Left: number;
readonly Name: string;
readonly Parent: any;
Position: XlChartElementPosition;
Select(): any;
Top: number;
Width: number;
}
class ProofreadingErrors {
private 'Word.ProofreadingErrors_typekey': ProofreadingErrors;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Range;
readonly Parent: any;
readonly Type: WdProofreadingErrorType;
}
class ProtectedViewWindow {
private 'Word.ProtectedViewWindow_typekey': ProtectedViewWindow;
private constructor();
Activate(): void;
readonly Active: boolean;
readonly Application: Application;
Caption: string;
Close(): void;
readonly Creator: number;
readonly Document: Document;
Edit(PasswordTemplate?: any, WritePasswordDocument?: any, WritePasswordTemplate?: any): Document;
Height: number;
readonly Index: number;
Left: number;
readonly Parent: any;
readonly SourceName: string;
readonly SourcePath: string;
ToggleRibbon(): void;
Top: number;
Visible: boolean;
Width: number;
WindowState: WdWindowState;
}
class ProtectedViewWindows {
private 'Word.ProtectedViewWindows_typekey': ProtectedViewWindows;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): ProtectedViewWindow;
Open(FileName: any, AddToRecentFiles?: any, PasswordDocument?: any, Visible?: any, OpenAndRepair?: any): ProtectedViewWindow;
readonly Parent: any;
}
class Range {
private 'Word.Range_typekey': Range;
private constructor();
readonly Application: Application;
AutoFormat(): void;
Bold: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
BoldBi: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
readonly BookmarkID: number;
readonly Bookmarks: Bookmarks;
Borders: Borders;
Calculate(): number;
readonly CanEdit: number;
readonly CanPaste: number;
Case: WdCharacterCase;
readonly Cells: Cells;
readonly Characters: Characters;
readonly CharacterStyle: any;
CharacterWidth: WdCharacterWidth;
CheckGrammar(): void;
CheckSpelling(
CustomDictionary?: any, IgnoreUppercase?: any, AlwaysSuggest?: any, CustomDictionary2?: any, CustomDictionary3?: any, CustomDictionary4?: any,
CustomDictionary5?: any, CustomDictionary6?: any, CustomDictionary7?: any, CustomDictionary8?: any, CustomDictionary9?: any, CustomDictionary10?: any): void;
CheckSynonyms(): void;
/** @param WdCollapseDirection [Direction=wdCollapseStart] */
Collapse(Direction?: WdCollapseDirection): void;
readonly Columns: Columns;
CombineCharacters: boolean;
readonly Comments: Comments;
ComputeStatistics(Statistic: WdStatistic): number;
readonly Conflicts: Conflicts;
readonly ContentControls: ContentControls;
ConvertHangulAndHanja(ConversionsMode?: any, FastConversion?: any, CheckHangulEnding?: any, EnableRecentOrdering?: any, CustomDictionary?: any): void;
ConvertToTable(
Separator?: any, NumRows?: any, NumColumns?: any, InitialColumnWidth?: any, Format?: any, ApplyBorders?: any, ApplyShading?: any, ApplyFont?: any,
ApplyColor?: any, ApplyHeadingRows?: any, ApplyLastRow?: any, ApplyFirstColumn?: any, ApplyLastColumn?: any, AutoFit?: any, AutoFitBehavior?: any, DefaultTableBehavior?: any): Table;
ConvertToTableOld(
Separator?: any, NumRows?: any, NumColumns?: any, InitialColumnWidth?: any, Format?: any, ApplyBorders?: any, ApplyShading?: any, ApplyFont?: any,
ApplyColor?: any, ApplyHeadingRows?: any, ApplyLastRow?: any, ApplyFirstColumn?: any, ApplyLastColumn?: any, AutoFit?: any): Table;
Copy(): void;
CopyAsPicture(): void;
CreatePublisher(Edition?: any, ContainsPICT?: any, ContainsRTF?: any, ContainsText?: any): void;
readonly Creator: number;
Cut(): void;
Delete(Unit?: WdUnits, Count?: number): number;
DetectLanguage(): void;
DisableCharacterSpaceGrid: boolean;
readonly Document: Document;
readonly Duplicate: Range;
readonly Editors: Editors;
EmphasisMark: WdEmphasisMark;
End: number;
readonly EndnoteOptions: EndnoteOptions;
readonly Endnotes: Endnotes;
EndOf(Unit?: any, Extend?: any): number;
readonly EnhMetaFileBits: any;
Expand(Unit?: any): number;
/**
* @param boolean [OpenAfterExport=false]
* @param Word.WdExportOptimizeFor [OptimizeFor=0]
* @param boolean [ExportCurrentPage=false]
* @param Word.WdExportItem [Item=0]
* @param boolean [IncludeDocProps=false]
* @param boolean [KeepIRM=true]
* @param Word.WdExportCreateBookmarks [CreateBookmarks=0]
* @param boolean [DocStructureTags=true]
* @param boolean [BitmapMissingFonts=true]
* @param boolean [UseISO19005_1=false]
*/
ExportAsFixedFormat(
OutputFileName: string, ExportFormat: WdExportFormat, OpenAfterExport?: boolean, OptimizeFor?: WdExportOptimizeFor, ExportCurrentPage?: boolean,
Item?: WdExportItem, IncludeDocProps?: boolean, KeepIRM?: boolean, CreateBookmarks?: WdExportCreateBookmarks, DocStructureTags?: boolean,
BitmapMissingFonts?: boolean, UseISO19005_1?: boolean, FixedFormatExtClassPtr?: any): void;
ExportFragment(FileName: string, Format: WdSaveFormat): void;
readonly Fields: Fields;
readonly Find: Find<Range>;
FitTextWidth: number;
Font: Font;
readonly FootnoteOptions: FootnoteOptions;
readonly Footnotes: Footnotes;
FormattedText: Range;
readonly FormFields: FormFields;
readonly Frames: Frames;
GetSpellingSuggestions(
CustomDictionary?: any, IgnoreUppercase?: any, MainDictionary?: any, SuggestionMode?: any, CustomDictionary2?: any, CustomDictionary3?: any,
CustomDictionary4?: any, CustomDictionary5?: any, CustomDictionary6?: any, CustomDictionary7?: any, CustomDictionary8?: any, CustomDictionary9?: any,
CustomDictionary10?: any): SpellingSuggestions;
GoTo(What?: any, Which?: any, Count?: any, Name?: any): Range;
GoToEditableRange(EditorID?: any): Range;
GoToNext(What: WdGoToItem): Range;
GoToPrevious(What: WdGoToItem): Range;
GrammarChecked: boolean;
readonly GrammaticalErrors: ProofreadingErrors;
HighlightColorIndex: WdColorIndex;
HorizontalInVertical: WdHorizontalInVerticalType;
readonly HTMLDivisions: HTMLDivisions;
readonly Hyperlinks: Hyperlinks;
ID: string;
/** @param boolean [MatchDestination=false] */
ImportFragment(FileName: string, MatchDestination?: boolean): void;
Information(Type: WdInformation): any;
readonly InlineShapes: InlineShapes;
InRange(Range: Range): boolean;
InsertAfter(Text: string): void;
/** @param number [RelativeTo=0] */
InsertAlignmentTab(Alignment: number, RelativeTo?: number): void;
InsertAutoText(): void;
InsertBefore(Text: string): void;
InsertBreak(Type?: any): void;
InsertCaption(Label: any, Title?: any, TitleAutoText?: any, Position?: any, ExcludeLabel?: any): void;
InsertCaptionXP(Label: any, Title?: any, TitleAutoText?: any, Position?: any): void;
InsertCrossReference(
ReferenceType: any, ReferenceKind: WdReferenceKind, ReferenceItem: any, InsertAsHyperlink?: any, IncludePosition?: any, SeparateNumbers?: any, SeparatorString?: any): void;
InsertCrossReference_2002(ReferenceType: any, ReferenceKind: WdReferenceKind, ReferenceItem: any, InsertAsHyperlink?: any, IncludePosition?: any): void;
InsertDatabase(
Format?: any, Style?: any, LinkToSource?: any, Connection?: any, SQLStatement?: any, SQLStatement1?: any, PasswordDocument?: any, PasswordTemplate?: any,
WritePasswordDocument?: any, WritePasswordTemplate?: any, DataSource?: any, From?: any, To?: any, IncludeFields?: any): void;
InsertDateTime(DateTimeFormat?: any, InsertAsField?: any, InsertAsFullWidth?: any, DateLanguage?: any, CalendarType?: any): void;
InsertDateTimeOld(DateTimeFormat?: any, InsertAsField?: any, InsertAsFullWidth?: any): void;
InsertFile(FileName: string, Range?: any, ConfirmConversions?: any, Link?: any, Attachment?: any): void;
InsertParagraph(): void;
InsertParagraphAfter(): void;
InsertParagraphBefore(): void;
InsertSymbol(CharacterNumber: number, Font?: any, Unicode?: any, Bias?: any): void;
InsertXML(XML: string, Transform?: any): void;
InStory(Range: Range): boolean;
readonly IsEndOfRowMark: boolean;
IsEqual(Range: Range): boolean;
Italic: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
ItalicBi: boolean | WdConstants.wdUndefined | WdConstants.wdToggle;
Kana: WdKana;
LanguageDetected: boolean;
LanguageID: WdLanguageID;
LanguageIDFarEast: WdLanguageID;
LanguageIDOther: WdLanguageID;
readonly ListFormat: ListFormat;
readonly ListParagraphs: ListParagraphs;
readonly ListStyle: any;
readonly Locks: CoAuthLocks;
LookupNameProperties(): void;
ModifyEnclosure(Style: any, Symbol?: any, EnclosedText?: any): void;
Move(Unit?: WdUnits, Count?: number): number;
MoveEnd(Unit?: WdUnits, Count?: number): number;
MoveEndUntil(Cset: any, Count?: any): number;
MoveEndWhile(Cset: any, Count?: any): number;
MoveStart(Unit?: WdUnits, Count?: number): number;
MoveStartUntil(Cset: any, Count?: any): number;
MoveStartWhile(Cset: any, Count?: any): number;
MoveUntil(Cset: any, Count?: any): number;
MoveWhile(Cset: any, Count?: any): number;
Next(Unit?: any, Count?: any): Range;
readonly NextStoryRange: Range;
NextSubdocument(): void;
NoProofing: number;
readonly OMaths: OMaths;
Orientation: WdTextOrientation;
PageSetup: PageSetup;
ParagraphFormat: ParagraphFormat;
readonly Paragraphs: Paragraphs;
readonly ParagraphStyle: any;
readonly Parent: any;
readonly ParentContentControl: ContentControl;
Paste(): void;
PasteAndFormat(Type: WdRecoveryType): void;
PasteAppendTable(): void;
PasteAsNestedTable(): void;
PasteExcelTable(LinkedToExcel: boolean, WordFormatting: boolean, RTF: boolean): void;
PasteSpecial(IconIndex?: any, Link?: any, Placement?: any, DisplayAsIcon?: any, DataType?: any, IconFileName?: any, IconLabel?: any): void;
/**
* @param Word.WdPhoneticGuideAlignmentType [Alignment=-1]
* @param number [Raise=0]
* @param number [FontSize=0]
* @param string [FontName='']
*/
PhoneticGuide(Text: string, Alignment?: WdPhoneticGuideAlignmentType, Raise?: number, FontSize?: number, FontName?: string): void;
Previous(Unit?: any, Count?: any): Range;
readonly PreviousBookmarkID: number;
PreviousSubdocument(): void;
readonly ReadabilityStatistics: ReadabilityStatistics;
Relocate(Direction: number): void;
readonly Revisions: Revisions;
readonly Rows: Rows;
readonly Scripts: Office.Scripts;
readonly Sections: Sections;
Select(): void;
readonly Sentences: Sentences;
SetListLevel(Level: number): void;
SetRange(Start: number, End: number): void;
readonly Shading: Shading;
readonly ShapeRange: ShapeRange;
ShowAll: boolean;
readonly SmartTags: SmartTags;
Sort(
ExcludeHeader?: any, FieldNumber?: any, SortFieldType?: any, SortOrder?: any, FieldNumber2?: any, SortFieldType2?: any, SortOrder2?: any, FieldNumber3?: any,
SortFieldType3?: any, SortOrder3?: any, SortColumn?: any, Separator?: any, CaseSensitive?: any, BidiSort?: any, IgnoreThe?: any, IgnoreKashida?: any,
IgnoreDiacritics?: any, IgnoreHe?: any, LanguageID?: any): void;
SortAscending(): void;
SortDescending(): void;
SortOld(
ExcludeHeader?: any, FieldNumber?: any, SortFieldType?: any, SortOrder?: any, FieldNumber2?: any, SortFieldType2?: any, SortOrder2?: any, FieldNumber3?: any,
SortFieldType3?: any, SortOrder3?: any, SortColumn?: any, Separator?: any, CaseSensitive?: any, LanguageID?: any): void;
SpellingChecked: boolean;
readonly SpellingErrors: ProofreadingErrors;
Start: number;
StartOf(Unit?: any, Extend?: any): number;
readonly StoryLength: number;
readonly StoryType: WdStoryType;
Style: any;
readonly Subdocuments: Subdocuments;
SubscribeTo(Edition: string, Format?: any): void;
readonly SynonymInfo: SynonymInfo;
readonly Tables: Tables;
readonly TableStyle: any;
/**
* @param Word.WdTCSCConverterDirection [WdTCSCConverterDirection=2]
* @param boolean [CommonTerms=false]
* @param boolean [UseVariants=false]
*/
TCSCConverter(WdTCSCConverterDirection?: WdTCSCConverterDirection, CommonTerms?: boolean, UseVariants?: boolean): void;
Text: string;
TextRetrievalMode: TextRetrievalMode;
readonly TopLevelTables: Tables;
TwoLinesInOne: WdTwoLinesInOneType;
Underline: WdUnderline;
readonly Updates: CoAuthUpdates;
WholeStory(): void;
readonly WordOpenXML: string;
readonly Words: Words;
/** @param boolean [DataOnly=false] */
XML(DataOnly?: boolean): string;
readonly XMLNodes: XMLNodes;
readonly XMLParentNode: XMLNode;
}
class ReadabilityStatistic {
private 'Word.ReadabilityStatistic_typekey': ReadabilityStatistic;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Name: string;
readonly Parent: any;
readonly Value: number;
}
class ReadabilityStatistics {
private 'Word.ReadabilityStatistics_typekey': ReadabilityStatistics;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): ReadabilityStatistic;
readonly Parent: any;
}
class RecentFile {
private 'Word.RecentFile_typekey': RecentFile;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Name: string;
Open(): Document;
readonly Parent: any;
readonly Path: string;
ReadOnly: boolean;
}
class RecentFiles {
private 'Word.RecentFiles_typekey': RecentFiles;
private constructor();
Add(Document: any, ReadOnly?: any): RecentFile;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): RecentFile;
Maximum: number;
readonly Parent: any;
}
class Rectangle {
private 'Word.Rectangle_typekey': Rectangle;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Height: number;
readonly Left: number;
readonly Lines: Lines;
readonly Parent: any;
readonly Range: Range;
readonly RectangleType: WdRectangleType;
readonly Top: number;
readonly Width: number;
}
class Rectangles {
private 'Word.Rectangles_typekey': Rectangles;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Rectangle;
readonly Parent: any;
}
class ReflectionFormat {
private 'Word.ReflectionFormat_typekey': ReflectionFormat;
private constructor();
readonly Application: Application;
Blur: number;
readonly Creator: number;
Offset: number;
readonly Parent: any;
Size: number;
Transparency: number;
Type: Office.MsoReflectionType;
}
class Replacement {
private 'Word.Replacement_typekey': Replacement;
private constructor();
readonly Application: Application;
ClearFormatting(): void;
readonly Creator: number;
Font: Font;
readonly Frame: Frame;
Highlight: number;
LanguageID: WdLanguageID;
LanguageIDFarEast: WdLanguageID;
NoProofing: number;
ParagraphFormat: ParagraphFormat;
readonly Parent: any;
Style: any;
Text: string;
}
class Research {
private 'Word.Research_typekey': Research;
private constructor();
readonly Application: Application;
readonly Creator: number;
FavoriteService: string;
IsResearchService(ServiceID: string): boolean;
readonly Parent: any;
/**
* @param string [QueryString='']
* @param Word.WdLanguageID [QueryLanguage=0]
* @param boolean [UseSelection=false]
* @param boolean [LaunchQuery=true]
*/
Query(ServiceID: string, QueryString?: string, QueryLanguage?: WdLanguageID, UseSelection?: boolean, LaunchQuery?: boolean): any;
SetLanguagePair(LanguageFrom: WdLanguageID, LanguageTo: WdLanguageID): any;
}
class Reviewer {
private 'Word.Reviewer_typekey': Reviewer;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Parent: any;
Visible: boolean;
}
class Reviewers {
private 'Word.Reviewers_typekey': Reviewers;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Reviewer;
readonly Parent: any;
}
class Revision {
private 'Word.Revision_typekey': Revision;
private constructor();
Accept(): void;
readonly Application: Application;
readonly Author: string;
readonly Cells: Cells;
readonly Creator: number;
readonly Date: VarDate;
readonly FormatDescription: string;
readonly Index: number;
readonly MovedRange: Range;
readonly Parent: any;
readonly Range: Range;
Reject(): void;
readonly Style: Style;
readonly Type: WdRevisionType;
}
class Revisions {
private 'Word.Revisions_typekey': Revisions;
private constructor();
AcceptAll(): void;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Revision;
readonly Parent: any;
RejectAll(): void;
}
class RoutingSlip {
private 'Word.RoutingSlip_typekey': RoutingSlip;
private constructor();
AddRecipient(Recipient: string): void;
readonly Application: Application;
readonly Creator: number;
Delivery: WdRoutingSlipDelivery;
Message: string;
readonly Parent: any;
Protect: WdProtectionType;
Recipients(Index?: any): any;
Reset(): void;
ReturnWhenDone: boolean;
readonly Status: WdRoutingSlipStatus;
Subject: string;
TrackStatus: boolean;
}
class Row {
private 'Word.Row_typekey': Row;
private constructor();
Alignment: WdRowAlignment;
AllowBreakAcrossPages: number;
readonly Application: Application;
Borders: Borders;
readonly Cells: Cells;
ConvertToText(Separator?: any, NestedTables?: any): Range;
ConvertToTextOld(Separator?: any): Range;
readonly Creator: number;
Delete(): void;
HeadingFormat: number;
Height: number;
HeightRule: WdRowHeightRule;
ID: string;
readonly Index: number;
readonly IsFirst: boolean;
readonly IsLast: boolean;
LeftIndent: number;
readonly NestingLevel: number;
readonly Next: Row;
readonly Parent: any;
readonly Previous: Row;
readonly Range: Range;
Select(): void;
SetHeight(RowHeight: number, HeightRule: WdRowHeightRule): void;
SetLeftIndent(LeftIndent: number, RulerStyle: WdRulerStyle): void;
readonly Shading: Shading;
SpaceBetweenColumns: number;
}
class Rows {
private 'Word.Rows_typekey': Rows;
private constructor();
Add(BeforeRow?: any): Row;
Alignment: WdRowAlignment;
AllowBreakAcrossPages: number;
AllowOverlap: number;
readonly Application: Application;
Borders: Borders;
ConvertToText(Separator?: any, NestedTables?: any): Range;
ConvertToTextOld(Separator?: any): Range;
readonly Count: number;
readonly Creator: number;
Delete(): void;
DistanceBottom: number;
DistanceLeft: number;
DistanceRight: number;
DistanceTop: number;
DistributeHeight(): void;
readonly First: Row;
HeadingFormat: number;
Height: number;
HeightRule: WdRowHeightRule;
HorizontalPosition: number;
Item(Index: number): Row;
readonly Last: Row;
LeftIndent: number;
readonly NestingLevel: number;
readonly Parent: any;
RelativeHorizontalPosition: WdRelativeHorizontalPosition;
RelativeVerticalPosition: WdRelativeVerticalPosition;
Select(): void;
SetHeight(RowHeight: number, HeightRule: WdRowHeightRule): void;
SetLeftIndent(LeftIndent: number, RulerStyle: WdRulerStyle): void;
readonly Shading: Shading;
SpaceBetweenColumns: number;
TableDirection: WdTableDirection;
VerticalPosition: number;
WrapAroundText: number;
}
class Section {
private 'Word.Section_typekey': Section;
private constructor();
readonly Application: Application;
Borders: Borders;
readonly Creator: number;
readonly Footers: HeadersFooters;
readonly Headers: HeadersFooters;
readonly Index: number;
PageSetup: PageSetup;
readonly Parent: any;
ProtectedForForms: boolean;
readonly Range: Range;
}
class Sections {
private 'Word.Sections_typekey': Sections;
private constructor();
Add(Range?: any, Start?: any): Section;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
readonly First: Section;
Item(Index: number): Section;
readonly Last: Section;
PageSetup: PageSetup;
readonly Parent: any;
}
class Selection {
private 'Word.Selection_typekey': Selection;
private constructor();
readonly Active: boolean;
readonly Application: Application;
BoldRun(): void;
readonly BookmarkID: number;
readonly Bookmarks: Bookmarks;
Borders: Borders;
Calculate(): number;
readonly Cells: Cells;
readonly Characters: Characters;
readonly ChildShapeRange: ShapeRange;
ClearCharacterAllFormatting(): void;
ClearCharacterDirectFormatting(): void;
ClearCharacterStyle(): void;
ClearFormatting(): void;
ClearParagraphAllFormatting(): void;
ClearParagraphDirectFormatting(): void;
ClearParagraphStyle(): void;
/** @param WdCollapseDirection [Direction=wdCollapseStart] */
Collapse(Direction?: WdCollapseDirection): void;
readonly Columns: Columns;
ColumnSelectMode: boolean;
readonly Comments: Comments;
readonly ContentControls: ContentControls;
ConvertToTable(
Separator?: any, NumRows?: any, NumColumns?: any, InitialColumnWidth?: any, Format?: any, ApplyBorders?: any, ApplyShading?: any, ApplyFont?: any,
ApplyColor?: any, ApplyHeadingRows?: any, ApplyLastRow?: any, ApplyFirstColumn?: any, ApplyLastColumn?: any, AutoFit?: any, AutoFitBehavior?: any, DefaultTableBehavior?: any): Table;
ConvertToTableOld(
Separator?: any, NumRows?: any, NumColumns?: any, InitialColumnWidth?: any, Format?: any, ApplyBorders?: any, ApplyShading?: any, ApplyFont?: any,
ApplyColor?: any, ApplyHeadingRows?: any, ApplyLastRow?: any, ApplyFirstColumn?: any, ApplyLastColumn?: any, AutoFit?: any): Table;
Copy(): void;
CopyAsPicture(): void;
CopyFormat(): void;
CreateAutoTextEntry(Name: string, StyleName: string): AutoTextEntry;
CreateTextbox(): void;
readonly Creator: number;
Cut(): void;
Delete(Unit?: WdUnits, Count?: number): number;
DetectLanguage(): void;
readonly Document: Document;
readonly Editors: Editors;
End: number;
EndKey(Unit?: any, Extend?: any): number;
readonly EndnoteOptions: EndnoteOptions;
readonly Endnotes: Endnotes;
EndOf(Unit?: any, Extend?: any): number;
readonly EnhMetaFileBits: any;
EscapeKey(): void;
Expand(Unit?: any): number;
/**
* @param boolean [OpenAfterExport=false]
* @param Word.WdExportOptimizeFor [OptimizeFor=0]
* @param boolean [ExportCurrentPage=false]
* @param Word.WdExportItem [Item=0]
* @param boolean [IncludeDocProps=false]
* @param boolean [KeepIRM=true]
* @param Word.WdExportCreateBookmarks [CreateBookmarks=0]
* @param boolean [DocStructureTags=true]
* @param boolean [BitmapMissingFonts=true]
* @param boolean [UseISO19005_1=false]
*/
ExportAsFixedFormat(
OutputFileName: string, ExportFormat: WdExportFormat, OpenAfterExport?: boolean, OptimizeFor?: WdExportOptimizeFor, ExportCurrentPage?: boolean,
Item?: WdExportItem, IncludeDocProps?: boolean, KeepIRM?: boolean, CreateBookmarks?: WdExportCreateBookmarks, DocStructureTags?: boolean,
BitmapMissingFonts?: boolean, UseISO19005_1?: boolean, FixedFormatExtClassPtr?: any): void;
Extend(Character?: any): void;
ExtendMode: boolean;
readonly Fields: Fields;
readonly Find: Find<Selection>;
FitTextWidth: number;
Flags: WdSelectionFlags;
Font: Font;
readonly FootnoteOptions: FootnoteOptions;
readonly Footnotes: Footnotes;
FormattedText: Range;
readonly FormFields: FormFields;
readonly Frames: Frames;
GoTo(What?: any, Which?: any, Count?: any, Name?: any): Range;
GoToEditableRange(EditorID?: any): Range;
GoToNext(What: WdGoToItem): Range;
GoToPrevious(What: WdGoToItem): Range;
readonly HasChildShapeRange: boolean;
readonly HeaderFooter: HeaderFooter;
HomeKey(Unit?: any, Extend?: any): number;
readonly HTMLDivisions: HTMLDivisions;
readonly Hyperlinks: Hyperlinks;
Information(Type: WdInformation): any;
readonly InlineShapes: InlineShapes;
InRange(Range: Range): boolean;
InsertAfter(Text: string): void;
InsertBefore(Text: string): void;
InsertBreak(Type?: any): void;
InsertCaption(Label: any, Title?: any, TitleAutoText?: any, Position?: any, ExcludeLabel?: any): void;
InsertCaptionXP(Label: any, Title?: any, TitleAutoText?: any, Position?: any): void;
InsertCells(ShiftCells?: any): void;
InsertColumns(): void;
InsertColumnsRight(): void;
InsertCrossReference(
ReferenceType: any, ReferenceKind: WdReferenceKind, ReferenceItem: any, InsertAsHyperlink?: any, IncludePosition?: any, SeparateNumbers?: any, SeparatorString?: any): void;
InsertCrossReference_2002(ReferenceType: any, ReferenceKind: WdReferenceKind, ReferenceItem: any, InsertAsHyperlink?: any, IncludePosition?: any): void;
InsertDateTime(DateTimeFormat?: any, InsertAsField?: any, InsertAsFullWidth?: any, DateLanguage?: any, CalendarType?: any): void;
InsertDateTimeOld(DateTimeFormat?: any, InsertAsField?: any, InsertAsFullWidth?: any): void;
InsertFile(FileName: string, Range?: any, ConfirmConversions?: any, Link?: any, Attachment?: any): void;
InsertFormula(Formula?: any, NumberFormat?: any): void;
InsertNewPage(): void;
InsertParagraph(): void;
InsertParagraphAfter(): void;
InsertParagraphBefore(): void;
InsertRows(NumRows?: any): void;
InsertRowsAbove(NumRows?: any): void;
InsertRowsBelow(NumRows?: any): void;
InsertStyleSeparator(): void;
InsertSymbol(CharacterNumber: number, Font?: any, Unicode?: any, Bias?: any): void;
InsertXML(XML: string, Transform?: any): void;
InStory(Range: Range): boolean;
readonly IPAtEndOfLine: boolean;
readonly IsEndOfRowMark: boolean;
IsEqual(Range: Range): boolean;
ItalicRun(): void;
LanguageDetected: boolean;
LanguageID: WdLanguageID;
LanguageIDFarEast: WdLanguageID;
LanguageIDOther: WdLanguageID;
LtrPara(): void;
LtrRun(): void;
Move(Unit?: WdUnits, Count?: number): number;
MoveDown(Unit?: WdUnits, Count?: number): number;
MoveEnd(Unit?: WdUnits, Count?: number): number;
MoveEndUntil(Cset: any, Count?: any): number;
MoveEndWhile(Cset: any, Count?: any): number;
MoveLeft(Unit?: WdUnits, Count?: number): number;
MoveRight(Unit?: WdUnits, Count?: number): number;
MoveStart(Unit?: WdUnits, Count?: number): number;
MoveStartUntil(Cset: any, Count?: any): number;
MoveStartWhile(Cset: any, Count?: any): number;
MoveUntil(Cset: any, Count?: any): number;
MoveUp(Unit?: WdUnits, Count?: number): number;
MoveWhile(Cset: any, Count?: any): number;
Next(Unit?: WdUnits, Count?: number): Range;
NextField(): Field;
NextRevision(Wrap?: any): Revision;
NextSubdocument(): void;
NoProofing: number;
readonly OMaths: OMaths;
Orientation: WdTextOrientation;
PageSetup: PageSetup;
ParagraphFormat: ParagraphFormat;
readonly Paragraphs: Paragraphs;
readonly Parent: any;
readonly ParentContentControl: ContentControl;
Paste(): void;
PasteAndFormat(Type: WdRecoveryType): void;
PasteAppendTable(): void;
PasteAsNestedTable(): void;
PasteExcelTable(LinkedToExcel: boolean, WordFormatting: boolean, RTF: boolean): void;
PasteFormat(): void;
PasteSpecial(IconIndex?: any, Link?: any, Placement?: any, DisplayAsIcon?: any, DataType?: any, IconFileName?: any, IconLabel?: any): void;
Previous(Unit?: any, Count?: any): Range;
readonly PreviousBookmarkID: number;
PreviousField(): Field;
PreviousRevision(Wrap?: any): Revision;
PreviousSubdocument(): void;
readonly Range: Range;
ReadingModeGrowFont(): void;
ReadingModeShrinkFont(): void;
readonly Rows: Rows;
RtlPara(): void;
RtlRun(): void;
readonly Sections: Sections;
Select(): void;
SelectCell(): void;
SelectColumn(): void;
SelectCurrentAlignment(): void;
SelectCurrentColor(): void;
SelectCurrentFont(): void;
SelectCurrentIndent(): void;
SelectCurrentSpacing(): void;
SelectCurrentTabs(): void;
SelectRow(): void;
readonly Sentences: Sentences;
SetRange(Start: number, End: number): void;
readonly Shading: Shading;
readonly ShapeRange: ShapeRange;
Shrink(): void;
ShrinkDiscontiguousSelection(): void;
readonly SmartTags: SmartTags;
Sort(
ExcludeHeader?: any, FieldNumber?: any, SortFieldType?: any, SortOrder?: any, FieldNumber2?: any, SortFieldType2?: any, SortOrder2?: any, FieldNumber3?: any,
SortFieldType3?: any, SortOrder3?: any, SortColumn?: any, Separator?: any, CaseSensitive?: any, BidiSort?: any, IgnoreThe?: any, IgnoreKashida?: any,
IgnoreDiacritics?: any, IgnoreHe?: any, LanguageID?: any, SubFieldNumber?: any, SubFieldNumber2?: any, SubFieldNumber3?: any): void;
Sort2000(
ExcludeHeader?: any, FieldNumber?: any, SortFieldType?: any, SortOrder?: any, FieldNumber2?: any, SortFieldType2?: any, SortOrder2?: any, FieldNumber3?: any,
SortFieldType3?: any, SortOrder3?: any, SortColumn?: any, Separator?: any, CaseSensitive?: any, BidiSort?: any, IgnoreThe?: any, IgnoreKashida?: any,
IgnoreDiacritics?: any, IgnoreHe?: any, LanguageID?: any): void;
SortAscending(): void;
SortDescending(): void;
SortOld(
ExcludeHeader?: any, FieldNumber?: any, SortFieldType?: any, SortOrder?: any, FieldNumber2?: any, SortFieldType2?: any, SortOrder2?: any, FieldNumber3?: any,
SortFieldType3?: any, SortOrder3?: any, SortColumn?: any, Separator?: any, CaseSensitive?: any, LanguageID?: any): void;
SplitTable(): void;
Start: number;
StartIsActive: boolean;
StartOf(Unit?: any, Extend?: any): number;
readonly StoryLength: number;
readonly StoryType: WdStoryType;
Style: any;
readonly Tables: Tables;
Text: string;
ToggleCharacterCode(): void;
readonly TopLevelTables: Tables;
readonly Type: WdSelectionType;
TypeBackspace(): void;
TypeParagraph(): void;
TypeText(Text: string): void;
WholeStory(): void;
readonly WordOpenXML: string;
readonly Words: Words;
/** @param boolean [DataOnly=false] */
XML(DataOnly?: boolean): string;
readonly XMLNodes: XMLNodes;
readonly XMLParentNode: XMLNode;
}
class Sentences {
private 'Word.Sentences_typekey': Sentences;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
readonly First: Range;
Item(Index: number): Range;
readonly Last: Range;
readonly Parent: any;
}
class SeriesLines {
private 'Word.SeriesLines_typekey': SeriesLines;
private constructor();
readonly Application: any;
readonly Border: ChartBorder;
readonly Creator: number;
Delete(): any;
readonly Format: ChartFormat;
readonly Name: string;
readonly Parent: any;
Select(): any;
}
class Shading {
private 'Word.Shading_typekey': Shading;
private constructor();
readonly Application: Application;
BackgroundPatternColor: WdColor;
BackgroundPatternColorIndex: WdColorIndex;
readonly Creator: number;
ForegroundPatternColor: WdColor;
ForegroundPatternColorIndex: WdColorIndex;
readonly Parent: any;
Texture: WdTextureIndex;
}
class ShadowFormat {
private 'Word.ShadowFormat_typekey': ShadowFormat;
private constructor();
readonly Application: Application;
Blur: number;
readonly Creator: number;
readonly ForeColor: ColorFormat;
IncrementOffsetX(Increment: number): void;
IncrementOffsetY(Increment: number): void;
Obscured: Office.MsoTriState;
OffsetX: number;
OffsetY: number;
readonly Parent: any;
RotateWithShape: Office.MsoTriState;
Size: number;
Style: Office.MsoShadowStyle;
Transparency: number;
Type: Office.MsoShadowType;
Visible: Office.MsoTriState;
}
class Shape {
private 'Word.Shape_typekey': Shape;
private constructor();
Activate(): void;
readonly Adjustments: Adjustments;
AlternativeText: string;
readonly Anchor: Range;
readonly AnchorID: number;
readonly Application: Application;
Apply(): void;
AutoShapeType: Office.MsoAutoShapeType;
BackgroundStyle: Office.MsoBackgroundStyleIndex;
readonly Callout: CalloutFormat;
CanvasCropBottom(Increment: number): void;
CanvasCropLeft(Increment: number): void;
CanvasCropRight(Increment: number): void;
CanvasCropTop(Increment: number): void;
readonly CanvasItems: CanvasShapes;
readonly Chart: Chart;
readonly Child: Office.MsoTriState;
readonly ConnectionSiteCount: number;
readonly Connector: Office.MsoTriState;
readonly ConnectorFormat: ConnectorFormat;
ConvertToFrame(): Frame;
ConvertToInlineShape(): InlineShape;
readonly Creator: number;
Delete(): void;
readonly Diagram: Office.IMsoDiagram;
readonly DiagramNode: DiagramNode;
Duplicate(): Shape;
readonly EditID: number;
readonly Fill: FillFormat;
Flip(FlipCmd: Office.MsoFlipCmd): void;
readonly Glow: GlowFormat;
readonly GroupItems: GroupShapes;
readonly HasChart: Office.MsoTriState;
readonly HasDiagram: Office.MsoTriState;
readonly HasDiagramNode: Office.MsoTriState;
readonly HasSmartArt: Office.MsoTriState;
Height: number;
HeightRelative: number;
readonly HorizontalFlip: Office.MsoTriState;
readonly Hyperlink: Hyperlink;
readonly ID: number;
IncrementLeft(Increment: number): void;
IncrementRotation(Increment: number): void;
IncrementTop(Increment: number): void;
LayoutInCell: number;
Left: number;
LeftRelative: number;
readonly Line: LineFormat;
readonly LinkFormat: LinkFormat;
LockAnchor: number;
LockAspectRatio: Office.MsoTriState;
Name: string;
readonly Nodes: ShapeNodes;
readonly OLEFormat: OLEFormat;
readonly Parent: any;
readonly ParentGroup: Shape;
PickUp(): void;
readonly PictureFormat: PictureFormat;
readonly Reflection: ReflectionFormat;
RelativeHorizontalPosition: WdRelativeHorizontalPosition;
RelativeHorizontalSize: WdRelativeHorizontalSize;
RelativeVerticalPosition: WdRelativeVerticalPosition;
RelativeVerticalSize: WdRelativeVerticalSize;
RerouteConnections(): void;
Rotation: number;
readonly RTF: string;
/** @param Office.MsoScaleFrom [Scale=0] */
ScaleHeight(Factor: number, RelativeToOriginalSize: Office.MsoTriState, Scale?: Office.MsoScaleFrom): void;
/** @param Office.MsoScaleFrom [Scale=0] */
ScaleWidth(Factor: number, RelativeToOriginalSize: Office.MsoTriState, Scale?: Office.MsoScaleFrom): void;
readonly Script: Office.Script;
Select(Replace?: any): void;
SetShapesDefaultProperties(): void;
readonly Shadow: ShadowFormat;
ShapeStyle: Office.MsoShapeStyleIndex;
readonly SmartArt: Office.SmartArt;
readonly SoftEdge: SoftEdgeFormat;
readonly TextEffect: TextEffectFormat;
readonly TextFrame: TextFrame;
readonly TextFrame2: Office.TextFrame2;
readonly ThreeD: ThreeDFormat;
Title: string;
Top: number;
TopRelative: number;
readonly Type: Office.MsoShapeType;
Ungroup(): ShapeRange;
readonly VerticalFlip: Office.MsoTriState;
readonly Vertices: any;
Visible: Office.MsoTriState;
Width: number;
WidthRelative: number;
readonly WrapFormat: WrapFormat;
ZOrder(ZOrderCmd: Office.MsoZOrderCmd): void;
readonly ZOrderPosition: number;
}
class ShapeNode {
private 'Word.ShapeNode_typekey': ShapeNode;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly EditingType: Office.MsoEditingType;
readonly Parent: any;
readonly Points: any;
readonly SegmentType: Office.MsoSegmentType;
}
class ShapeNodes {
private 'Word.ShapeNodes_typekey': ShapeNodes;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Delete(Index: number): void;
/**
* @param number [X2=0]
* @param number [Y2=0]
* @param number [X3=0]
* @param number [Y3=0]
*/
Insert(Index: number, SegmentType: Office.MsoSegmentType, EditingType: Office.MsoEditingType, X1: number, Y1: number, X2?: number, Y2?: number, X3?: number, Y3?: number): void;
Item(Index: any): ShapeNode;
readonly Parent: any;
SetEditingType(Index: number, EditingType: Office.MsoEditingType): void;
SetPosition(Index: number, X1: number, Y1: number): void;
SetSegmentType(Index: number, SegmentType: Office.MsoSegmentType): void;
}
class ShapeRange {
private 'Word.ShapeRange_typekey': ShapeRange;
private constructor();
Activate(): void;
readonly Adjustments: Adjustments;
Align(Align: Office.MsoAlignCmd, RelativeTo: number): void;
AlternativeText: string;
readonly Anchor: Range;
readonly Application: Application;
Apply(): void;
AutoShapeType: Office.MsoAutoShapeType;
BackgroundStyle: Office.MsoBackgroundStyleIndex;
readonly Callout: CalloutFormat;
CanvasCropBottom(Increment: number): void;
CanvasCropLeft(Increment: number): void;
CanvasCropRight(Increment: number): void;
CanvasCropTop(Increment: number): void;
readonly CanvasItems: CanvasShapes;
readonly Child: Office.MsoTriState;
readonly ConnectionSiteCount: number;
readonly Connector: Office.MsoTriState;
readonly ConnectorFormat: ConnectorFormat;
ConvertToFrame(): Frame;
ConvertToInlineShape(): InlineShape;
readonly Count: number;
readonly Creator: number;
Delete(): void;
readonly Diagram: Office.IMsoDiagram;
readonly DiagramNode: DiagramNode;
Distribute(Distribute: Office.MsoDistributeCmd, RelativeTo: number): void;
Duplicate(): ShapeRange;
readonly Fill: FillFormat;
Flip(FlipCmd: Office.MsoFlipCmd): void;
readonly Glow: GlowFormat;
Group(): Shape;
readonly GroupItems: GroupShapes;
readonly HasDiagram: Office.MsoTriState;
readonly HasDiagramNode: Office.MsoTriState;
Height: number;
HeightRelative: number;
readonly HorizontalFlip: Office.MsoTriState;
readonly Hyperlink: Hyperlink;
readonly ID: number;
IncrementLeft(Increment: number): void;
IncrementRotation(Increment: number): void;
IncrementTop(Increment: number): void;
Item(Index: any): Shape;
LayoutInCell: number;
Left: number;
LeftRelative: number;
readonly Line: LineFormat;
LockAnchor: number;
LockAspectRatio: Office.MsoTriState;
Name: string;
readonly Nodes: ShapeNodes;
readonly Parent: any;
readonly ParentGroup: Shape;
PickUp(): void;
readonly PictureFormat: PictureFormat;
readonly Reflection: ReflectionFormat;
Regroup(): Shape;
RelativeHorizontalPosition: WdRelativeHorizontalPosition;
RelativeHorizontalSize: WdRelativeHorizontalSize;
RelativeVerticalPosition: WdRelativeVerticalPosition;
RelativeVerticalSize: WdRelativeVerticalSize;
RerouteConnections(): void;
Rotation: number;
readonly RTF: string;
/** @param Office.MsoScaleFrom [Scale=0] */
ScaleHeight(Factor: number, RelativeToOriginalSize: Office.MsoTriState, Scale?: Office.MsoScaleFrom): void;
/** @param Office.MsoScaleFrom [Scale=0] */
ScaleWidth(Factor: number, RelativeToOriginalSize: Office.MsoTriState, Scale?: Office.MsoScaleFrom): void;
Select(Replace?: any): void;
SetShapesDefaultProperties(): void;
readonly Shadow: ShadowFormat;
ShapeStyle: Office.MsoShapeStyleIndex;
readonly SoftEdge: SoftEdgeFormat;
readonly TextEffect: TextEffectFormat;
readonly TextFrame: TextFrame;
readonly TextFrame2: Office.TextFrame2;
readonly ThreeD: ThreeDFormat;
Title: string;
Top: number;
TopRelative: number;
readonly Type: Office.MsoShapeType;
Ungroup(): ShapeRange;
readonly VerticalFlip: Office.MsoTriState;
readonly Vertices: any;
Visible: Office.MsoTriState;
Width: number;
WidthRelative: number;
readonly WrapFormat: WrapFormat;
ZOrder(ZOrderCmd: Office.MsoZOrderCmd): void;
readonly ZOrderPosition: number;
}
class Shapes {
private 'Word.Shapes_typekey': Shapes;
private constructor();
AddCallout(Type: Office.MsoCalloutType, Left: number, Top: number, Width: number, Height: number, Anchor?: any): Shape;
AddCanvas(Left: number, Top: number, Width: number, Height: number, Anchor?: any): Shape;
/** @param Office.XlChartType [Type=-1] */
AddChart(Type?: Office.XlChartType, Left?: any, Top?: any, Width?: any, Height?: any, Anchor?: any): Shape;
AddConnector(Type: Office.MsoConnectorType, BeginX: number, BeginY: number, EndX: number, EndY: number): Shape;
AddCurve(SafeArrayOfPoints: any, Anchor?: any): Shape;
AddDiagram(Type: Office.MsoDiagramType, Left: number, Top: number, Width: number, Height: number, Anchor?: any): Shape;
AddLabel(Orientation: Office.MsoTextOrientation, Left: number, Top: number, Width: number, Height: number, Anchor?: any): Shape;
AddLine(BeginX: number, BeginY: number, EndX: number, EndY: number, Anchor?: any): Shape;
AddOLEControl(ClassType?: any, Left?: any, Top?: any, Width?: any, Height?: any, Anchor?: any): Shape;
AddOLEObject(
ClassType?: any, FileName?: any, LinkToFile?: any, DisplayAsIcon?: any, IconFileName?: any, IconIndex?: any, IconLabel?: any, Left?: any, Top?: any,
Width?: any, Height?: any, Anchor?: any): Shape;
AddPicture(FileName: string, LinkToFile?: any, SaveWithDocument?: any, Left?: any, Top?: any, Width?: any, Height?: any, Anchor?: any): Shape;
AddPolyline(SafeArrayOfPoints: any, Anchor?: any): Shape;
AddShape(Type: number, Left: number, Top: number, Width: number, Height: number, Anchor?: any): Shape;
AddSmartArt(Layout: Office.SmartArtLayout, Left?: any, Top?: any, Width?: any, Height?: any, Anchor?: any): Shape;
AddTextbox(Orientation: Office.MsoTextOrientation, Left: number, Top: number, Width: number, Height: number, Anchor?: any): Shape;
AddTextEffect(
PresetTextEffect: Office.MsoPresetTextEffect, Text: string, FontName: string, FontSize: number, FontBold: Office.MsoTriState, FontItalic: Office.MsoTriState,
Left: number, Top: number, Anchor?: any): Shape;
readonly Application: Application;
BuildFreeform(EditingType: Office.MsoEditingType, X1: number, Y1: number): FreeformBuilder;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Shape;
readonly Parent: any;
Range(Index: any): ShapeRange;
SelectAll(): void;
}
class SmartTag {
private 'Word.SmartTag_typekey': SmartTag;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly DownloadURL: string;
readonly Name: string;
readonly Parent: any;
readonly Properties: CustomProperties;
readonly Range: Range;
Select(): void;
readonly SmartTagActions: SmartTagActions;
readonly XML: string;
readonly XMLNode: XMLNode;
}
class SmartTagAction {
private 'Word.SmartTagAction_typekey': SmartTagAction;
private constructor();
readonly ActiveXControl: any;
readonly Application: Application;
CheckboxState: boolean;
readonly Creator: number;
Execute(): void;
ExpandDocumentFragment: boolean;
ExpandHelp: boolean;
ListSelection: number;
readonly Name: string;
readonly Parent: any;
readonly PresentInPane: boolean;
RadioGroupSelection: number;
TextboxText: string;
readonly Type: WdSmartTagControlType;
}
class SmartTagActions {
private 'Word.SmartTagActions_typekey': SmartTagActions;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): SmartTagAction;
readonly Parent: any;
ReloadActions(): void;
}
class SmartTagRecognizer {
private 'Word.SmartTagRecognizer_typekey': SmartTagRecognizer;
private constructor();
readonly Application: Application;
readonly Caption: string;
readonly Creator: number;
Enabled: boolean;
readonly FullName: string;
readonly Parent: any;
readonly ProgID: string;
}
class SmartTagRecognizers {
private 'Word.SmartTagRecognizers_typekey': SmartTagRecognizers;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): SmartTagRecognizer;
readonly Parent: any;
ReloadRecognizers(): void;
}
class SmartTags {
private 'Word.SmartTags_typekey': SmartTags;
private constructor();
Add(Name: string, Range?: any, Properties?: any): SmartTag;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): SmartTag;
readonly Parent: any;
SmartTagsByType(Name: string): SmartTags;
}
class SmartTagType {
private 'Word.SmartTagType_typekey': SmartTagType;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly FriendlyName: string;
readonly Name: string;
readonly Parent: any;
readonly SmartTagActions: SmartTagActions;
readonly SmartTagRecognizers: SmartTagRecognizers;
}
class SmartTagTypes {
private 'Word.SmartTagTypes_typekey': SmartTagTypes;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): SmartTagType;
readonly Parent: any;
ReloadAll(): void;
}
class SoftEdgeFormat {
private 'Word.SoftEdgeFormat_typekey': SoftEdgeFormat;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Parent: any;
Radius: number;
Type: Office.MsoSoftEdgeType;
}
class Source {
private 'Word.Source_typekey': Source;
private constructor();
readonly Application: Application;
readonly Cited: boolean;
readonly Creator: number;
Delete(): void;
Field(Name: string): string;
readonly Parent: any;
readonly Tag: string;
readonly XML: string;
}
class Sources {
private 'Word.Sources_typekey': Sources;
private constructor();
Add(Data: string): void;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Source;
readonly Parent: any;
}
class SpellingSuggestion {
private 'Word.SpellingSuggestion_typekey': SpellingSuggestion;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Name: string;
readonly Parent: any;
}
class SpellingSuggestions {
private 'Word.SpellingSuggestions_typekey': SpellingSuggestions;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): SpellingSuggestion;
readonly Parent: any;
readonly SpellingErrorType: WdSpellingErrorType;
}
class StoryRanges {
private 'Word.StoryRanges_typekey': StoryRanges;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: WdStoryType): Range;
readonly Parent: any;
}
class Style {
private 'Word.Style_typekey': Style;
private constructor();
readonly Application: Application;
AutomaticallyUpdate: boolean;
BaseStyle: any;
Borders: Borders;
readonly BuiltIn: boolean;
readonly Creator: number;
Delete(): void;
readonly Description: string;
Font: Font;
readonly Frame: Frame;
Hidden: boolean;
readonly InUse: boolean;
LanguageID: WdLanguageID;
LanguageIDFarEast: WdLanguageID;
readonly Linked: boolean;
LinkStyle: any;
LinkToListTemplate(ListTemplate: ListTemplate, ListLevelNumber?: any): void;
readonly ListLevelNumber: number;
readonly ListTemplate: ListTemplate;
Locked: boolean;
NameLocal: string;
NextParagraphStyle: any;
NoProofing: number;
NoSpaceBetweenParagraphsOfSameStyle: boolean;
ParagraphFormat: ParagraphFormat;
readonly Parent: any;
Priority: number;
QuickStyle: boolean;
readonly Shading: Shading;
readonly Table: TableStyle;
readonly Type: WdStyleType;
UnhideWhenUsed: boolean;
Visibility: boolean;
}
class Styles {
private 'Word.Styles_typekey': Styles;
private constructor();
Add(Name: string, Type?: any): Style;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Style;
readonly Parent: any;
}
class StyleSheet {
private 'Word.StyleSheet_typekey': StyleSheet;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly FullName: string;
readonly Index: number;
Move(Precedence: WdStyleSheetPrecedence): void;
readonly Name: string;
readonly Parent: any;
readonly Path: string;
Title: string;
Type: WdStyleSheetLinkType;
}
class StyleSheets {
private 'Word.StyleSheets_typekey': StyleSheets;
private constructor();
Add(FileName: string, LinkType: WdStyleSheetLinkType, Title: string, Precedence: WdStyleSheetPrecedence): StyleSheet;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): StyleSheet;
readonly Parent: any;
}
class Subdocument {
private 'Word.Subdocument_typekey': Subdocument;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly HasFile: boolean;
readonly Level: number;
Locked: boolean;
readonly Name: string;
Open(): Document;
readonly Parent: any;
readonly Path: string;
readonly Range: Range;
Split(Range: Range): void;
}
class Subdocuments {
private 'Word.Subdocuments_typekey': Subdocuments;
private constructor();
AddFromFile(
Name: any, ConfirmConversions?: any, ReadOnly?: any, PasswordDocument?: any, PasswordTemplate?: any, Revert?: any, WritePasswordDocument?: any, WritePasswordTemplate?: any): Subdocument;
AddFromRange(Range: Range): Subdocument;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Delete(): void;
Expanded: boolean;
Item(Index: number): Subdocument;
Merge(FirstSubdocument?: any, LastSubdocument?: any): void;
readonly Parent: any;
Select(): void;
}
class SynonymInfo {
private 'Word.SynonymInfo_typekey': SynonymInfo;
private constructor();
readonly AntonymList: any;
readonly Application: Application;
readonly Creator: number;
readonly Found: boolean;
readonly MeaningCount: number;
readonly MeaningList: any;
readonly Parent: any;
readonly PartOfSpeechList: any;
readonly RelatedExpressionList: any;
readonly RelatedWordList: any;
SynonymList(Meaning: any): any;
readonly Word: string;
}
class System {
private 'Word.System_typekey': System;
private constructor();
readonly Application: Application;
readonly ComputerType: string;
Connect(Path: string, Drive?: any, Password?: any): void;
readonly Country: WdCountry;
readonly CountryRegion: WdCountry;
readonly Creator: number;
Cursor: WdCursorType;
readonly FreeDiskSpace: number;
readonly HorizontalResolution: number;
readonly LanguageDesignation: string;
readonly MacintoshName: string;
readonly MathCoprocessorInstalled: boolean;
MSInfo(): void;
readonly OperatingSystem: string;
readonly Parent: any;
PrivateProfileString(FileName: string, Section: string, Key: string): string;
readonly ProcessorType: string;
ProfileString(Section: string, Key: string): string;
readonly QuickDrawInstalled: boolean;
readonly Version: string;
readonly VerticalResolution: number;
}
class Table {
private 'Word.Table_typekey': Table;
private constructor();
AllowAutoFit: boolean;
AllowPageBreaks: boolean;
readonly Application: Application;
ApplyStyleColumnBands: boolean;
ApplyStyleDirectFormatting(StyleName: string): void;
ApplyStyleFirstColumn: boolean;
ApplyStyleHeadingRows: boolean;
ApplyStyleLastColumn: boolean;
ApplyStyleLastRow: boolean;
ApplyStyleRowBands: boolean;
AutoFitBehavior(Behavior: WdAutoFitBehavior): void;
AutoFormat(
Format?: any, ApplyBorders?: any, ApplyShading?: any, ApplyFont?: any, ApplyColor?: any, ApplyHeadingRows?: any, ApplyLastRow?: any, ApplyFirstColumn?: any,
ApplyLastColumn?: any, AutoFit?: any): void;
readonly AutoFormatType: number;
Borders: Borders;
BottomPadding: number;
Cell(Row: number, Column: number): Cell;
readonly Columns: Columns;
ConvertToText(Separator?: any, NestedTables?: any): Range;
ConvertToTextOld(Separator?: any): Range;
readonly Creator: number;
Delete(): void;
Descr: string;
ID: string;
LeftPadding: number;
readonly NestingLevel: number;
readonly Parent: any;
PreferredWidth: number;
PreferredWidthType: WdPreferredWidthType;
readonly Range: Range;
RightPadding: number;
readonly Rows: Rows;
Select(): void;
readonly Shading: Shading;
Sort(
ExcludeHeader?: any, FieldNumber?: any, SortFieldType?: any, SortOrder?: any, FieldNumber2?: any, SortFieldType2?: any, SortOrder2?: any, FieldNumber3?: any,
SortFieldType3?: any, SortOrder3?: any, CaseSensitive?: any, BidiSort?: any, IgnoreThe?: any, IgnoreKashida?: any, IgnoreDiacritics?: any, IgnoreHe?: any, LanguageID?: any): void;
SortAscending(): void;
SortDescending(): void;
SortOld(
ExcludeHeader?: any, FieldNumber?: any, SortFieldType?: any, SortOrder?: any, FieldNumber2?: any, SortFieldType2?: any, SortOrder2?: any, FieldNumber3?: any,
SortFieldType3?: any, SortOrder3?: any, CaseSensitive?: any, LanguageID?: any): void;
Spacing: number;
Split(BeforeRow: any): Table;
Style: any;
TableDirection: WdTableDirection;
readonly Tables: Tables;
Title: string;
TopPadding: number;
readonly Uniform: boolean;
UpdateAutoFormat(): void;
}
class TableOfAuthorities {
private 'Word.TableOfAuthorities_typekey': TableOfAuthorities;
private constructor();
readonly Application: Application;
Bookmark: string;
Category: number;
readonly Creator: number;
Delete(): void;
EntrySeparator: string;
IncludeCategoryHeader: boolean;
IncludeSequenceName: string;
KeepEntryFormatting: boolean;
PageNumberSeparator: string;
PageRangeSeparator: string;
readonly Parent: any;
Passim: boolean;
readonly Range: Range;
Separator: string;
TabLeader: WdTabLeader;
Update(): void;
}
class TableOfAuthoritiesCategory {
private 'Word.TableOfAuthoritiesCategory_typekey': TableOfAuthoritiesCategory;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Index: number;
Name: string;
readonly Parent: any;
}
class TableOfContents {
private 'Word.TableOfContents_typekey': TableOfContents;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly HeadingStyles: HeadingStyles;
HidePageNumbersInWeb: boolean;
IncludePageNumbers: boolean;
LowerHeadingLevel: number;
readonly Parent: any;
readonly Range: Range;
RightAlignPageNumbers: boolean;
TabLeader: WdTabLeader;
TableID: string;
Update(): void;
UpdatePageNumbers(): void;
UpperHeadingLevel: number;
UseFields: boolean;
UseHeadingStyles: boolean;
UseHyperlinks: boolean;
}
class TableOfFigures {
private 'Word.TableOfFigures_typekey': TableOfFigures;
private constructor();
readonly Application: Application;
Caption: string;
readonly Creator: number;
Delete(): void;
readonly HeadingStyles: HeadingStyles;
HidePageNumbersInWeb: boolean;
IncludeLabel: boolean;
IncludePageNumbers: boolean;
LowerHeadingLevel: number;
readonly Parent: any;
readonly Range: Range;
RightAlignPageNumbers: boolean;
TabLeader: WdTabLeader;
TableID: string;
Update(): void;
UpdatePageNumbers(): void;
UpperHeadingLevel: number;
UseFields: boolean;
UseHeadingStyles: boolean;
UseHyperlinks: boolean;
}
class Tables {
private 'Word.Tables_typekey': Tables;
private constructor();
Add(Range: Range, NumRows: number, NumColumns: number, DefaultTableBehavior?: any, AutoFitBehavior?: any): Table;
AddOld(Range: Range, NumRows: number, NumColumns: number): Table;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Table;
readonly NestingLevel: number;
readonly Parent: any;
}
class TablesOfAuthorities {
private 'Word.TablesOfAuthorities_typekey': TablesOfAuthorities;
private constructor();
Add(
Range: Range, Category?: any, Bookmark?: any, Passim?: any, KeepEntryFormatting?: any, Separator?: any, IncludeSequenceName?: any, EntrySeparator?: any,
PageRangeSeparator?: any, IncludeCategoryHeader?: any, PageNumberSeparator?: any): TableOfAuthorities;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Format: WdToaFormat;
Item(Index: number): TableOfAuthorities;
MarkAllCitations(ShortCitation: string, LongCitation?: any, LongCitationAutoText?: any, Category?: any): void;
MarkCitation(Range: Range, ShortCitation: string, LongCitation?: any, LongCitationAutoText?: any, Category?: any): Field;
NextCitation(ShortCitation: string): void;
readonly Parent: any;
}
class TablesOfAuthoritiesCategories {
private 'Word.TablesOfAuthoritiesCategories_typekey': TablesOfAuthoritiesCategories;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): TableOfAuthoritiesCategory;
readonly Parent: any;
}
class TablesOfContents {
private 'Word.TablesOfContents_typekey': TablesOfContents;
private constructor();
Add(
Range: Range, UseHeadingStyles?: any, UpperHeadingLevel?: any, LowerHeadingLevel?: any, UseFields?: any, TableID?: any, RightAlignPageNumbers?: any,
IncludePageNumbers?: any, AddedStyles?: any, UseHyperlinks?: any, HidePageNumbersInWeb?: any, UseOutlineLevels?: any): TableOfContents;
Add2000(
Range: Range, UseHeadingStyles?: any, UpperHeadingLevel?: any, LowerHeadingLevel?: any, UseFields?: any, TableID?: any, RightAlignPageNumbers?: any,
IncludePageNumbers?: any, AddedStyles?: any, UseHyperlinks?: any, HidePageNumbersInWeb?: any): TableOfContents;
AddOld(
Range: Range, UseHeadingStyles?: any, UpperHeadingLevel?: any, LowerHeadingLevel?: any, UseFields?: any, TableID?: any, RightAlignPageNumbers?: any,
IncludePageNumbers?: any, AddedStyles?: any): TableOfContents;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Format: WdTocFormat;
Item(Index: number): TableOfContents;
MarkEntry(Range: Range, Entry?: any, EntryAutoText?: any, TableID?: any, Level?: any): Field;
readonly Parent: any;
}
class TablesOfFigures {
private 'Word.TablesOfFigures_typekey': TablesOfFigures;
private constructor();
Add(
Range: Range, Caption?: any, IncludeLabel?: any, UseHeadingStyles?: any, UpperHeadingLevel?: any, LowerHeadingLevel?: any, UseFields?: any, TableID?: any,
RightAlignPageNumbers?: any, IncludePageNumbers?: any, AddedStyles?: any, UseHyperlinks?: any, HidePageNumbersInWeb?: any): TableOfFigures;
AddOld(
Range: Range, Caption?: any, IncludeLabel?: any, UseHeadingStyles?: any, UpperHeadingLevel?: any, LowerHeadingLevel?: any, UseFields?: any, TableID?: any,
RightAlignPageNumbers?: any, IncludePageNumbers?: any, AddedStyles?: any): TableOfFigures;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Format: WdTofFormat;
Item(Index: number): TableOfFigures;
MarkEntry(Range: Range, Entry?: any, EntryAutoText?: any, TableID?: any, Level?: any): Field;
readonly Parent: any;
}
class TableStyle {
private 'Word.TableStyle_typekey': TableStyle;
private constructor();
Alignment: WdRowAlignment;
AllowBreakAcrossPage: number;
AllowPageBreaks: boolean;
readonly Application: Application;
Borders: Borders;
BottomPadding: number;
ColumnStripe: number;
Condition(ConditionCode: WdConditionCode): ConditionalStyle;
readonly Creator: number;
LeftIndent: number;
LeftPadding: number;
readonly Parent: any;
RightPadding: number;
RowStripe: number;
readonly Shading: Shading;
Spacing: number;
TableDirection: WdTableDirection;
TopPadding: number;
}
class TabStop {
private 'Word.TabStop_typekey': TabStop;
private constructor();
Alignment: WdTabAlignment;
readonly Application: Application;
Clear(): void;
readonly Creator: number;
readonly CustomTab: boolean;
Leader: WdTabLeader;
readonly Next: TabStop;
readonly Parent: any;
Position: number;
readonly Previous: TabStop;
}
class TabStops {
private 'Word.TabStops_typekey': TabStops;
private constructor();
Add(Position: number, Alignment?: any, Leader?: any): TabStop;
After(Position: number): TabStop;
readonly Application: Application;
Before(Position: number): TabStop;
ClearAll(): void;
readonly Count: number;
readonly Creator: number;
Item(Index: any): TabStop;
readonly Parent: any;
}
class Task {
private 'Word.Task_typekey': Task;
private constructor();
Activate(Wait?: any): void;
readonly Application: Application;
Close(): void;
readonly Creator: number;
Height: number;
Left: number;
Move(Left: number, Top: number): void;
readonly Name: string;
readonly Parent: any;
Resize(Width: number, Height: number): void;
SendWindowMessage(Message: number, wParam: number, lParam: number): void;
Top: number;
Visible: boolean;
Width: number;
WindowState: WdWindowState;
}
class TaskPane {
private 'Word.TaskPane_typekey': TaskPane;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Parent: any;
Visible: boolean;
}
class TaskPanes {
private 'Word.TaskPanes_typekey': TaskPanes;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: WdTaskPanes): TaskPane;
readonly Parent: any;
}
class Tasks {
private 'Word.Tasks_typekey': Tasks;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Exists(Name: string): boolean;
ExitWindows(): void;
Item(Index: any): Task;
readonly Parent: any;
}
class Template {
private 'Word.Template_typekey': Template;
private constructor();
readonly Application: Application;
readonly AutoTextEntries: AutoTextEntries;
readonly BuildingBlockEntries: BuildingBlockEntries;
readonly BuildingBlockTypes: BuildingBlockTypes;
readonly BuiltInDocumentProperties: Office.DocumentProperties<Application>;
readonly Creator: number;
readonly CustomDocumentProperties: Office.DocumentProperties<Application>;
FarEastLineBreakLanguage: WdFarEastLineBreakLanguageID;
FarEastLineBreakLevel: WdFarEastLineBreakLevel;
readonly FullName: string;
JustificationMode: WdJustificationMode;
KerningByAlgorithm: boolean;
LanguageID: WdLanguageID;
LanguageIDFarEast: WdLanguageID;
readonly ListTemplates: ListTemplates;
readonly Name: string;
NoLineBreakAfter: string;
NoLineBreakBefore: string;
NoProofing: number;
OpenAsDocument(): Document;
readonly Parent: any;
readonly Path: string;
Save(): void;
Saved: boolean;
readonly Type: WdTemplateType;
readonly VBProject: VBIDE.VBProject;
}
class Templates {
private 'Word.Templates_typekey': Templates;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Template;
LoadBuildingBlocks(): void;
readonly Parent: any;
}
class TextColumn {
private 'Word.TextColumn_typekey': TextColumn;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Parent: any;
SpaceAfter: number;
Width: number;
}
class TextColumns {
private 'Word.TextColumns_typekey': TextColumns;
private constructor();
Add(Width?: any, Spacing?: any, EvenlySpaced?: any): TextColumn;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
EvenlySpaced: number;
FlowDirection: WdFlowDirection;
Item(Index: number): TextColumn;
LineBetween: number;
readonly Parent: any;
SetCount(NumColumns: number): void;
Spacing: number;
Width: number;
}
class TextEffectFormat {
private 'Word.TextEffectFormat_typekey': TextEffectFormat;
private constructor();
Alignment: Office.MsoTextEffectAlignment;
readonly Application: Application;
readonly Creator: number;
FontBold: Office.MsoTriState;
FontItalic: Office.MsoTriState;
FontName: string;
FontSize: number;
KernedPairs: Office.MsoTriState;
NormalizedHeight: Office.MsoTriState;
readonly Parent: any;
PresetShape: Office.MsoPresetTextEffectShape;
PresetTextEffect: Office.MsoPresetTextEffect;
RotatedChars: Office.MsoTriState;
Text: string;
ToggleVerticalText(): void;
Tracking: number;
}
class TextFrame {
private 'Word.TextFrame_typekey': TextFrame;
private constructor();
readonly Application: Application;
AutoSize: number;
BreakForwardLink(): void;
readonly Column: Office.TextColumn2;
readonly ContainingRange: Range;
readonly Creator: number;
DeleteText(): void;
readonly HasText: number;
HorizontalAnchor: Office.MsoHorizontalAnchor;
MarginBottom: number;
MarginLeft: number;
MarginRight: number;
MarginTop: number;
Next: TextFrame;
NoTextRotation: Office.MsoTriState;
Orientation: Office.MsoTextOrientation;
readonly Overflowing: boolean;
readonly Parent: Shape;
PathFormat: Office.MsoPathFormat;
Previous: TextFrame;
readonly TextRange: Range;
readonly ThreeD: ThreeDFormat;
ValidLinkTarget(TargetTextFrame: TextFrame): boolean;
VerticalAnchor: Office.MsoVerticalAnchor;
WarpFormat: Office.MsoWarpFormat;
WordWrap: number;
}
class TextInput {
private 'Word.TextInput_typekey': TextInput;
private constructor();
readonly Application: Application;
Clear(): void;
readonly Creator: number;
Default: string;
EditType(Type: WdTextFormFieldType, Default?: any, Format?: any, Enabled?: any): void;
readonly Format: string;
readonly Parent: any;
readonly Type: WdTextFormFieldType;
readonly Valid: boolean;
Width: number;
}
class TextRetrievalMode {
private 'Word.TextRetrievalMode_typekey': TextRetrievalMode;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly Duplicate: TextRetrievalMode;
IncludeFieldCodes: boolean;
IncludeHiddenText: boolean;
readonly Parent: any;
ViewType: WdViewType;
}
class ThreeDFormat {
private 'Word.ThreeDFormat_typekey': ThreeDFormat;
private constructor();
readonly Application: Application;
BevelBottomDepth: number;
BevelBottomInset: number;
BevelBottomType: Office.MsoBevelType;
BevelTopDepth: number;
BevelTopInset: number;
BevelTopType: Office.MsoBevelType;
readonly ContourColor: ColorFormat;
ContourWidth: number;
readonly Creator: number;
Depth: number;
readonly ExtrusionColor: ColorFormat;
ExtrusionColorType: Office.MsoExtrusionColorType;
FieldOfView: number;
IncrementRotationHorizontal(Increment: number): void;
IncrementRotationVertical(Increment: number): void;
IncrementRotationX(Increment: number): void;
IncrementRotationY(Increment: number): void;
IncrementRotationZ(Increment: number): void;
LightAngle: number;
readonly Parent: any;
Perspective: Office.MsoTriState;
readonly PresetCamera: Office.MsoPresetCamera;
readonly PresetExtrusionDirection: Office.MsoPresetExtrusionDirection;
PresetLighting: Office.MsoLightRigType;
PresetLightingDirection: Office.MsoPresetLightingDirection;
PresetLightingSoftness: Office.MsoPresetLightingSoftness;
PresetMaterial: Office.MsoPresetMaterial;
readonly PresetThreeDFormat: Office.MsoPresetThreeDFormat;
ProjectText: Office.MsoTriState;
ResetRotation(): void;
RotationX: number;
RotationY: number;
RotationZ: number;
SetExtrusionDirection(PresetExtrusionDirection: Office.MsoPresetExtrusionDirection): void;
SetPresetCamera(PresetCamera: Office.MsoPresetCamera): void;
SetThreeDFormat(PresetThreeDFormat: Office.MsoPresetThreeDFormat): void;
Visible: Office.MsoTriState;
Z: number;
}
class TickLabels {
private 'Word.TickLabels_typekey': TickLabels;
private constructor();
Alignment: number;
readonly Application: any;
AutoScaleFont: any;
readonly Creator: number;
Delete(): any;
readonly Depth: number;
readonly Font: ChartFont;
readonly Format: ChartFormat;
MultiLevel: boolean;
readonly Name: string;
NumberFormat: string;
NumberFormatLinked: boolean;
NumberFormatLocal: any;
Offset: number;
Orientation: XlTickLabelOrientation;
readonly Parent: any;
ReadingOrder: number;
Select(): any;
}
class TwoInitialCapsException {
private 'Word.TwoInitialCapsException_typekey': TwoInitialCapsException;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
}
class TwoInitialCapsExceptions {
private 'Word.TwoInitialCapsExceptions_typekey': TwoInitialCapsExceptions;
private constructor();
Add(Name: string): TwoInitialCapsException;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): TwoInitialCapsException;
readonly Parent: any;
}
class UndoRecord {
private 'Word.UndoRecord_typekey': UndoRecord;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly CustomRecordLevel: number;
readonly CustomRecordName: string;
EndCustomRecord(): void;
readonly IsRecordingCustomRecord: boolean;
readonly Parent: any;
/** @param string [Name=''] */
StartCustomRecord(Name?: string): void;
}
class UpBars {
private 'Word.UpBars_typekey': UpBars;
private constructor();
readonly Application: any;
readonly Border: ChartBorder;
readonly Creator: number;
Delete(): any;
readonly Fill: ChartFillFormat;
readonly Format: ChartFormat;
readonly Interior: Interior;
readonly Name: string;
readonly Parent: any;
Select(): any;
}
class Variable {
private 'Word.Variable_typekey': Variable;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Index: number;
readonly Name: string;
readonly Parent: any;
Value: string;
}
class Variables {
private 'Word.Variables_typekey': Variables;
private constructor();
Add(Name: string, Value?: any): Variable;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number | string): Variable;
readonly Parent: any;
}
class Version {
private 'Word.Version_typekey': Version;
private constructor();
readonly Application: Application;
readonly Comment: string;
readonly Creator: number;
readonly Date: VarDate;
Delete(): void;
readonly Index: number;
Open(): Document;
OpenOld(): void;
readonly Parent: any;
readonly SavedBy: string;
}
class Versions {
private 'Word.Versions_typekey': Versions;
private constructor();
readonly Application: Application;
AutoVersion: WdAutoVersions;
readonly Count: number;
readonly Creator: number;
Item(Index: number): Version;
readonly Parent: any;
Save(Comment?: any): void;
}
class View {
private 'Word.View_typekey': View;
private constructor();
readonly Application: Application;
BrowseToWindow: number;
CollapseOutline(Range?: any): void;
ConflictMode: boolean;
readonly Creator: number;
DisplayBackgrounds: boolean;
DisplayPageBoundaries: boolean;
DisplaySmartTags: boolean;
Draft: boolean;
EnlargeFontsLessThan: number;
ExpandOutline(Range?: any): void;
FieldShading: WdFieldShading;
FullScreen: boolean;
Magnifier: boolean;
MailMergeDataView: boolean;
MarkupMode: WdRevisionsMode;
NextHeaderFooter(): void;
Panning: boolean;
readonly Parent: any;
PreviousHeaderFooter(): void;
ReadingLayout: boolean;
ReadingLayoutActualView: boolean;
ReadingLayoutAllowEditing: boolean;
ReadingLayoutAllowMultiplePages: boolean;
ReadingLayoutTruncateMargins: WdReadingLayoutMargin;
readonly Reviewers: Reviewers;
RevisionsBalloonShowConnectingLines: boolean;
RevisionsBalloonSide: WdRevisionsBalloonMargin;
RevisionsBalloonWidth: number;
RevisionsBalloonWidthType: WdRevisionsBalloonWidthType;
RevisionsMode: WdRevisionsMode;
RevisionsView: WdRevisionsView;
SeekView: WdSeekView;
ShadeEditableRanges: number;
ShowAll: boolean;
ShowAllHeadings(): void;
ShowAnimation: boolean;
ShowBookmarks: boolean;
ShowComments: boolean;
ShowCropMarks: boolean;
ShowDrawings: boolean;
ShowFieldCodes: boolean;
ShowFirstLineOnly: boolean;
ShowFormat: boolean;
ShowFormatChanges: boolean;
ShowHeading(Level: number): void;
ShowHiddenText: boolean;
ShowHighlight: boolean;
ShowHyphens: boolean;
ShowInkAnnotations: boolean;
ShowInsertionsAndDeletions: boolean;
ShowMainTextLayer: boolean;
ShowMarkupAreaHighlight: boolean;
ShowObjectAnchors: boolean;
ShowOptionalBreaks: boolean;
ShowOtherAuthors: boolean;
ShowParagraphs: boolean;
ShowPicturePlaceHolders: boolean;
ShowRevisionsAndComments: boolean;
ShowSpaces: boolean;
ShowTabs: boolean;
ShowTextBoundaries: boolean;
ShowXMLMarkup: number;
SplitSpecial: WdSpecialPane;
TableGridlines: boolean;
Type: WdViewType;
WrapToWindow: boolean;
readonly Zoom: Zoom;
}
class Walls {
private 'Word.Walls_typekey': Walls;
private constructor();
readonly Application: any;
readonly Border: ChartBorder;
ClearFormats(): any;
readonly Creator: number;
readonly Fill: ChartFillFormat;
readonly Format: ChartFormat;
readonly Interior: Interior;
readonly Name: string;
readonly Parent: any;
Paste(): void;
PictureType: any;
PictureUnit: any;
Select(): any;
Thickness: number;
}
class WebOptions {
private 'Word.WebOptions_typekey': WebOptions;
private constructor();
AllowPNG: boolean;
readonly Application: Application;
BrowserLevel: WdBrowserLevel;
readonly Creator: number;
Encoding: Office.MsoEncoding;
readonly FolderSuffix: string;
OptimizeForBrowser: boolean;
OrganizeInFolder: boolean;
readonly Parent: any;
PixelsPerInch: number;
RelyOnCSS: boolean;
RelyOnVML: boolean;
ScreenSize: Office.MsoScreenSize;
TargetBrowser: Office.MsoTargetBrowser;
UseDefaultFolderSuffix(): void;
UseLongFileNames: boolean;
}
class Window {
private 'Word.Window_typekey': Window;
private constructor();
Activate(): void;
readonly Active: boolean;
readonly ActivePane: Pane;
readonly Application: Application;
Caption: string;
Close(SaveChanges?: any, RouteDocument?: any): void;
readonly Creator: number;
DisplayHorizontalScrollBar: boolean;
DisplayLeftScrollBar: boolean;
DisplayRightRuler: boolean;
DisplayRulers: boolean;
DisplayScreenTips: boolean;
DisplayVerticalRuler: boolean;
DisplayVerticalScrollBar: boolean;
readonly Document: Document;
DocumentMap: boolean;
DocumentMapPercentWidth: number;
EnvelopeVisible: boolean;
GetPoint(ScreenPixelsLeft: number, ScreenPixelsTop: number, ScreenPixelsWidth: number, ScreenPixelsHeight: number, obj: any): void;
Height: number;
HorizontalPercentScrolled: number;
IMEMode: WdIMEMode;
readonly Index: number;
LargeScroll(Down?: any, Up?: any, ToRight?: any, ToLeft?: any): void;
Left: number;
NewWindow(): Window;
readonly Next: Window;
PageScroll(Down?: any, Up?: any): void;
readonly Panes: Panes;
readonly Parent: any;
readonly Previous: Window;
PrintOut(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any, PrintZoomColumn?: any, PrintZoomRow?: any, PrintZoomPaperWidth?: any,
PrintZoomPaperHeight?: any): void;
PrintOut2000(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any, PrintZoomColumn?: any, PrintZoomRow?: any, PrintZoomPaperWidth?: any,
PrintZoomPaperHeight?: any): void;
PrintOutOld(
Background?: any, Append?: any, Range?: any, OutputFileName?: any, From?: any, To?: any, Item?: any, Copies?: any, Pages?: any, PageType?: any,
PrintToFile?: any, Collate?: any, ActivePrinterMacGX?: any, ManualDuplexPrint?: any): void;
RangeFromPoint(x: number, y: number): any;
ScrollIntoView(obj: any, Start?: any): void;
readonly Selection: Selection;
SetFocus(): void;
ShowSourceDocuments: WdShowSourceDocuments;
SmallScroll(Down?: any, Up?: any, ToRight?: any, ToLeft?: any): void;
Split: boolean;
SplitVertical: number;
StyleAreaWidth: number;
Thumbnails: boolean;
ToggleRibbon(): void;
ToggleShowAllReviewers(): void;
Top: number;
readonly Type: WdWindowType;
readonly UsableHeight: number;
readonly UsableWidth: number;
VerticalPercentScrolled: number;
readonly View: View;
Visible: boolean;
Width: number;
readonly WindowNumber: number;
WindowState: WdWindowState;
}
class Windows {
private 'Word.Windows_typekey': Windows;
private constructor();
Add(Window?: any): Window;
readonly Application: Application;
Arrange(ArrangeStyle?: any): void;
BreakSideBySide(): boolean;
CompareSideBySideWith(Document: any): boolean;
readonly Count: number;
readonly Creator: number;
Item(Index: any): Window;
readonly Parent: any;
ResetPositionsSideBySide(): void;
SyncScrollingSideBySide: boolean;
}
class Words {
private 'Word.Words_typekey': Words;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
readonly First: Range;
Item(Index: number): Range;
readonly Last: Range;
readonly Parent: any;
}
class WrapFormat {
private 'Word.WrapFormat_typekey': WrapFormat;
private constructor();
AllowOverlap: number;
readonly Application: Application;
readonly Creator: number;
DistanceBottom: number;
DistanceLeft: number;
DistanceRight: number;
DistanceTop: number;
readonly Parent: any;
Side: WdWrapSideType;
Type: WdWrapType;
}
class XMLChildNodeSuggestion {
private 'Word.XMLChildNodeSuggestion_typekey': XMLChildNodeSuggestion;
private constructor();
readonly Application: Application;
readonly BaseName: string;
readonly Creator: number;
Insert(Range?: any): XMLNode;
readonly NamespaceURI: string;
readonly Parent: any;
readonly XMLSchemaReference: XMLSchemaReference;
}
class XMLChildNodeSuggestions {
private 'Word.XMLChildNodeSuggestions_typekey': XMLChildNodeSuggestions;
private constructor();
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): XMLChildNodeSuggestion;
readonly Parent: any;
}
class XMLMapping {
private 'Word.XMLMapping_typekey': XMLMapping;
private constructor();
readonly Application: Application;
readonly Creator: number;
readonly CustomXMLNode: Office.CustomXMLNode;
readonly CustomXMLPart: Office.CustomXMLPart;
Delete(): void;
readonly IsMapped: boolean;
readonly Parent: any;
readonly PrefixMappings: string;
/**
* @param string [PrefixMapping='']
* @param Office.CustomXMLPart [Source=0]
*/
SetMapping(XPath: string, PrefixMapping?: string, Source?: Office.CustomXMLPart): boolean;
SetMappingByNode(Node: Office.CustomXMLNode): boolean;
readonly XPath: string;
}
class XMLNamespace {
private 'Word.XMLNamespace_typekey': XMLNamespace;
private constructor();
/** @param boolean [AllUsers=false] */
Alias(AllUsers?: boolean): string;
readonly Application: Application;
AttachToDocument(Document: any): void;
readonly Creator: number;
/** @param boolean [AllUsers=false] */
DefaultTransform(AllUsers?: boolean): XSLTransform;
Delete(): void;
/** @param boolean [AllUsers=false] */
Location(AllUsers?: boolean): string;
readonly Parent: any;
readonly URI: string;
readonly XSLTransforms: XSLTransforms;
}
class XMLNamespaces {
private 'Word.XMLNamespaces_typekey': XMLNamespaces;
private constructor();
/** @param boolean [InstallForAllUsers=false] */
Add(Path: string, NamespaceURI: any, Alias: any, InstallForAllUsers?: boolean): XMLNamespace;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
/** @param boolean [InstallForAllUsers=false] */
InstallManifest(Path: string, InstallForAllUsers?: boolean): void;
Item(Index: any): XMLNamespace;
readonly Parent: any;
}
class XMLNode {
private 'Word.XMLNode_typekey': XMLNode;
private constructor();
readonly Application: Application;
readonly Attributes: XMLNodes;
readonly BaseName: string;
readonly ChildNodes: XMLNodes;
readonly ChildNodeSuggestions: XMLChildNodeSuggestions;
Copy(): void;
readonly Creator: number;
Cut(): void;
Delete(): void;
readonly FirstChild: XMLNode;
readonly HasChildNodes: boolean;
readonly LastChild: XMLNode;
readonly Level: WdXMLNodeLevel;
readonly NamespaceURI: string;
readonly NextSibling: XMLNode;
readonly NodeType: WdXMLNodeType;
NodeValue: string;
readonly OwnerDocument: Document;
readonly Parent: any;
readonly ParentNode: XMLNode;
PlaceholderText: string;
readonly PreviousSibling: XMLNode;
readonly Range: Range;
RemoveChild(ChildElement: XMLNode): void;
/**
* @param string [PrefixMapping='']
* @param boolean [FastSearchSkippingTextNodes=true]
*/
SelectNodes(XPath: string, PrefixMapping?: string, FastSearchSkippingTextNodes?: boolean): XMLNodes;
/**
* @param string [PrefixMapping='']
* @param boolean [FastSearchSkippingTextNodes=true]
*/
SelectSingleNode(XPath: string, PrefixMapping?: string, FastSearchSkippingTextNodes?: boolean): XMLNode;
/** @param boolean [ClearedAutomatically=true] */
SetValidationError(Status: WdXMLValidationStatus, ErrorText: any, ClearedAutomatically?: boolean): void;
readonly SmartTag: SmartTag;
Text: string;
Validate(): void;
/** @param boolean [Advanced=false] */
ValidationErrorText(Advanced?: boolean): string;
readonly ValidationStatus: WdXMLValidationStatus;
readonly WordOpenXML: string;
/** @param boolean [DataOnly=false] */
XML(DataOnly?: boolean): string;
}
class XMLNodes {
private 'Word.XMLNodes_typekey': XMLNodes;
private constructor();
Add(Name: string, Namespace: string, Range?: any): XMLNode;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: number): XMLNode;
readonly Parent: any;
}
class XMLSchemaReference {
private 'Word.XMLSchemaReference_typekey': XMLSchemaReference;
private constructor();
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly Location: string;
readonly NamespaceURI: string;
readonly Parent: any;
Reload(): void;
}
class XMLSchemaReferences {
private 'Word.XMLSchemaReferences_typekey': XMLSchemaReferences;
private constructor();
/** @param boolean [InstallForAllUsers=false] */
Add(NamespaceURI: any, Alias: any, FileName: any, InstallForAllUsers?: boolean): XMLSchemaReference;
AllowSaveAsXMLWithoutValidation: boolean;
readonly Application: Application;
AutomaticValidation: boolean;
readonly Count: number;
readonly Creator: number;
HideValidationErrors: boolean;
IgnoreMixedContent: boolean;
Item(Index: any): XMLSchemaReference;
readonly Parent: any;
ShowPlaceholderText: boolean;
Validate(): void;
}
class XSLTransform {
private 'Word.XSLTransform_typekey': XSLTransform;
private constructor();
/** @param boolean [AllUsers=false] */
Alias(AllUsers?: boolean): string;
readonly Application: Application;
readonly Creator: number;
Delete(): void;
readonly ID: string;
/** @param boolean [AllUsers=false] */
Location(AllUsers?: boolean): string;
readonly Parent: any;
}
class XSLTransforms {
private 'Word.XSLTransforms_typekey': XSLTransforms;
private constructor();
/** @param boolean [InstallForAllUsers=false] */
Add(Location: string, Alias: any, InstallForAllUsers?: boolean): XSLTransform;
readonly Application: Application;
readonly Count: number;
readonly Creator: number;
Item(Index: any): XSLTransform;
readonly Parent: any;
}
class Zoom {
private 'Word.Zoom_typekey': Zoom;
private constructor();
readonly Application: Application;
readonly Creator: number;
PageColumns: number;
PageFit: WdPageFit;
PageRows: number;
readonly Parent: any;
Percentage: number;
}
class Zooms {
private 'Word.Zooms_typekey': Zooms;
private constructor();
readonly Application: Application;
readonly Creator: number;
Item(Index: WdViewType): Zoom;
readonly Parent: any;
}
namespace EventHelperTypes {
type Application_EPostageInsertEx_ArgNames = ['Doc', 'cpDeliveryAddrStart', 'cpDeliveryAddrEnd', 'cpReturnAddrStart', 'cpReturnAddrEnd', 'xaWidth', 'yaHeight', 'bstrPrinterName',
'bstrPaperFeed', 'fPrint', 'fCancel'];
type Application_Invoke_ArgNames = ['dispidMember', 'riid', 'lcid', 'wFlags', 'pdispparams', 'pvarResult', 'pexcepinfo', 'puArgErr'];
interface Application_EPostageInsertEx_Parameter {
readonly bstrPaperFeed: string;
readonly bstrPrinterName: string;
readonly cpDeliveryAddrEnd: number;
readonly cpDeliveryAddrStart: number;
readonly cpReturnAddrEnd: number;
readonly cpReturnAddrStart: number;
readonly Doc: Document;
fCancel: boolean;
readonly fPrint: boolean;
readonly xaWidth: number;
readonly yaHeight: number;
}
interface Application_Invoke_Parameter {
readonly dispidMember: number;
readonly lcid: number;
readonly pdispparams: stdole.DISPPARAMS;
pexcepinfo: stdole.EXCEPINFO;
puArgErr: number;
pvarResult: any;
readonly riid: stdole.GUID;
readonly wFlags: number;
}
}
}
interface ActiveXObject {
on(
obj: Word.Application, event: 'DocumentBeforeClose' | 'DocumentBeforePrint' | 'MailMergeBeforeRecordMerge', argNames: ['Doc', 'Cancel'],
handler: (this: Word.Application, parameter: {readonly Doc: Word.Document, Cancel: boolean}) => void): void;
on(
obj: Word.Application, event: 'DocumentBeforeSave', argNames: ['Doc', 'SaveAsUI', 'Cancel'], handler: (
this: Word.Application, parameter: {readonly Doc: Word.Document, readonly SaveAsUI: boolean, Cancel: boolean}) => void): void;
on(
obj: Word.Application, event: 'DocumentOpen' | 'EPostageInsert' | 'EPostagePropertyDialog' | 'MailMergeAfterRecordMerge' | 'MailMergeDataSourceLoad' |
'MailMergeWizardSendToCustom' | 'NewDocument',
argNames: ['Doc'], handler: (this: Word.Application, parameter: {readonly Doc: Word.Document}) => void): void;
on(
obj: Word.Application, event: 'DocumentSync', argNames: ['Doc', 'SyncEventType'], handler: (
this: Word.Application, parameter: {readonly Doc: Word.Document, readonly SyncEventType: Office.MsoSyncEventType}) => void): void;
on(
obj: Word.Application, event: 'EPostageInsertEx', argNames: Word.EventHelperTypes.Application_EPostageInsertEx_ArgNames, handler: (
this: Word.Application, parameter: Word.EventHelperTypes.Application_EPostageInsertEx_Parameter) => void): void;
on(
obj: Word.Application, event: 'GetIDsOfNames', argNames: ['riid', 'rgszNames', 'cNames', 'lcid', 'rgdispid'], handler: (
this: Word.Application, parameter: {readonly riid: stdole.GUID, readonly rgszNames: number, readonly cNames: number, readonly lcid: number, rgdispid: number}) => void): void;
on(
obj: Word.Application, event: 'GetTypeInfo', argNames: ['itinfo', 'lcid', 'pptinfo'], handler: (
this: Word.Application, parameter: {readonly itinfo: number, readonly lcid: number, pptinfo: undefined}) => void): void;
on(obj: Word.Application, event: 'GetTypeInfoCount', argNames: ['pctinfo'], handler: (this: Word.Application, parameter: {pctinfo: number}) => void): void;
on(
obj: Word.Application, event: 'Invoke', argNames: Word.EventHelperTypes.Application_Invoke_ArgNames, handler: (
this: Word.Application, parameter: Word.EventHelperTypes.Application_Invoke_Parameter) => void): void;
on(
obj: Word.Application, event: 'MailMergeAfterMerge', argNames: ['Doc', 'DocResult'], handler: (
this: Word.Application, parameter: {readonly Doc: Word.Document, readonly DocResult: Word.Document}) => void): void;
on(
obj: Word.Application, event: 'MailMergeBeforeMerge', argNames: ['Doc', 'StartRecord', 'EndRecord', 'Cancel'], handler: (
this: Word.Application, parameter: {readonly Doc: Word.Document, readonly StartRecord: number, readonly EndRecord: number, Cancel: boolean}) => void): void;
on(
obj: Word.Application, event: 'MailMergeDataSourceValidate', argNames: ['Doc', 'Handled'], handler: (
this: Word.Application, parameter: {readonly Doc: Word.Document, readonly Handled: boolean}) => void): void;
on(
obj: Word.Application, event: 'MailMergeDataSourceValidate2', argNames: ['Doc', 'Handled'], handler: (
this: Word.Application, parameter: {readonly Doc: Word.Document, Handled: boolean}) => void): void;
on(
obj: Word.Application, event: 'MailMergeWizardStateChange', argNames: ['Doc', 'FromState', 'ToState', 'Handled'], handler: (
this: Word.Application, parameter: {readonly Doc: Word.Document, readonly FromState: number, readonly ToState: number, readonly Handled: boolean}) => void): void;
on(
obj: Word.Application, event: 'ProtectedViewWindowActivate' | 'ProtectedViewWindowDeactivate' | 'ProtectedViewWindowOpen' | 'ProtectedViewWindowSize',
argNames: ['PvWindow'], handler: (this: Word.Application, parameter: {readonly PvWindow: Word.ProtectedViewWindow}) => void): void;
on(
obj: Word.Application, event: 'ProtectedViewWindowBeforeClose', argNames: ['PvWindow', 'CloseReason', 'Cancel'], handler: (
this: Word.Application, parameter: {readonly PvWindow: Word.ProtectedViewWindow, readonly CloseReason: number, Cancel: boolean}) => void): void;
on(
obj: Word.Application, event: 'ProtectedViewWindowBeforeEdit', argNames: ['PvWindow', 'Cancel'], handler: (
this: Word.Application, parameter: {readonly PvWindow: Word.ProtectedViewWindow, Cancel: boolean}) => void): void;
on(obj: Word.Application, event: 'QueryInterface', argNames: ['riid', 'ppvObj'], handler: (this: Word.Application, parameter: {readonly riid: stdole.GUID, ppvObj: undefined}) => void): void;
on(
obj: Word.Application, event: 'WindowActivate' | 'WindowDeactivate' | 'WindowSize', argNames: ['Doc', 'Wn'], handler: (
this: Word.Application, parameter: {readonly Doc: Word.Document, readonly Wn: Word.Window}) => void): void;
on(
obj: Word.Application, event: 'WindowBeforeDoubleClick' | 'WindowBeforeRightClick', argNames: ['Sel', 'Cancel'], handler: (
this: Word.Application, parameter: {readonly Sel: Word.Selection, Cancel: boolean}) => void): void;
on(obj: Word.Application, event: 'WindowSelectionChange', argNames: ['Sel'], handler: (this: Word.Application, parameter: {readonly Sel: Word.Selection}) => void): void;
on(
obj: Word.Application, event: 'XMLSelectionChange', argNames: ['Sel', 'OldXMLNode', 'NewXMLNode', 'Reason'], handler: (
this: Word.Application, parameter: {readonly Sel: Word.Selection, readonly OldXMLNode: Word.XMLNode, readonly NewXMLNode: Word.XMLNode, readonly Reason: number}) => void): void;
on(obj: Word.Application, event: 'XMLValidationError', argNames: ['XMLNode'], handler: (this: Word.Application, parameter: {readonly XMLNode: Word.XMLNode}) => void): void;
on(
obj: Word.Document, event: 'BuildingBlockInsert', argNames: ['Range', 'Name', 'Category', 'BlockType', 'Template'], handler: (
this: Word.Document, parameter: {readonly Range: Word.Range, readonly Name: string, readonly Category: string, readonly BlockType: string, readonly Template: string}) => void): void;
on(
obj: Word.Document, event: 'ContentControlAfterAdd', argNames: ['NewContentControl', 'InUndoRedo'], handler: (
this: Word.Document, parameter: {readonly NewContentControl: Word.ContentControl, readonly InUndoRedo: boolean}) => void): void;
on(
obj: Word.Document, event: 'ContentControlBeforeContentUpdate' | 'ContentControlBeforeStoreUpdate', argNames: ['ContentControl', 'Content'],
handler: (this: Word.Document, parameter: {readonly ContentControl: Word.ContentControl, Content: string}) => void): void;
on(
obj: Word.Document, event: 'ContentControlBeforeDelete', argNames: ['OldContentControl', 'InUndoRedo'], handler: (
this: Word.Document, parameter: {readonly OldContentControl: Word.ContentControl, readonly InUndoRedo: boolean}) => void): void;
on(obj: Word.Document, event: 'ContentControlOnEnter', argNames: ['ContentControl'], handler: (this: Word.Document, parameter: {readonly ContentControl: Word.ContentControl}) => void): void;
on(
obj: Word.Document, event: 'ContentControlOnExit', argNames: ['ContentControl', 'Cancel'], handler: (
this: Word.Document, parameter: {readonly ContentControl: Word.ContentControl, Cancel: boolean}) => void): void;
on(obj: Word.Document, event: 'Sync', argNames: ['SyncEventType'], handler: (this: Word.Document, parameter: {readonly SyncEventType: Office.MsoSyncEventType}) => void): void;
on(
obj: Word.Document, event: 'XMLAfterInsert', argNames: ['NewXMLNode', 'InUndoRedo'], handler: (
this: Word.Document, parameter: {readonly NewXMLNode: Word.XMLNode, readonly InUndoRedo: boolean}) => void): void;
on(
obj: Word.Document, event: 'XMLBeforeDelete', argNames: ['DeletedRange', 'OldXMLNode', 'InUndoRedo'], handler: (
this: Word.Document, parameter: {readonly DeletedRange: Word.Range, readonly OldXMLNode: Word.XMLNode, readonly InUndoRedo: boolean}) => void): void;
on(obj: Word.Application, event: 'AddRef' | 'DocumentChange' | 'Quit' | 'Release' | 'Startup', handler: (this: Word.Application, parameter: {}) => void): void;
on(obj: Word.Document, event: 'Close' | 'New' | 'Open', handler: (this: Word.Document, parameter: {}) => void): void;
on(obj: Word.OLEControl, event: 'GotFocus' | 'LostFocus', handler: (this: Word.OLEControl, parameter: {}) => void): void;
set(obj: Word.Document, propertyName: 'ActiveWritingStyle', parameterTypes: [any], newValue: string): void;
set(obj: Word.Document, propertyName: 'Compatibility', parameterTypes: [Word.WdCompatibility], newValue: boolean): void;
set(obj: Word.System, propertyName: 'PrivateProfileString', parameterTypes: [string, string, string], newValue: string): void;
}
interface ActiveXObjectNameMap {
'Word.Application': Word.Application;
'Word.Document': Word.Document;
}
interface EnumeratorConstructor {
new(col: Word.AddIns): Enumerator<Word.AddIn>;
new(col: Word.AutoCaptions): Enumerator<Word.AutoCaption>;
new(col: Word.AutoCorrectEntries): Enumerator<Word.AutoCorrectEntry>;
new(col: Word.AutoTextEntries): Enumerator<Word.AutoTextEntry>;
new(col: Word.Bookmarks): Enumerator<Word.Bookmark>;
new(col: Word.Borders): Enumerator<Word.Border>;
new(col: Word.Breaks): Enumerator<Word.Break>;
new(col: Word.CanvasShapes | Word.GroupShapes | Word.ShapeRange | Word.Shapes): Enumerator<Word.Shape>;
new(col: Word.CaptionLabels): Enumerator<Word.CaptionLabel>;
new(col: Word.Cells): Enumerator<Word.Cell>;
new(col: Word.Characters | Word.ProofreadingErrors | Word.Sentences | Word.StoryRanges | Word.Words): Enumerator<Word.Range>;
new(col: Word.CoAuthLocks): Enumerator<Word.CoAuthLock>;
new(col: Word.CoAuthors): Enumerator<Word.CoAuthor>;
new(col: Word.CoAuthUpdates): Enumerator<Word.CoAuthUpdate>;
new(col: Word.Columns): Enumerator<Word.Column>;
new(col: Word.Comments): Enumerator<Word.Comment>;
new(col: Word.Conflicts): Enumerator<Word.Conflict>;
new(col: Word.ContentControlListEntries): Enumerator<Word.ContentControlListEntry>;
new(col: Word.ContentControls): Enumerator<Word.ContentControl>;
new(col: Word.CustomLabels): Enumerator<Word.CustomLabel>;
new(col: Word.CustomProperties): Enumerator<Word.CustomProperty>;
new(col: Word.DiagramNodeChildren | Word.DiagramNodes): Enumerator<Word.DiagramNode>;
new(col: Word.Dialogs): Enumerator<Word.Dialog>;
new(col: Word.Dictionaries | Word.HangulHanjaConversionDictionaries): Enumerator<Word.Dictionary>;
new(col: Word.Documents): Enumerator<Word.Document>;
new(col: Word.EmailSignatureEntries): Enumerator<Word.EmailSignatureEntry>;
new(col: Word.Endnotes): Enumerator<Word.Endnote>;
new(col: Word.Fields): Enumerator<Word.Field>;
new(col: Word.FileConverters): Enumerator<Word.FileConverter>;
new(col: Word.FirstLetterExceptions): Enumerator<Word.FirstLetterException>;
new(col: Word.FontNames): Enumerator<string>;
new(col: Word.Footnotes): Enumerator<Word.Footnote>;
new(col: Word.FormFields): Enumerator<Word.FormField>;
new(col: Word.Frames): Enumerator<Word.Frame>;
new(col: Word.HangulAndAlphabetExceptions): Enumerator<Word.HangulAndAlphabetException>;
new(col: Word.HeadersFooters): Enumerator<Word.HeaderFooter>;
new(col: Word.HeadingStyles): Enumerator<Word.HeadingStyle>;
new(col: Word.HTMLDivisions): Enumerator<Word.HTMLDivision>;
new(col: Word.Hyperlinks): Enumerator<Word.Hyperlink>;
new(col: Word.Indexes): Enumerator<Word.Index>;
new(col: Word.InlineShapes): Enumerator<Word.InlineShape>;
new(col: Word.KeyBindings | Word.KeysBoundTo): Enumerator<Word.KeyBinding>;
new(col: Word.Languages): Enumerator<Word.Language>;
new(col: Word.Lines): Enumerator<Word.Line>;
new(col: Word.ListEntries): Enumerator<Word.ListEntry>;
new(col: Word.ListGalleries): Enumerator<Word.ListGallery>;
new(col: Word.ListLevels): Enumerator<Word.ListLevel>;
new(col: Word.ListParagraphs | Word.Paragraphs): Enumerator<Word.Paragraph>;
new(col: Word.Lists): Enumerator<Word.List>;
new(col: Word.ListTemplates): Enumerator<Word.ListTemplate>;
new(col: Word.MailMergeDataFields): Enumerator<Word.MailMergeDataField>;
new(col: Word.MailMergeFieldNames): Enumerator<Word.MailMergeFieldName>;
new(col: Word.MailMergeFields): Enumerator<Word.MailMergeField>;
new(col: Word.MappedDataFields): Enumerator<Word.MappedDataField>;
new(col: Word.OMathAutoCorrectEntries): Enumerator<Word.OMathAutoCorrectEntry>;
new(col: Word.OMathFunctions): Enumerator<Word.OMathFunction>;
new(col: Word.OMathMatCols): Enumerator<Word.OMathMatCol>;
new(col: Word.OMathMatRows): Enumerator<Word.OMathMatRow>;
new(col: Word.OMathRecognizedFunctions): Enumerator<Word.OMathRecognizedFunction>;
new(col: Word.OMaths): Enumerator<Word.OMath>;
new(col: Word.OtherCorrectionsExceptions): Enumerator<Word.OtherCorrectionsException>;
new(col: Word.PageNumbers): Enumerator<Word.PageNumber>;
new(col: Word.Pages): Enumerator<Word.Page>;
new(col: Word.Panes): Enumerator<Word.Pane>;
new(col: Word.ProtectedViewWindows): Enumerator<Word.ProtectedViewWindow>;
new(col: Word.ReadabilityStatistics): Enumerator<Word.ReadabilityStatistic>;
new(col: Word.RecentFiles): Enumerator<Word.RecentFile>;
new(col: Word.Rectangles): Enumerator<Word.Rectangle>;
new(col: Word.Reviewers): Enumerator<Word.Reviewer>;
new(col: Word.Revisions): Enumerator<Word.Revision>;
new(col: Word.Rows): Enumerator<Word.Row>;
new(col: Word.Sections): Enumerator<Word.Section>;
new(col: Word.ShapeNodes): Enumerator<Word.ShapeNode>;
new(col: Word.SmartTagActions): Enumerator<Word.SmartTagAction>;
new(col: Word.SmartTagRecognizers): Enumerator<Word.SmartTagRecognizer>;
new(col: Word.SmartTags): Enumerator<Word.SmartTag>;
new(col: Word.SmartTagTypes): Enumerator<Word.SmartTagType>;
new(col: Word.Sources): Enumerator<Word.Source>;
new(col: Word.SpellingSuggestions): Enumerator<Word.SpellingSuggestion>;
new(col: Word.Styles): Enumerator<Word.Style>;
new(col: Word.StyleSheets): Enumerator<Word.StyleSheet>;
new(col: Word.Subdocuments): Enumerator<Word.Subdocument>;
new(col: Word.Tables): Enumerator<Word.Table>;
new(col: Word.TablesOfAuthorities): Enumerator<Word.TableOfAuthorities>;
new(col: Word.TablesOfAuthoritiesCategories): Enumerator<Word.TableOfAuthoritiesCategory>;
new(col: Word.TablesOfContents): Enumerator<Word.TableOfContents>;
new(col: Word.TablesOfFigures): Enumerator<Word.TableOfFigures>;
new(col: Word.TabStops): Enumerator<Word.TabStop>;
new(col: Word.TaskPanes): Enumerator<Word.TaskPane>;
new(col: Word.Tasks): Enumerator<Word.Task>;
new(col: Word.Templates): Enumerator<Word.Template>;
new(col: Word.TextColumns): Enumerator<Word.TextColumn>;
new(col: Word.TwoInitialCapsExceptions): Enumerator<Word.TwoInitialCapsException>;
new(col: Word.Variables): Enumerator<Word.Variable>;
new(col: Word.Versions): Enumerator<Word.Version>;
new(col: Word.Windows): Enumerator<Word.Window>;
new(col: Word.XMLChildNodeSuggestions): Enumerator<Word.XMLChildNodeSuggestion>;
new(col: Word.XMLNamespaces): Enumerator<Word.XMLNamespace>;
new(col: Word.XMLNodes): Enumerator<Word.XMLNode>;
new(col: Word.XMLSchemaReferences): Enumerator<Word.XMLSchemaReference>;
new(col: Word.XSLTransforms): Enumerator<Word.XSLTransform>;
}
interface SafeArray<T = any> {
_brand: SafeArray<T>;
} | the_stack |
import * as React from "react";
import {
View,
Animated,
Text,
StyleSheet,
StyleProp,
ViewStyle,
TextStyle,
Platform,
TextInputProps,
ImageStyle,
I18nManager,
LayoutChangeEvent,
TextInput as NativeTextInput,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import dateFormat from "dateformat";
import { withTheme } from "../../theming";
import Portal from "../Portal/Portal";
import Button from "../DeprecatedButton";
import Touchable from "../Touchable";
import DateTimePicker from "./DatePickerComponent";
import type { Theme } from "../../styles/DefaultTheme";
import type { IconSlot } from "../../interfaces/Icon";
import { usePrevious } from "../../hooks";
const AnimatedText = Animated.createAnimatedComponent(Text);
const FOCUS_ANIMATION_DURATION = 150;
const BLUR_ANIMATION_DURATION = 180;
const ICON_SIZE = 24;
type Props = {
style?: StyleProp<ViewStyle> & { height?: number };
theme: Theme;
// initialDate?: string;
// locale?: string;
// minuteInterval?: number;
// timeZoneOffsetInMinutes?: number;
// error?: boolean;
// type?: string;
date?: Date;
format?: string;
onDateChange?: (data?: Date) => void;
initialValue?: Date; // deprecated
defaultValue?: Date;
disabled?: boolean;
mode?: "date" | "time" | "datetime";
type?: "solid" | "underline";
label?: string;
placeholder?: string;
leftIconName?: string;
leftIconMode?: "outset" | "inset";
rightIconName?: string;
} & IconSlot &
TextInputProps;
const MONTHS = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const DatePicker: React.FC<Props> = ({
Icon,
style,
theme: { colors, typography, roundness, disabledOpacity },
date,
onDateChange = () => {},
initialValue,
defaultValue,
disabled = false,
mode = "date",
format,
type = "underline",
leftIconName,
rightIconName,
leftIconMode = "inset",
label,
placeholder,
...props
}) => {
const [value, setValue] = React.useState<any>(date || defaultValue);
React.useEffect(() => {
if (defaultValue != null) {
setValue(defaultValue);
}
}, [defaultValue]);
const [pickerVisible, setPickerVisible] = React.useState(false);
const [labeled] = React.useState<Animated.Value>(
new Animated.Value(date ? 0 : 1)
);
const [placeholder1, setPlaceholder1] = React.useState("");
const [focused, setFocused] = React.useState<boolean>(false);
const [labelLayout, setLabelLayout] = React.useState<{
measured: Boolean;
width: number;
}>({ measured: false, width: 0 });
const previousInitialValue = usePrevious(initialValue);
React.useEffect(() => {
const initialValueStr = initialValue ? initialValue.toString() : "";
const previousInitialValueStr = previousInitialValue
? // This weirdly complains about being possibly undefined despite being inside a ternary
// @ts-ignore
previousInitialValue.toString()
: "";
if (initialValueStr !== previousInitialValueStr) {
setValue(initialValue);
onDateChange(initialValue);
}
}, [initialValue, previousInitialValue, setValue, onDateChange]);
const getValidDate = (): Date => {
if (!value) {
return new Date();
}
return typeof value?.getMonth === "function" ? value : new Date();
};
const formatDate = (): string => {
if (!value) return "";
let newDate = getValidDate();
if (format) return dateFormat(newDate, format);
if (mode === "time") {
return `${newDate.toLocaleTimeString()}`;
}
if (mode === "datetime") {
return `${newDate.toLocaleString()}`;
}
return `${
MONTHS[newDate.getMonth()]
} ${newDate.getDate()}, ${newDate.getFullYear()}`;
};
const toggleVisibility = async () => {
setPickerVisible(!pickerVisible);
focused ? _handleBlur() : _handleFocus();
};
const insets = useSafeAreaInsets();
// const _restoreLabel = () =>
// Animated.timing(labeled, {
// toValue: 1,
// duration: FOCUS_ANIMATION_DURATION,
// useNativeDriver: true,
// }).start();
// const _minmizeLabel = () =>
// Animated.timing(labeled, {
// toValue: 0,
// duration: BLUR_ANIMATION_DURATION,
// useNativeDriver: true,
// }).start();
// const _showPlaceholder = () =>
// setTimeout(() => setPlaceholder1(placeholder || ""), 50);
const _hidePlaceholder = () => {
setPlaceholder1("");
};
React.useEffect(() => {
setValue(date);
}, [date]);
React.useEffect(() => {
if (value || focused || placeholder1) {
// _minmizeLabel();
Animated.timing(labeled, {
toValue: 0,
duration: BLUR_ANIMATION_DURATION,
useNativeDriver: true,
}).start();
} else {
// _restoreLabel();
Animated.timing(labeled, {
toValue: 1,
duration: FOCUS_ANIMATION_DURATION,
useNativeDriver: true,
}).start();
}
}, [value, focused, placeholder1, labeled]);
React.useEffect(() => {
const _showPlaceholder = () =>
setTimeout(() => setPlaceholder1(placeholder || ""), 50);
if (focused || !label) {
_showPlaceholder();
} else {
_hidePlaceholder();
}
return () => {
clearTimeout(_showPlaceholder());
};
}, [focused, label, placeholder]);
const _handleFocus = () => {
if (disabled) {
return;
}
setFocused(true);
};
const _handleBlur = () => {
if (disabled) {
return;
}
setFocused(false);
};
const MINIMIZED_LABEL_Y_OFFSET = -(typography.caption.lineHeight + 4);
const OUTLINE_MINIMIZED_LABEL_Y_OFFSET = -(16 * 0.5 + 4);
const MAXIMIZED_LABEL_FONT_SIZE = typography.subtitle1.fontSize;
const MINIMIZED_LABEL_FONT_SIZE = typography.caption.fontSize;
const hasActiveOutline = focused;
let inputTextColor,
activeColor,
underlineColor,
borderColor,
placeholderColor,
containerStyle: StyleProp<ViewStyle>,
backgroundColor,
inputStyle: StyleProp<TextStyle>;
inputTextColor = colors.strong;
if (disabled) {
activeColor = colors.light;
placeholderColor = colors.light;
borderColor = "transparent";
underlineColor = "transparent";
backgroundColor = colors.divider;
} else {
activeColor = colors.primary;
placeholderColor = borderColor = colors.light;
underlineColor = colors.light;
backgroundColor = colors.background;
}
const { lineHeight, ...subtitle1 } = typography.subtitle1;
inputStyle = {
paddingVertical: 0,
color: inputTextColor,
paddingLeft:
leftIconName && leftIconMode === "inset"
? ICON_SIZE + (type === "solid" ? 16 : 12)
: 0,
paddingRight: rightIconName ? ICON_SIZE + 16 + 4 : 12,
...subtitle1,
height: lineHeight,
};
if (type === "underline") {
containerStyle = {
borderTopLeftRadius: roundness,
borderTopRightRadius: roundness,
paddingBottom: 12,
marginTop: 16,
};
} else {
containerStyle = {
borderRadius: roundness,
borderColor: hasActiveOutline ? activeColor : borderColor,
borderWidth: 1,
paddingTop: labeled ? 16 * 1.5 : 16,
paddingBottom: labeled ? 16 * 0.5 : 16,
opacity: disabled ? disabledOpacity : 1,
backgroundColor,
};
inputStyle.paddingHorizontal = 12;
}
if (leftIconName && leftIconMode === "outset") {
containerStyle.marginLeft = ICON_SIZE + 8;
}
let leftIconColor;
if (focused) {
leftIconColor = colors.primary;
} else {
leftIconColor = colors.light;
}
const leftIconProps = {
size: 24,
color: leftIconColor,
name: leftIconName || "",
};
const leftIconStyle: ImageStyle = {
position: "absolute",
marginTop:
type === "solid"
? leftIconMode === "inset"
? MINIMIZED_LABEL_FONT_SIZE + 4
: 16
: leftIconMode === "outset"
? 16
: 0,
};
const labelStyle = {
...typography.subtitle1,
top: type === "solid" ? 16 : 0,
left:
leftIconName && leftIconMode === "inset"
? ICON_SIZE + (type === "solid" ? 16 : 12)
: 0,
transform: [
{
// Move label to top
translateY: labeled.interpolate({
inputRange: [0, 1],
outputRange: [
type === "solid"
? OUTLINE_MINIMIZED_LABEL_Y_OFFSET
: MINIMIZED_LABEL_Y_OFFSET,
0,
],
}),
},
{
// Make label smaller
scale: labeled.interpolate({
inputRange: [0, 1],
outputRange: [
MINIMIZED_LABEL_FONT_SIZE / MAXIMIZED_LABEL_FONT_SIZE,
1,
],
}),
},
{
// Offset label scale since RN doesn't support transform origin
translateX: labeled.interpolate({
inputRange: [0, 1],
outputRange: [
-(1 - MINIMIZED_LABEL_FONT_SIZE / MAXIMIZED_LABEL_FONT_SIZE) *
(labelLayout.width / 2),
0,
],
}),
},
],
};
const inputStyles = [
styles.input,
inputStyle,
type === "solid" ? { marginHorizontal: 12 } : {},
];
// const render = (props) => <NativeTextInput {...props} />;
return (
<View style={[styles.container, style]}>
<Touchable disabled={disabled} onPress={toggleVisibility}>
<View pointerEvents="none">
<View style={[styles.container, style]}>
{leftIconName && leftIconMode === "outset" ? (
<Icon {...leftIconProps} style={leftIconStyle} />
) : null}
<View
style={[containerStyle, style ? { height: style.height } : {}]}
>
{type === "underline" ? (
// When type === 'flat', render an underline
<Animated.View
style={[
styles.underline,
{
backgroundColor: focused ? activeColor : underlineColor,
// Underlines is thinner when input is not focused
transform: [{ scaleY: focused ? 1 : 0.5 }],
},
]}
/>
) : null}
{label ? (
// Position colored placeholder and gray placeholder on top of each other and crossfade them
// This gives the effect of animating the color, but allows us to use native driver
<View
pointerEvents="none"
style={[
StyleSheet.absoluteFill,
{
opacity:
// Hide the label in minimized state until we measure its width
date || focused ? (labelLayout.measured ? 1 : 0) : 1,
},
]}
>
<AnimatedText
onLayout={(e: LayoutChangeEvent) =>
setLabelLayout({
width: e.nativeEvent.layout.width,
measured: true,
})
}
style={[
styles.placeholder,
type === "solid" ? { paddingHorizontal: 12 } : {},
labelStyle,
{
color: colors.light,
opacity: labeled.interpolate({
inputRange: [0, 1],
outputRange: [hasActiveOutline ? 1 : 0, 0],
}),
},
]}
numberOfLines={1}
>
{label}
</AnimatedText>
<AnimatedText
style={[
styles.placeholder,
type === "solid" ? { paddingHorizontal: 12 } : {},
labelStyle,
{
color: placeholderColor,
opacity: hasActiveOutline ? labeled : 1,
},
]}
numberOfLines={1}
>
{label}
</AnimatedText>
</View>
) : null}
{leftIconName && leftIconMode === "inset" ? (
<Icon
{...leftIconProps}
style={{
...leftIconStyle,
marginLeft: type === "solid" ? 16 : 0,
}}
/>
) : null}
<NativeTextInput
value={formatDate()}
placeholder={label ? placeholder1 : placeholder}
editable={!disabled}
placeholderTextColor={placeholderColor}
selectionColor={activeColor}
onFocus={_handleFocus}
onBlur={_handleBlur}
underlineColorAndroid={"transparent"}
style={inputStyles}
{...props}
/>
</View>
{rightIconName ? (
<Icon
name={rightIconName}
size={ICON_SIZE}
color={colors.light}
style={{
position: "absolute",
right: 16,
marginTop:
type === "solid" ? MINIMIZED_LABEL_FONT_SIZE + 4 : 16,
}}
/>
) : null}
</View>
</View>
</Touchable>
{pickerVisible && (
<Portal>
<View
style={[
styles.picker,
{
backgroundColor: colors.divider,
},
]}
>
<View
style={[
styles.pickerContainer,
{
paddingTop: insets.top,
paddingBottom: insets.bottom,
paddingLeft: insets.left,
paddingRight: insets.right,
},
]}
>
{Platform.OS === "ios" && (
<Button
Icon={Icon}
type="text"
onPress={toggleVisibility}
style={styles.closeButton}
>
Close
</Button>
)}
<DateTimePicker
value={getValidDate()}
mode={mode}
isVisible={pickerVisible}
toggleVisibility={toggleVisibility}
onChange={(_event: any, data: any) => {
Platform.OS === "ios" ? null : toggleVisibility();
setValue(data);
onDateChange(data);
}}
/>
</View>
</View>
</Portal>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
alignSelf: "stretch",
},
picker: {
position: "absolute",
bottom: 0,
left: 0,
right: 0,
flexDirection: "row",
justifyContent: "center",
},
underline: {
position: "absolute",
left: 0,
right: 0,
bottom: 0,
height: 2,
},
input: {
flexGrow: 1,
justifyContent: "center",
textAlignVertical: "center",
margin: 0,
textAlign: I18nManager.isRTL ? "right" : "left",
},
placeholder: {
position: "absolute",
left: 0,
},
pickerContainer: { flexDirection: "column", width: "100%" },
closeButton: {
alignSelf: "flex-end",
},
});
export default withTheme(DatePicker); | the_stack |
import assert from 'assert'
import * as t from '@babel/types'
import { Prop, Data, ChildComponent, DefaultValue } from './types'
type StaticKey = t.Identifier | t.StringLiteral | t.NumericLiteral
export function extractProps(program: t.Program): Prop[] {
const options = findComponentOptions(program.body)
if (!options) return []
const props = findProperty(options.properties, 'props')
if (!props) return []
if (t.isObjectExpression(props.value)) {
return props.value.properties.filter(isStaticProperty).map(p => {
const key = p.key as StaticKey
return {
name: getStaticKeyName(key),
type: getPropType(p.value),
default: getPropDefault(p.value)
}
})
} else if (t.isArrayExpression(props.value)) {
return props.value.elements
.filter((el): el is t.StringLiteral => !!el && isStringLiteral(el))
.map(el => {
return {
name: el.value,
type: 'any',
default: undefined
}
})
} else {
return []
}
}
export function extractData(program: t.Program): Data[] {
const options = findComponentOptions(program.body)
if (!options) return []
const data = findPropertyOrMethod(options.properties, 'data')
if (!data) return []
const obj = getDataObject(data)
if (!obj) return []
return obj.properties.filter(isStaticProperty).map(p => {
const key = p.key as StaticKey
return {
name: getStaticKeyName(key),
default: getLiteralValue(p.value)
}
})
}
export function extractChildComponents(
program: t.Program,
uri: string,
localPathToUri: (localPath: string) => string
): ChildComponent[] {
const imports = getImportDeclarations(program.body)
const options = findComponentOptions(program.body)
if (!options) return []
const childComponents = []
const selfName = findProperty(options.properties, 'name')
if (selfName && isStringLiteral(selfName.value)) {
childComponents.push({
name: selfName.value.value,
uri
})
}
const components = findProperty(options.properties, 'components')
if (components) {
childComponents.push(
...extractComponents(components, imports, localPathToUri)
)
}
const lifecycle = findPropertyOrMethod(options.properties, 'beforeCreate')
if (lifecycle) {
childComponents.push(
...extractLazyAddComponents(lifecycle, imports, localPathToUri)
)
}
return childComponents
}
function extractComponents(
prop: t.ObjectProperty,
imports: Record<string, t.ImportDeclaration>,
localPathToUri: (localPath: string) => string
): ChildComponent[] {
if (!t.isObjectExpression(prop.value)) {
return []
}
function notUndef<T>(p: T | undefined): p is T {
return p !== undefined
}
return prop.value.properties
.map(
(p): ChildComponent | undefined => {
if (!isStaticProperty(p) || !t.isIdentifier(p.value)) {
return undefined
}
return findMatchingComponent(
getStaticKeyName(p.key as StaticKey),
p.value.name,
imports,
localPathToUri
)
}
)
.filter(notUndef)
}
function extractLazyAddComponents(
prop: t.ObjectProperty | t.ObjectMethod,
imports: Record<string, t.ImportDeclaration>,
localPathToUri: (localPath: string) => string
): ChildComponent[] {
const func = normalizeMethod(prop)
if (!func || !t.isBlockStatement(func.body)) {
return []
}
function notUndef<T>(p: T | undefined): p is T {
return p !== undefined
}
// Extract all `this.$options.components.LocalComponentName = ComponentName`
return func.body.body
.map(
(st): ChildComponent | undefined => {
// We leave this chack as loosely since the user may not write
// `this.$options.components.LocalComponentName = ComponentName`
// but assign `components` to another variable to save key types.
// If there are false positive in this check, they probably be
// proned by maching with imported components in later.
if (
!t.isExpressionStatement(st) ||
!t.isAssignmentExpression(st.expression) ||
!t.isIdentifier(st.expression.right) || // = ComponentName
!t.isMemberExpression(st.expression.left) ||
!t.isIdentifier(st.expression.left.property) // .LocalComponentName
) {
return undefined
}
return findMatchingComponent(
st.expression.right.name,
st.expression.left.property.name,
imports,
localPathToUri
)
}
)
.filter(notUndef)
}
function getImportDeclarations(
body: t.Statement[]
): Record<string, t.ImportDeclaration> {
const res: Record<string, t.ImportDeclaration> = {}
body.forEach(node => {
if (!t.isImportDeclaration(node)) return
// Collect all declared local variables in import declaration into record
// to store all possible components.
node.specifiers.forEach(s => {
res[s.local.name] = node
})
})
return res
}
function findMatchingComponent(
localName: string,
importedName: string,
imports: Record<string, t.ImportDeclaration>,
localPathToUri: (localPath: string) => string
): ChildComponent | undefined {
const componentImport = imports[importedName]
if (!componentImport) return undefined
const sourcePath = componentImport.source.value as string
assert(
typeof sourcePath === 'string',
'[script] Import declaration unexpectedly has non-string literal: ' +
sourcePath
)
return {
name: localName,
uri: localPathToUri(sourcePath)
}
}
function isStringLiteral(node: t.Node): node is t.StringLiteral {
return t.isStringLiteral(node)
}
/**
* Check if the property has a statically defined key
* If it returns `true`, `node.key` should be `StaticKey`.
*/
function isStaticProperty(
node: t.ObjectProperty | t.ObjectMethod | t.SpreadProperty
): node is t.ObjectProperty {
return t.isObjectProperty(node) && !node.computed
}
function isStaticPropertyOrMethod(
node: t.ObjectProperty | t.ObjectMethod | t.SpreadProperty
): node is t.ObjectProperty | t.ObjectMethod {
return isStaticProperty(node) || (t.isObjectMethod(node) && !node.computed)
}
function getStaticKeyName(key: StaticKey): string {
return t.isIdentifier(key) ? key.name : String(key.value)
}
/**
* Find a property name that matches the specified property name.
*/
export function findProperty(
props: (t.ObjectProperty | t.ObjectMethod | t.SpreadProperty)[],
name: string
): t.ObjectProperty | undefined {
return props.filter(isStaticProperty).find(p => {
const key = p.key as StaticKey
return getStaticKeyName(key) === name
})
}
function findPropertyOrMethod(
props: (t.ObjectProperty | t.ObjectMethod | t.SpreadProperty)[],
name: string
): t.ObjectProperty | t.ObjectMethod | undefined {
return props.filter(isStaticPropertyOrMethod).find(p => {
const key = p.key as StaticKey
return getStaticKeyName(key) === name
})
}
/**
* Return function-like node if object property has
* function value or it is a method.
* Return undefined if it does not have a function value.
*/
function normalizeMethod(
prop: t.ObjectProperty | t.ObjectMethod
): t.Function | undefined {
if (t.isObjectMethod(prop)) {
return prop
}
if (t.isFunction(prop.value)) {
return prop.value as t.Function
}
return undefined
}
/**
* Detect `Vue.extend(...)`
*/
function isVueExtend(
node: t.Declaration | t.Expression
): node is t.CallExpression {
if (!t.isCallExpression(node) || !t.isMemberExpression(node.callee)) {
return false
}
const property = node.callee.property
if (!t.isIdentifier(property, { name: 'extend' })) {
return false
}
const object = node.callee.object
if (!object || !t.isIdentifier(object, { name: 'Vue' })) {
return false
}
return true
}
function getPropType(value: t.Expression | t.PatternLike): string {
if (t.isIdentifier(value)) {
// Constructor
return value.name
} else if (t.isObjectExpression(value)) {
// Detailed prop definition
// { type: ..., ... }
const type = findProperty(value.properties, 'type')
if (type && t.isIdentifier(type.value)) {
return type.value.name
}
}
return 'any'
}
function getPropDefault(value: t.Expression | t.PatternLike): DefaultValue {
if (t.isObjectExpression(value)) {
// Find `default` property in the prop option.
const def = findPropertyOrMethod(value.properties, 'default')
if (def) {
// If it is a function, extract default value from it,
// otherwise just use the value.
const func = normalizeMethod(def)
if (func) {
const exp = getReturnedExpression(func.body)
return exp && getLiteralValue(exp)
} else {
return getLiteralValue((def as t.ObjectProperty).value)
}
}
}
return undefined
}
function getDataObject(
prop: t.ObjectProperty | t.ObjectMethod
): t.ObjectExpression | undefined {
// If the value is an object expression, just return it.
if (t.isObjectProperty(prop)) {
const value = prop.value
if (t.isObjectExpression(value)) {
return value
}
}
// If the value is a function, return the returned object expression
const func = normalizeMethod(prop)
if (func) {
const exp = getReturnedExpression(func.body)
if (exp && t.isObjectExpression(exp)) {
return exp
}
}
return undefined
}
/**
* Extract returned expression in function body.
* The function `body` should be `BlockStatement` in the declared type
* but it can be other expressions if it forms like `() => ({ foo: 'bar' })`
*/
function getReturnedExpression(
block: t.BlockStatement | t.Expression
): t.Expression | undefined {
if (t.isBlockStatement(block)) {
const statements = block.body.slice().reverse()
for (const s of statements) {
if (t.isReturnStatement(s)) {
return s.argument || undefined
}
}
} else {
return block
}
}
function getLiteralValue(node: t.Node): DefaultValue {
// Simple literals like number, string and boolean
if (
t.isStringLiteral(node) ||
t.isNumericLiteral(node) ||
t.isBooleanLiteral(node)
) {
return node.value
}
if (t.isNullLiteral(node)) {
return null
}
// Object literal
if (t.isObjectExpression(node)) {
const obj: Record<string, DefaultValue> = {}
node.properties.forEach(p => {
if (!t.isObjectProperty(p)) {
return
}
if (p.computed || !t.isIdentifier(p.key)) {
return
}
obj[p.key.name] = getLiteralValue(p.value)
})
return obj
}
// Array literal
if (t.isArrayExpression(node)) {
function notNull<T>(x: T | null): x is T {
return !!x
}
return node.elements.filter(notNull).map(getLiteralValue)
}
return undefined
}
export function findComponentOptions(
body: t.Statement[]
): t.ObjectExpression | undefined {
const exported = body.find(
(n): n is t.ExportDefaultDeclaration => t.isExportDefaultDeclaration(n)
)
if (!exported) return undefined
// TODO: support class style component
const dec = exported.declaration
if (t.isObjectExpression(dec)) {
// Using object literal definition
// export default {
// ...
// }
return dec
} else if (isVueExtend(dec) && t.isObjectExpression(dec.arguments[0])) {
// Using Vue.extend with object literal
// export default Vue.extend({
// ...
// })
return dec.arguments[0] as t.ObjectExpression
}
return undefined
} | the_stack |
import type { IndexedCollection } from "./utility-types.ts";
import type { PrimitiveView } from "./view-types.ts";
export class StringView extends DataView implements PrimitiveView<string> {
static viewLength = 0;
static masks = new Int8Array(256).fill(-1);
static decoder = new TextDecoder();
static encoder = new TextEncoder();
/**
* The amount of UTF characters in the StringView.
*/
get size() {
let size = 0;
for (let i = 0; i < this.byteLength; i++) {
if (this.getUint8(i) >> 6 !== 2) size++;
}
return size;
}
/**
* Converts a UTF8 byte array into a JS string.
* Adopted from Google Closure:
* https://github.com/google/closure-library/blob/master/closure/goog/crypt/crypt.js
*
* @param view the view to decode
* @param start the starting offset
* @param length the byte length to decode
* @return the JavaScript value
*/
static decode(view: DataView, start = 0, length = view.byteLength): string {
if (length > 200) {
const arrayOffset = view.byteOffset + start;
const arrayLength = length === view.byteLength
? length - arrayOffset
: length;
return this.decoder.decode(
new Uint8Array(view.buffer, arrayOffset, arrayLength),
);
}
const out = [];
const end = start + length;
let pos = start;
let c = 0;
while (pos < end) {
const c1 = view.getUint8(pos++);
// bail on zero byte
if (c1 === 0) break;
if (c1 < 128) {
out[c++] = c1;
} else if (c1 > 191 && c1 < 224) {
out[c++] = ((c1 & 31) << 6) | (view.getUint8(pos++) & 63);
} else if (c1 > 239 && c1 < 365) {
// Surrogate Pair
const u = (((c1 & 7) << 18) |
((view.getUint8(pos++) & 63) << 12) |
((view.getUint8(pos++) & 63) << 6) |
(view.getUint8(pos++) & 63)) -
0x10000;
out[c++] = 0xd800 + (u >> 10);
out[c++] = 0xdc00 + (u & 1023);
} else {
out[c++] = ((c1 & 15) << 12) |
((view.getUint8(pos++) & 63) << 6) |
(view.getUint8(pos++) & 63);
}
}
return String.fromCharCode.apply(String, out);
}
/**
* Converts a JS string into a UTF8 byte array.
* Adopted from Deno:
* https://github.com/denoland/deno/blob/18a684ab1c20914e13c27bc10e20bda6396ea38d/extensions/web/08_text_encoding.js#L79
*
* @param value the value to encode
* @param view the view to encode into
* @param start the view offset to start
* @param length the byte length to encode
* @return the amount of written bytes
*/
static encode(
value: string,
view: DataView,
start = 0,
length?: number,
): number {
let written = 0;
const valueLength = value.length;
const byteLength = length ?? valueLength << 1;
if (byteLength > 200) {
({ written } = this.encoder.encodeInto(
value,
new Uint8Array(view.buffer, view.byteOffset + start, length),
));
} else {
let read = 0;
const maxLength = Math.min(byteLength, view.byteLength);
while (read < valueLength) {
const badCodePoint = 0xfffd;
const codeUnit = value.charCodeAt(read++);
const surrogateMask = codeUnit & 0xfc00;
let codePoint = codeUnit;
if (surrogateMask === 0xd800) {
if (read < valueLength) {
const nextCodeUnit = value.charCodeAt(read);
if ((nextCodeUnit & 0xfc00) === 0xdc00) {
codePoint = 0x10000 + ((codeUnit & 0x3ff) << 10) +
(nextCodeUnit & 0x3ff);
read++;
} else {
codePoint = badCodePoint;
}
} else {
codePoint = badCodePoint;
}
} else if (surrogateMask === 0xdc00) {
codePoint = badCodePoint;
}
const availableSpace = maxLength - written;
if (availableSpace < 4) {
if (
availableSpace < 1 ||
(availableSpace < 2 && codePoint >= 0x80) ||
(availableSpace < 3 && codePoint >= 0x800) ||
codePoint >= 0x10000
) {
const isSurrogatePair = codePoint !== codeUnit &&
codePoint !== badCodePoint;
read -= isSurrogatePair ? 2 : 1;
break;
}
}
if (codePoint < 0x80) {
view.setUint8(start + written++, codePoint);
} else if (codePoint < 0x800) {
view.setUint8(start + written++, 0xc0 | (0x1f & (codePoint >> 6)));
view.setUint8(start + written++, 0x80 | (0x3f & codePoint));
} else if (codePoint < 0x10000) {
view.setUint8(start + written++, 0xe0 | (0x0f & (codePoint >> 12)));
view.setUint8(start + written++, 0x80 | (0x3f & (codePoint >> 6)));
view.setUint8(start + written++, 0x80 | (0x3f & codePoint));
} else {
view.setUint8(start + written++, 0xf0 | (0x07 & (codePoint >> 18)));
view.setUint8(start + written++, 0x80 | (0x3f & (codePoint >> 12)));
view.setUint8(start + written++, 0x80 | (0x3f & (codePoint >> 6)));
view.setUint8(start + written++, 0x80 | (0x3f & codePoint));
}
}
}
if (length) {
// zero-out remaining bytes if length is provided
let caret = written;
while (caret < length) view.setUint8(start + caret++, 0);
}
return written;
}
/**
* Creates a StringView from a string or an array like object.
*
* @param value the string to encode
* @return the new view
*/
static from(value: string) {
const length = this.getLength(value);
const view = new this(new ArrayBuffer(length));
this.encode(value, view);
return view;
}
/**
* Returns the size in bytes of a given string.
*
* @param string the string to check
* @return the size in bytes
*/
static getLength(string = "") {
let size = 0;
for (let i = 0; i < string.length; i++) {
const code = string.codePointAt(i)!; // todo test
if (code < 0x0080) size += 1;
// 1-byte
else if (code < 0x0800) size += 2;
// 2-byte
else if (code < 0x10000) size += 3;
// 3-byte
else {
// 4-byte
size += 4;
i++;
}
}
return size;
}
/**
* Returns a new string consisting of the single UTF character
* located at the specified character index.
*
* @param index a character index
* @return a string representing the character
*/
charAt(index = 0) {
return this.toChar(this.getCharStart(index));
}
/**
* Iterates over the characters in the StringView.
*/
*characters() {
for (let i = 0; i < this.byteLength; i++) {
if (this.getUint8(i) >> 6 !== 2) {
yield this.toChar(i);
}
}
}
/**
* Returns the string encoded in the StringView.
*/
get(): string {
return (this.constructor as typeof StringView).decode(this);
}
getCharEnd(index: number) {
const point = this.getUint8(index);
if (point < 0x80) return index;
switch ((point & 0xf0) >> 4) {
case 0xf:
return index + 3;
case 0xe:
return index + 2;
case 0xd:
case 0xc:
return index + 1;
default:
return -1;
}
}
getCharStart(index: number, startCharIndex = -1, startIndex = 0) {
let current = startCharIndex;
for (let i = startIndex; i < this.byteLength; i++) {
if (this.getUint8(i) >> 6 !== 2) current++;
if (current === index) return i;
}
return -1;
}
/**
* Performs an in-place replacement within the StringView
* of all occurrences of a given pattern with a given replacement.
*
* @param pattern the pattern to be replaced
* @param replacement the replacement
* @return this
*/
replace(pattern: IndexedCollection, replacement: IndexedCollection) {
let position = 0;
while (position < this.byteLength) {
const currentIndex = this.indexOf(pattern, position);
if (!~currentIndex) break;
new Uint8Array(this.buffer).set(replacement, currentIndex);
position = currentIndex + replacement.length;
}
return this;
}
/**
* Reverses the characters of the StringView in-place.
*
* @return this
*/
reverse() {
const last = this.byteLength - 1;
for (let i = 0, j = last; i < j; i++, j--) {
this.swapChar(i, j);
}
let j = this.byteLength;
while (--j > 0) {
switch ((this.getUint8(j) & 0xf0) >> 4) {
case 0xf:
this.swapChar(j, j - 3);
this.swapChar(j - 1, j - 2);
j -= 3;
break;
case 0xe:
this.swapChar(j, j - 2);
j -= 2;
break;
case 0xc:
case 0xd:
this.swapChar(j, j - 1);
j--;
break;
default:
break;
}
}
return this;
}
/**
* Checks whether the provided encoded sequence is found inside the view.
*
* @param searchValue the value to search for
* @param position the starting position
* @return whether the value is found
*/
includes(searchValue: IndexedCollection, position?: number): boolean {
return this.indexOf(searchValue, position) !== -1;
}
/**
* Returns the index within the StringView
* of the first occurrence of the specified value, starting the search at start.
* Returns -1 if the value is not found.
*
* @param searchValue the value to search for
* @param fromIndex the index at which to start the search
* @return the index of the first occurrence of the specified value
*/
indexOf(searchValue: IndexedCollection, fromIndex = 0) {
if (this.byteLength > 256 && searchValue.length < 32) {
return this.searchShiftOr(searchValue, fromIndex);
}
return this.searchNaive(searchValue, fromIndex);
}
searchNaive(searchValue: IndexedCollection, start: number) {
const wordLength = searchValue.length;
const max = this.byteLength - wordLength;
outer:
for (let i = start; i <= max; i++) {
for (let j = 0; j < wordLength; j++) {
if (this.getUint8(i + j) !== searchValue[j]) {
continue outer;
}
}
return i;
}
return -1;
}
searchShiftOr(searchValue: IndexedCollection, start: number) {
const { masks } = this.constructor as typeof StringView;
const m = searchValue.length;
const m1 = 1 << m;
masks.fill(-1);
let r = -2;
for (let i = 0; i < m; i++) {
masks[searchValue[i]] &= ~(1 << i);
}
for (let i = start; i < this.byteLength; i++) {
r |= masks[this.getUint8(i)];
r <<= 1;
if ((r & m1) === 0) {
return i - m + 1;
}
}
return -1;
}
/**
* Encodes a given string into the StringView
*/
set(value: string): void {
(this.constructor as typeof StringView).encode(value, this);
}
/**
* Returns a string of characters between the start and end
* character indexes, or to the end of the string.
*
* @param indexStart the character index of the first character to include
* @param indexEnd the character index of the first character to exclude
* @return a new string containing the specified part of the given string
*/
substring(indexStart = 0, indexEnd = this.size) {
const start = this.getCharStart(indexStart);
// return empty string if no character is found;
if (start === -1) return "";
const end = this.getCharStart(indexEnd, indexStart, start);
return (this.constructor as typeof StringView).decode(
this,
start,
end - start + 1,
);
}
toChar(index: number) {
// check boundaries
if (index < 0 || index > this.byteLength) return "";
const point = this.getUint8(index);
if (point < 0x80) return String.fromCodePoint(point);
switch ((point & 0xf0) >> 4) {
case 0xf:
return String.fromCodePoint(
((point & 0x07) << 18) |
((this.getUint8(index + 1) & 0x3f) << 12) |
((this.getUint8(index + 2) & 0x3f) << 6) |
(this.getUint8(index + 3) & 0x3f),
);
case 0xe:
return String.fromCodePoint(
((point & 0x0f) << 12) |
((this.getUint8(index + 1) & 0x3f) << 6) |
(this.getUint8(index + 2) & 0x3f),
);
case 0xd:
case 0xc:
return String.fromCodePoint(
((point & 0x1f) << 6) | (this.getUint8(index + 1) & 0x3f),
);
default:
return "";
}
}
/**
* Returns a string value of the StringView.
*/
toJSON() {
return this.get();
}
/**
* Returns a string value of the StringView.
*/
toString() {
return this.get();
}
/**
* Returns a StringView without trailing zeros.
*/
trim() {
let end = -1;
while (++end < this.byteLength) {
if (this.getUint8(end) === 0) break;
}
return end !== this.byteLength
? new (this.constructor as typeof StringView)(
this.buffer,
this.byteOffset,
end,
)
: this;
}
swapChar(i: number, j: number): void {
const temp = this.getUint8(i);
this.setUint8(i, this.getUint8(j));
this.setUint8(j, temp);
}
} | the_stack |
declare module "@fluid-experimental/property-properties" {
import { ChangeSet, SerializedChangeSet } from "@fluid-experimental/property-changeset"
namespace PROPERTY_TREE_NS {
class EventEmitter {
static defaultMaxListeners: number;
emit(type: string): boolean;
addListener(type: string, listener: (...args: any[]) => any): EventEmitter;
static listenerCount(emitter: EventEmitter, type: string): number;
listenerCount(type: string): number;
listeners(type: string): (...args: any[]) => any[];
static makeEventEmitter(constructor: (...args: any[]) => any): (...args: any[]) => any;
off(type: string, listener: (...args: any[]) => any): EventEmitter;
on(type: string, listener: (...args: any[]) => any): EventEmitter;
once(type: string, listener: (...args: any[]) => any): EventEmitter;
register(event: string, cb: (...args: any[]) => any): string;
removeAllListeners(type: string): EventEmitter;
removeListener(type: string, listener: (...args: any[]) => any): EventEmitter;
setMaxListeners(n: number): EventEmitter;
trigger(event: string, caller: object, argsArr?: any): void;
unregister(event: string, key: string): boolean;
}
/**
* The range combinations of two change sets (A and B)
* This can either be complete operations, parts of complete operations or overlapping segments
*/
type ArrayChangeSetRangeType_TYPE = number;
/**
* Used to set the synchronization mode of the Workspace.
*/
type SYNC_MODE_TYPE = number;
interface SYNC_MODE_ENUM {
MANUAL: number; // Application needs to update and push manually. Commit is local in this mode.
PUSH: number; // Workspace automatically pushes local commits to the server
PULL: number; // Workspace automatically pulls remote changes without pushing its changes back
SYNCHRONIZE: number; // Workspace updates and pushes automatically (default)
}
/**
* Used to control the invocation of the rebase callback
*/
type REBASE_CALLBACK_NOTIFICATION_MODES_TYPE = number;
interface REBASE_CALLBACK_NOTIFICATION_MODES_ENUM {
ALWAYS: number; // Always invoke the rebase
// callback
CONFLICTS_ONLY: number; // Only invoke the rebase callback when a conflict occurs
}
/**
* Used to Set the server side conflict handling mode on each commit.
*/
type SERVER_AUTO_REBASE_MODES_TYPE = number;
interface SERVER_AUTO_REBASE_MODES_ENUM {
NONE: number; // Server rejects all commits that are not based on top of the latest state.
// The conflict handler is always called. (default)
INDEPENDENT_PROPERTIES: number; // Server rebases only when paths within change sets are non-colliding.
// The conflict handler is called only when two change sets operate on the same paths.
// Server does not resolve any conflicts.
}
/**
* Determines in which cases a reference will automatically be resolved
*/
type REFERENCE_RESOLUTION_TYPE = number;
interface REFERENCE_RESOLUTION_ENUM {
ALWAYS: number; // The resolution will always automatically follow references
NO_LEAFS: number; // If a reference is the last entry during the path resolution, it will not automatically be resolved
NEVER: number; // References are never automatically resolved
}
/**
* Used to indicate the state of a property. These flags can be connected via OR.
*/
type MODIFIED_STATE_FLAGS_TYPE = number;
interface MODIFIED_STATE_FLAGS_ENUM {
CLEAN: number; // No changes to this property at the moment
PENDING_CHANGE: number; // The property is marked as changed in the currently pending ChangeSet
DIRTY: number; // The property has been modified and the result has not yet been reported to the application for scene updates
}
/**
* Binary Property States.
*/
type BINARY_PROPERTY_STATUS_TYPE = number;
interface BINARY_PROPERTY_STATUS_ENUM {
NEW: number;
INITIALIZED: number;
ATTACHING: number;
ATTACHED: number;
ATTACH_FAILED: number;
DELETING: number;
DELETED: number;
DELETE_FAILED: number;
EXPIRED: number;
PREPARED: number;
}
/**
* Token Types
*/
type TOKEN_TYPES_TYPE = number;
interface TOKEN_TYPES_ENUM {
PATH_SEGMENT_TOKEN: number; // A normal path segment, separated via .
ARRAY_TOKEN: number; // An array path segment, separated via [ ]
PATH_ROOT_TOKEN: number; // A / at the beginning of the path
DEREFERENCE_TOKEN: number; // A * that indicates a dereferencing operation
RAISE_LEVEL_TOKEN: number; // A ../ that indicates one step above the current path
}
/**
* The state of this repository reference
*/
type STATE_TYPE = number;
interface STATE_ENUM {
EMPTY: number; // The reference does not point to any other repository
LOADING: number; // The reference is currently loading the referenced repository
AVAILABLE: number; // The referenced repository has successfully been loaded and is available
FAILED: number; // Loading the referenced repository has failed
}
/**
* Repository states code
*/
type RepositoryState_TYPE = number;
interface RepositoryState_ENUM {
INIT: number;
LOADING: number;
LOADED: number;
UPDATING: number;
EDITING: number;
SAVING: number;
}
/**
* Iterator types
*/
type types_TYPE = number;
interface types_ENUM {
INSERT: number;
REMOVE: number;
MODIFY: number;
MOVE: number;
NOP: number;
}
/**
* Token Types
*/
type PATH_TOKENS_TYPE = number;
interface PATH_TOKENS_ENUM {
ROOT: number; // A / at the beginning of the path
REF: number; // A * that indicates a dereferencing operation
UP: number; // A ../ that indicates one step above the current path
}
type PropertyTemplateType = {
id?: string; // id of the property
name?: string; // Name of the property
typeid: string; // The type identifier
length?: number; // The length of the property. Only valid if
// the property is an array, otherwise the length defaults to 1
context?: string; // The type of property this template represents
// i.e. array, hash, etc.
properties?: Array<object>; // List of property templates that
// are used to define children properties
constants?: Array<object>; // List of property templates that
// are used to define constant properties and their values
inherits?: Array<string> | string; // List of property template typeids that this
// PropertyTemplate inherits from
annotation?: { [key: string]: string };
}
type ArrayProperty_ArrayProperty_in_params_TYPE = {
length: number; // the length of the array, if applicable
}
type BaseProperty_BaseProperty_in_params_TYPE = {
id: string; // id of the property
typeid: string; // The type unique identifier
length: number; // The length of the property. Only valid if
// the property is an array, otherwise the length defaults to 1
context: string; // The type of property this template represents
// i.e. single, array, map, set.
properties: Array<object>; // List of property templates that
// are used to define children properties -- UNUSED PARAMETER ??
inherits: Array<string>; // List of property template typeids that this
// PropertyTemplate inherits from -- UNUSED PARAMETER ??
}
type BinaryProperty_BinaryProperty_in_params_TYPE = {
typeid: string; // Type Id (nothing for BinaryProperty)
}
type ContainerProperty_ContainerProperty_in_params_TYPE = {
dataObj: object; // optional argument containing an object
// that should be used as the backing store of this value
// property
dataId: object; // optional argument must be provided when
// in_params.dataObj is passed. Must contain a valid member
// name of dataObj. This member will be used to set/get
// values of this value property
}
type EnumArrayProperty_EnumArrayProperty_in_params_TYPE = {
length: number; // the length of the array, if applicable
_enumDictionary: object; // the value<->enum dictonary needed to convert the values
}
type NamedNodeProperty_NamedNodeProperty_in_params_TYPE = {
id: string; // id of the property (null, if the GUID should be used for the ID)
typeid: string; // The type identifier
}
type NamedProperty_NamedProperty_in_params_TYPE = {
id: string; // id of the property (null, if the GUID should be used for the ID)
typeid: string; // The type identifier
}
type RepositoryReferenceProperty_RepositoryReferenceProperty_in_params_TYPE = {
id: string; // id of the property
name: string; // Name of the property
typeid: string; // The type identifier
}
type ValueProperty_ValueProperty_in_params_TYPE = {
dataObj: object; // optional argument containing an object
// that should be used as the backing store of this value
// property
dataId: object; // optional argument must be provided when
// in_params.dataObj is passed. Must contain a valid member
// name of dataObj. This member will be used to set/get
// values of this value property
}
type ScopeProperty_ScopeProperty_in_params_TYPE = {
scope: string; // The scope to keep track of
}
type Repository_Repository_in_params_TYPE = {
name: string; // the name of this repository.
creatorId: string; // The oxygen user ID of the person who creates the repository
guid: string; // the guid of the repository
commitCacheSize: number; // the size of the cache for old commits
}
type BranchNode_BranchNode_in_params_TYPE = {
guid: string; // The guid of the branch
name: string; // The name of the branch. Will default to the guid.
}
type PropertyFactory_create_in_options_TYPE = {
workspace: Workspace; // A checked out workspace to check against. If supplied,
// the function will check against the schemas that have been registered within the workspace
}
type PropertyFactory_inheritsFrom_in_options_TYPE = {
includeSelf?: boolean; // Also return true if in_templateTypeid === in_baseTypeid
workspace?: Workspace; // A checked out workspace to check against. If supplied,
// the function will check against the schemas that have been registered within the workspace
}
type PropertyFactory_getAllParentsForTemplate_in_options_TYPE = {
includeBaseProperty?: boolean; // Include BaseProperty as parent.
// Everything implicitly inherits
// from BaseProperty, but it is not explicitly listed in the
// template, so it is only included if explicitly requested
workspace?: Workspace; // A checked out workspace to check against. If supplied,
// the function will check against the schemas that have been registered within the workspace
}
type getBearerTokenFn = (...arg: any[]) => any; // TODO
type PropertyFactory_initializeSchemaStore_in_options_TYPE = {
getBearerToken: getBearerTokenFn; // Function that accepts a callback.
// Function that should be called with an error or the OAuth2 bearer token representing the user.
url: string; // The root of the url used in the request to retrieve PropertySet schemas.
}
type Workspace_initialize_in_options_TYPE = {
urn?: string; // The urn of the branch or commit to load
metadata?: { // The branch metadata
name?: string,
guid?: string,
};
local?: boolean; // Flag used work locally
paths?: string[]; // List of paths to checkout.
// NOTE: the workspace will ONLY load the given paths and will only receive changes on these paths from the server.
}
type Workspace_branch_in_options_TYPE = {
metadata?: { // The branch metadata
name?: string
};
local?: boolean; // Flag used to create a local branch
}
type Workspace_commit_in_options_TYPE = {
headers?: object; // Objects to be appended as headers in the request
local?: boolean; // Flag used to create a local commit
metadata?: object; // Object containing the commit meta data
mergeInfo?: object; // The merge info (if commit is based on a merge operation)
allowEmptyChangeset?: boolean; // Allow the commit even if changeSet is empty
}
type Workspace_rebase_in_options_TYPE = {
push?: boolean; // Flag used to indicate that any local commits that have been rebased
// onto the new commit will not be pushed to the the server.
squash?: boolean; // Flag used to squash the commits during the rebase.
metadata?: object; // Metadata that can be attached to a squashed rebase.
}
type Workspace_revertTo_in_options_TYPE = {
/**
* Only reverts the changes to properties and sub properties
* of the passed in paths. Default is revert all.
*/
paths: string[];
}
type Workspace_setRebaseCallback_in_options_TYPE = {
notificationMode?: number; // Mode controlling the invocation of the rebase callback
// (default = ALWAYS)
}
type Workspace_checkout_in_options_TYPE = {
paths: string[]; // List of paths to checkout.
// NOTE: the workspace will ONLY load the given paths and will only receive changes on these paths from the server.
}
type Workspace_resolvePath_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type Workspace_get_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type ArrayProperty_get_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type BaseProperty_serialize_in_options_TYPE = {
dirtyOnly?: boolean; // Only include dirty entries in the serialization
includeRootTypeid?: boolean; // Include the typeid of the root of the hierarchy
dirtinessType?: MODIFIED_STATE_FLAGS_TYPE; // The type of dirtiness to use when reporting dirty changes.
includeReferencedRepositories?: boolean; // If this is set to true, the serialize
// function will descend into referenced repositories. WARNING: if there are loops in the references
// this can result in an infinite loop
}
type Datastore = any; // TODO
type DataSource = any; // TODO
type BinaryProperty_initialize_in_params_TYPE = {
datastore: Datastore; // Datastore for storing data.
dataSource: DataSource; // DataSource to read or write to.
}
type ContainerProperty_get_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type ContainerProperty_getValue_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type ContainerProperty_resolvePath_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type ReferenceProperty_get_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type ReferenceProperty_resolvePath_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type CoarsePermission = 'read' | 'write' | 'delete';
type RepositoryPermission = 'repository.read' | 'repository.write' | 'repository.delete' | 'repository.share';
type BranchPermission = 'branch.read' | 'branch.write' | 'branch.delete' | 'branch.share';
type PropertyPermission = 'property.read' | 'property.insert' | 'property.modify' | 'property.remove' | 'property.share';
type Permission = RepositoryPermission | BranchPermission | PropertyPermission | CoarsePermission;
type Repository_getBranchNodes_in_options_TYPE = {
array: boolean; // Flag used to control the return
// type of the function. If set to true, the return value will be an Array
}
type Repository__branch_in_branchMetaData_TYPE = {
name: string; // The human readable name of the branch.
// If not specified, it defaults to the guid.
guid: string; // The guid of the branch. If not specified, a guid will be generated
}
type Repository__branch_in_options_TYPE = {
trackRemoteBranch: boolean; // Flag to track the remote branch.
// NOTE: This results in a BranchNode (remote) to be created and linked to the new BranchNode (local)
}
type Repository__rebase_in_options_TYPE = {
rebaseCallback: Function; // A callback that is invoked to perform the rebase operation. It will be invoked separately for each commit that
// is rebased, and then finally again for the pending changes if applicable. The function indicates via its
// return value, whether the rebase was successful. If true is returned the rebase will continue, if false is
// returned, it will be aborted (and no changes will occur). Furthermore, the function can modify the ChangeSet
// in the parameter transformedChangeSet to adapt the changes to the changes in the onto-branch.
//
// It will be passed an Object with these members:
// * {SerializedChangeSet} transformedChangeSet - The ChangeSet that resulted from performing the
// rebase operation on the primitive types and
// collections. This ChangeSet can be modified
// to adapt the changes to the changes in the
// onto-branch.
// * {SerializedChangeSet} originalChangeSet - The original ChangeSet before the rebase
// * {SerializedChangeSet} ontoBranchChangeSet - The changes between the common parent commit and
// the tip of the onto branch
// * {SerializedChangeSet} [currentState] - The normalized ChangeSet for the whole repository
// before the application of the
// transformedChangeSet. It will only be supplied
// when in_options.trackState===true, since
// computing this state can be expensive.
// * {Array.<ConflictInfo>} conflicts - List with the conflicts that occurred during the
// rebase
// * {CommitNode} [commitNode] - The commit node that is rebased. This is
// undefined, when the pending changes are rebased
// * {CommitNode} commonParentCommitNode - The commit node of the common parent
squash: boolean; // Flag used to squash the commits during the rebase.
metadata: object; // Metadata that can be attached to a squashed rebase.
trackState: boolean; // Enable tracking of the normalized ChangeSet during the rebase operation. This can be disabled, since the
// computation of the normalized ChangeSet incurs additional costs and should only be done when it is needed
// by the rebase function.
}
type RepositoryStore_createRemoteRepository_in_params_TYPE = {
changeSet: object; // The flattened change set to
// be set as the root commit.
// The repository object parameter
// Includes the guid of the repository plus all metadata
repository: {
guid: string,
creatorId?: string
};
rootCommit: { // The root commit object to add to the Repository
guid: string
};
}
type RepositoryStore_addCommitNode_in_params_TYPE = {
commit: object | undefined; // object describing a commit
commits: Array<object> | undefined; // Array of objects describing the individual commits
// within a batch. NOTE: If this parameter is not specified then "commit" param must be specified
changeSet: ChangeSet; // ChangeSet coupled with the commit object
branch: { // The branch information
guid: string
};
}
type RepositoryStore_updateRepository_in_params_TYPE = {
commits: Array<object>; // The list of commit objects
// Includes the guid of the commit plus all metadata
branch: object; // The branch object parameter
// Includes the guid of the branch plus all metadata
flatten: boolean; // flag used to indicate that the commit history is flattened
// This flag is generally set to true when loading a branch that doesn't
// exist locally. Defaults to false.
}
type EnumArrayProperty_get_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type ValueArrayProperty_get_in_options_TYPE = {
referenceResolutionMode: REFERENCE_RESOLUTION_TYPE; // How should this function behave during reference resolution?
}
type NamedProperty_share_permission_TYPE = {
userIds: Array<string>; // The user ids which will get permissions assigned
groupIds?: Array<string>; // The user group ids which will get permissions assigned
serviceIds?: Array<string>; // The service ids which will get permissions assigned
actions: PropertyPermission[]; // The actions to grant to the subject on the property
}
type NamedProperty_share_options_TYPE = {
synchronous?: boolean; // whether the share sould be sent to the PropertyTree immediatly or on next sync
noInherit?: boolean; // Optional flag to set noInherit on the property
}
type NamedProperty_unshare_permission_TYPE = {
userIds: Array<string>; // The user ids which will get permissions assigned
groupIds?: Array<string>; // The user group ids which will get permissions assigned
serviceIds?: Array<string>; // The service ids which will get permissions assigned
actions: PropertyPermission[]; // The actions to grant to the subject on the property
}
type NamedProperty_unshare_options_TYPE = {
synchronous?: boolean; // whether the share sould be sent to the PropertyTree immediatly or on next sync
}
type BranchIdentifier = any; // TODO
type CommitOrBranchIdentifier = any; // TODO
type RootProperty = any; // TODO
type ExpiryTimeType = 'transient' | 'temporary' | 'persistent' | number;
/** TODO
* apply a range's operation to the rebased changeset
* @param in_segment to be applied
* @param io_changeset target
* @param in_currentIndexOffset current offset
* @param out_conflicts A list of paths that resulted in conflicts together with the type of the conflict
* @param in_basePath Base path to get to the property processed by this function
* @param in_isPrimitiveType is it an array of primitive types
* @param in_options Optional additional parameters
*/
class PropertyError {
}
class PropertyFactoryError {
}
class RepositoryError {
}
class ServerError {
}
class ChangeSetError {
}
class UtilsError {
}
class PssClientError {
}
class JSONSchemaToPropertySetsTemplateConverter {
/**
* Recursively parses the given JSON Schema and returns the corresponding
* array of PropertySets Templates.
*/
getPropertySetsTemplates(): Array<object>;
/**
* Returns the absolute document URI of the given definition.
*
* A definition can modify the document URI for its sub-definitions if its id
* is an absolute URI for example or if it specifies a new relative URI.
*/
getDefinitionDocPath(): string;
/**
* Returns an absolute defintion id based on an absolute document path and a definition id.
*
* The absolute id of a definition depends on the current document path if the id
* of the definition is not itself an absolute path.
*/
getDefinitionAbsoluteId(): string;
/**
* Recursively parses the object refered by the given reference ('$ref').
*
* If the refered object is an individual Property Sets Template, just add a
* reference to it. Otherwise expands the refered object in place.
*/
parseSchemaReference(): object;
/**
* Recursively parses the given properties ('properties': {...}) and adds them
* to 'out_props' argument.
*/
parseSchemaProperties(): void;
/**
* Recursively parses the given oneOf array ('oneOf': [...]) and adds the properties
* to 'out_props' argument.
*
* TODO: Support arrays of more than one element.
*/
parseSchemaOneOf(): void;
/**
* Recursively parses the given allOf array ('allOf': [...]) and adds the properties
* to 'out_props' argument.
*/
parseSchemaAllOf(): void;
/**
* Adds the given PropertySets Template to the generated templates if not already there.
*/
addToTemplates(): void;
/**
* Recursively parses the given definition and returns it.
*/
parseSchemaDefinition(): object;
/**
* Recursively indexes the definitions of the schema.
*/
indexSchemaDefinitions(): void;
}
class ContainerProperty extends BaseProperty {
/**
* This class serves as a view to read, write and listen to changes in an
* object's value field. To do this we simply keep a pointer to the object and
* its associated data field that we are interested in. If no data field is
* present this property will fail constructing.
* @param in_params the parameters
*/
constructor(in_params: ContainerProperty_ContainerProperty_in_params_TYPE);
/**
* Returns the sub-property having the given name, or following the given paths, in this property.
* @param in_ids the ID or IDs of the property or an array of IDs
* if an array is passed, the .get function will be performed on each id in sequence
* for example .get(['position','x']) is equivalent to .get('position').get('x').
* If .get resolves to a ReferenceProperty, it will, by default, return the property that the
* ReferenceProperty refers to.
* @param in_options parameter object
*/
get<T = BaseProperty>(in_ids?: string | number | Array<string | number>, in_options?: ContainerProperty_get_in_options_TYPE): T | undefined;
/**
* returns the value of a sub-property
* This is a shortcut for .get(in_ids, in_options).getValue()
* @param in_ids the ID or IDs of the property or an array of IDs
* if an array is passed, the .get function will be performed on each id in sequence
* for example .getValue(['position','x']) is equivalent to .get('position').get('x').getValue().
* If at any point .get resolves to a ReferenceProperty, it will, by default, return the property that the
* ReferenceProperty refers to.
* @param in_options parameter object
*/
getValue<T>(in_ids?: string | number | Array<string | number>, in_options?: ContainerProperty_getValue_in_options_TYPE): T;
/**
* Get all sub-properties of the current property.
* Caller MUST NOT modify the properties.
* If entries include References, it will return the reference (will not automatically resolve the reference)
*/
getEntriesReadOnly(): { [key: string]: BaseProperty };
/**
* Returns the name of all the sub-properties of this property.
*/
getIds(): Array<string>;
/**
* Returns an object with all the nested values contained in this property
*/
getValues<T>(): T;
/**
* Checks whether a property with the given name exists
*/
has(in_id: string): boolean;
/**
* Expand a path returning the property or value at the end.
* @param in_path the path
* @param in_options parameter object
*/
resolvePath<T = BaseProperty>(in_path: string, in_options?: ContainerProperty_resolvePath_in_options_TYPE): T | undefined;
/**
* Given an object that mirrors a PSet Template, assigns the properties to the values
* found in that object.
* eg.
* <pre>
* Templates = {
* properties: [
* { id: 'foo', typeid: 'String' },
* { id: 'bar', properties: [{id: 'baz', typeid: 'Uint32'}] }
* ]
* }
* </pre>
*/
setValues<T>(in_values: T[] | Object): void;
/**
* Append a child property
*
* This is an internal function, called by the PropertyFactory when instantiating a template and internally by the
* NodeProperty. Adding children dynamically by the user is only allowed in the NodeProperty.
*/
protected _append(): void;
/**
* Merge child properties
*
* This is an internal function that merges children of two properties.
* This is used for extending inherited properties.
*/
protected _merge(): void;
/**
* Remove a child property
*
* This is an internal function, called internally by NodeProperty. Removing children dynamically by the user is
* only allowed in the NodeProperty.
*/
protected _remove(): void;
/**
* Traverses the property hierarchy downwards until all child properties are reached
*/
traverseDown(): string | undefined;
/**
* Traverses all static properties (properties declared in the template and not added dynamically) in the
* hierarchy below this node
*/
protected _traverseStaticProperties(): void;
}
class IndexedCollectionBaseProperty extends ContainerProperty {
/**
* A IndexedCollectionBaseProperty is the base class for indexed collections (maps and sets). It should not be used
* directly.
*/
constructor();
/**
* Removes the dirtiness flag from this property and recursively from all of its children
* @param flags The flags to clean, if none are supplied all will be removed
*/
public cleanDirty(flags?: MODIFIED_STATE_FLAGS_ENUM): void
/**
* Returns an object with all the nested values contained in this property
*/
getValues<T>(): T;
/**
* Checks whether a property or data exists at the given position.
* @param in_position index of the property
*/
has(in_position: string): boolean;
}
class ValueArrayProperty extends ArrayProperty {
/**
* An array property which stores primitive values
*/
constructor();
/**
* returns the array of primitive values.
*/
getValues<T = number[] | string[]>(): T;
/**
* Insert into the array at a given position.
* It will not overwrite the existing value, it will push it to the right.
* E.g. [1, 2, 3] .insert(1, 4) => [1, 4, 2, 3]
*/
insert<T = any>(in_position: number, in_value: T): void;
/**
* Add one or more values at the end of the array
*/
push<T = any>(values: T | T[]): number;
/**
* Removes an element of the array (or a letter in a StringProperty) and shifts remaining elements to the left
* E.g. [1, 2, 3] .remove(1) => [1, 3]
* E.g. (StringProperty) 'ABCDE' .remove(1) => 'ACDE'
*/
remove(): BaseProperty | any;
/**
* Removes the last element of the array or the last letter of a string (for StringProperty)
*/
pop(): BaseProperty | any;
/**
* Change an existing element of the array. This will overwrite an existing element.
* E.g. [1, 2, 3] .set(1, 8) => [1, 8, 3]
*/
set(in_position: number, in_value: any): void;
/**
* Sets the values of items in the array.
* If called using an array (e.g. setValues([pop1, prop2])), it will overwrite the whole array.
* If called using an object with indexes (e.g. setValues{0: prop1}), it will only overwrite the
* items at those indexes.
* For arrays of Properties, this can be used to set nested values in properties found in the array.
* For example: setValues({0: {position: {x: 2, y:3}}});
*/
setValues<T = Array<any>>(values: T): void;
/**
* Deletes all values from an array
*/
clear(): void;
/**
* Inserts the content of a given array into the array property
* It will not overwrite the existing values but push them to the right instead.
* E.g. [1, 2, 3] .insertRange(1, [9, 8]) => [1, 9, 8, 2, 3]
* @param in_offset target index
* @param in_array the array to be inserted
* @throws if in_offset is smaller than zero, larger than the length of the array or not a number.
* @throws if trying to insert a property that already has a parent.
* @throws if tyring to modify a referenced property.
*/
insertRange<T = any>(in_offset: number, in_array: T[]): void;
/**
* Removes a given number of elements from the array property (or given number of letters from a StringProperty)
* and shifts remaining values to the left.
* E.g. [1, 2, 3, 4, 5] .removeRange(1, 3) => [1, 5]
*/
removeRange(): Array<any> | Array<BaseProperty>;
/**
* Sets the array properties elements to the content of the given array
* All changed elements must already exist. This will overwrite existing elements.
* E.g. [1, 2, 3, 4, 5] .setRange(1, [7, 8]) => [1, 7, 8, 4, 5]
*/
setRange(in_offset: number, in_array: Array<any>): void;
/**
* Returns the name of all the sub-properties of this property.
* Numerical indexes from the array will be returned as strings.
* E.g. ['0', '1', '2']
*/
getIds(): Array<string>;
/**
* Gets the array element at a given index
* @param in_position the target index
* if an array is passed, elements in the array will be treated as part of a path.
* The first item in an array should be a position in the array.
* For example, .get([0,'position','x']) is the equivalent of .get(0).get('position').get('x')
* If it encounters a ReferenceProperty, .get will, by default, resolve the property it refers to.
* @param in_options parameter object
*/
get(in_position: number | Array<string | number>, in_options?: ValueArrayProperty_get_in_options_TYPE): any | BaseProperty | undefined;
getLength(): number;
/**
* Returns true if the property is a primitive type
*/
isPrimitiveType(): boolean;
}
class ArrayProperty extends ContainerProperty {
/**
* Default constructor for ArrayProperty
* @param in_params the parameters
* @param in_constructor the constructor for the array data
* @param in_primitiveType Is this an array of primitive types?
* @param in_scope The scope in which the property typeid is defined
*/
constructor(in_params: ArrayProperty_ArrayProperty_in_params_TYPE, in_constructor: object, in_primitiveType: Boolean, in_scope: string | undefined);
public get length()
/**
* Gets the array element at a given index
* @param in_position the target index
* if an array is passed, elements in the array will be treated as part of a path.
* The first item in an array should be a position in the array.
* For example, .get([0,'position','x']) is the equivalent of .get(0).get('position').get('x')
* If it encounters a ReferenceProperty, .get will, by default, resolve the property it refers to.
* @param in_options parameter object
*/
get<T=BaseProperty>(in_position: number | string | Array<string|number>, in_options?: ArrayProperty_get_in_options_TYPE): T | undefined;
/**
* Insert into the array at a given position.
* It will not overwrite the existing values, it will push them to the right.
*/
insert(in_position: number, in_value: any): void;
/**
* Add one or more values at the end of the array
*/
push(in_values: Array<any> | any): number;
/**
* Add a value at the front of the array or letters to the beginning of a string (for StringProperty)
* It can also add multiple values to an array if you pass in an array of values.
*/
unshift(in_values: Array<any> | any): number;
/**
* Removes an element of the array (or a letter in a StringProperty) and shifts remaining elements to the left
* E.g. [1, 2, 3] .remove(1) => [1, 3]
* E.g. (StringProperty) 'ABCDE' .remove(1) => 'ACDE'
*/
remove(in_position: number): BaseProperty | any;
/**
* Removes the last element of the array or the last letter of a string (for StringProperty)
*/
pop(): BaseProperty | any;
/**
* Removes an element from the front of the array or a letter from the beginning of a string (for StringProperty)
*/
shift(): BaseProperty;
/**
* Change an existing element of the array. This will overwrite an existing element.
* E.g. [1, 2, 3] .set(1, 8) => [1, 8, 3]
*/
set(in_position: number, in_value: any): void;
/**
* Deletes all values from an array
*/
clear(): void;
/**
* Inserts the content of a given array into the array property
* It will not overwrite the existing values but push them to the right instead.
* E.g. [1, 2, 3] .insertRange(1, [9, 8]) => [1, 9, 8, 2, 3]
* @param in_offset target index
* @param in_array the array to be inserted
* @throws if in_offset is smaller than zero, larger than the length of the array or not a number.
* @throws if trying to insert a property that already has a parent.
* @throws if tyring to modify a referenced property.
*/
insertRange<T=any>(in_offset: number, in_array: T[]): void;
/**
* Removes a given number of elements from the array property (or given number of letters from a StringProperty)
* and shifts remaining values to the left.
* E.g. [1, 2, 3, 4, 5] .removeRange(1, 3) => [1, 5]
*/
removeRange(in_offset: number, in_deleteCount: number): Array<any> | Array<BaseProperty>;
/**
* Sets the array properties elements to the content of the given array
* All changed elements must already exist. This will overwrite existing elements.
* E.g. [1, 2, 3, 4, 5] .setRange(1, [7, 8]) => [1, 7, 8, 4, 5]
*/
setRange(in_offset: number, in_array: Array<any>): void;
/**
* Returns an object with all the nested values contained in this property
*/
getValues<T = BaseProperty[]>(): T;
getLength(): number;
/**
* Checks whether a property or data exists at the given position.
* @param in_position index of the property
*/
has(in_position: string): boolean;
/**
* Returns the full property type identifier for the ChangeSet including the array type id, if not
* omitted by parameters
* @param in_hideCollection - if true the collection type (if applicable) will be omitted. Default to false
* @return The typeid
*/
public getFullTypeid(in_hideCollection?: boolean): string
}
class EnumArrayProperty extends ArrayProperty {
/**
* This class is a specialized version of the ArrayProperty for enums.
* Since we internally represent enums as Int32Array this is much more
* efficient and convenient. Additionally, we provide direct access
* methods to the enums in the array, e.g. .getEnumString(3) directly
* returns the enum string at position 3 of the array
* @param in_params the parameters
*/
constructor(in_params: EnumArrayProperty_EnumArrayProperty_in_params_TYPE);
/**
* inserts the content of a given array into the array property
* @param in_offset target index
* @param in_array the array to be inserted
* @throws if in_array is not an array
* @throws if in_position is not a number
* @throws if a value to be inserted is an instance of BaseProperty
* @throws if tyring to modify a referenced property.
*/
insertRange<T = any>(in_offset: number, in_array: T[]): void;
/**
* sets the content of the an enum in an enum array
*/
set(): void;
/**
* sets the content of an enum in an enum array
*/
setEnumByString(): void;
/**
* sets the array properties elements to the content of the given array
* all changed elements must already exist
*/
setRange(in_offset: number, in_array: Array<string>): void;
/**
* get the array element at a given index
*/
getEnumString(in_position: number): string;
/**
* get an array of the enum strings starting at a given index
*/
getEnumStrings(in_offset: number, in_length: number): Array<string>;
/**
* let the user to query all valid entries of an enum
*/
getValidEnumList(): { [key: string]: { value: any, annotation: any } };
/**
* Returns the full property type identifier for the ChangeSet including the enum and array type id
* @param in_hideCollection - if true the collection type (if applicable) will be omitted
* since that is not aplicable here, this param is ignored. Default to false
* @return The typeid
*/
getFullTypeid(in_hideCollection: boolean): string;
/**
* Insert into the array at a given position.
* It will not overwrite the existing values, it will push them to the right.
*/
insert(): void;
/**
* Add one or more values at the end of the array
*/
push(): number;
/**
* Removes an element of the array (or a letter in a StringProperty) and shifts remaining elements to the left
* E.g. [1, 2, 3] .remove(1) => [1, 3]
* E.g. (StringProperty) 'ABCDE' .remove(1) => 'ACDE'
*/
remove(): BaseProperty | any;
/**
* Removes the last element of the array or the last letter of a string (for StringProperty)
*/
pop(): BaseProperty | any;
/**
* Sets the values of items in the array.
* If called using an array (e.g. setValues([pop1, prop2])), it will overwrite the whole array.
* If called using an object with indexes (e.g. setValues{0: prop1}), it will only overwrite the
* items at those indexes.
* For arrays of Properties, this can be used to set nested values in properties found in the array.
* For example: setValues({0: {position: {x: 2, y:3}}});
*/
setValues(): void;
/**
* Deletes all values from an array
*/
clear(): void;
/**
* Removes a given number of elements from the array property (or given number of letters from a StringProperty)
* and shifts remaining values to the left.
* E.g. [1, 2, 3, 4, 5] .removeRange(1, 3) => [1, 5]
*/
removeRange(): Array<any> | Array<BaseProperty>;
/**
* Returns the name of all the sub-properties of this property.
* Numerical indexes from the array will be returned as strings.
* E.g. ['0', '1', '2']
*/
getIds(): Array<string>;
/**
* Gets the array element at a given index
* @param in_position the target index
* if an array is passed, elements in the array will be treated as part of a path.
* The first item in an array should be a position in the array.
* For example, .get([0,'position','x']) is the equivalent of .get(0).get('position').get('x')
* If it encounters a ReferenceProperty, .get will, by default, resolve the property it refers to.
* @param in_options parameter object
*/
get(in_position: number | Array<string | number>, in_options?: EnumArrayProperty_get_in_options_TYPE): any | BaseProperty | undefined;
getLength(): number;
}
/**
* An ArrayProperty which stores reference values
*/
class ReferenceArrayProperty extends ArrayProperty {
/**
* Returns the typeid for the target of this reference
*
* Note: This is the type that is specified in the typeid of this reference and not the actual type
* of the referenced object, which might inherit from that typeid.
*/
getReferenceTargetTypeId(): string;
/**
* Checks whether the reference is valid. This is either the case when it is empty or when the referenced
* property exists.
*/
isReferenceValid(in_position: number): boolean;
/**
* Sets the range in the array to point to the given property objects or to be equal to the given paths
*/
setRange(in_offset: number, in_array: Array<string>): void;
/**
* Insert a range which points to the given property objects into the array
*
* @param {number} in_offset - target start index
* @param {Array<property-properties.BaseProperty|undefined|String>} in_array - contains the properties to be set or
* the paths to those properties. If undefined is passed, the reference will be set to an empty string to
* indicate an empty reference.
* @throws if in_offset is smaller than zero, larger than the length of the array or not a number
* @throws if in_array is not an array
* @throws if one of the items in in_array is defined, but is not a property or a string.
*/
insertRange(): void;
/**
* returns the path value of a reference.
*/
getValue<T = string>(): T;
/**
* Returns an object with all the nested values contained in this property
*/
getValues<T = String[]>(): T;
/**
* Removes the last element of the array
*/
pop(): string;
/**
* Removes an element of the array and shift remaining elements to the left
*/
remove(): string;
/**
* Removes a given number of elements from the array and shifts remaining values to the left.
*/
removeRange(): Array<string>;
}
class StringProperty extends ValueArrayProperty {
/**
* A primitive property for a string value.
*/
constructor();
/**
* Get the string value
*/
getValue<T = string>(): T;
/**
* inserts a string starting at a position and shifts the rest of
* the String to the right. Will not overwrite existing values.
*/
insert(): void;
/**
* Adds letters to the end of the string
*/
push(): number;
/**
* returns the String to an empty string.
*/
clear(): void;
/**
* removes a given number of elements from the array property and shifts
* remaining values to the left.
*/
removeRange(): Array<any> | Array<BaseProperty>;
setValue(value: string): void;
setValues(): void;
/**
* sets the value of a string at a single index.
* For example, if you have a string of value 'AAAA' and do .set(1, 'a') => 'AaAA'
* If you pass in a string of multiple letters, it will replace the letter at in_index and insert the
* rest of you in_string. E.g. 'ABCD' .set(1, 'xy') => 'AxyCD'
*/
set(): void;
/**
* sets values in a string starting at an index.
* For example, if you have a string of Value 'AAAA' and do .setRange(1, 'aa') => AaaA
* It will set as many letters as are in in_string.
*/
setRange(): void;
/**
* get a letter at a given index
*/
get(): string;
/**
* inserts a string starting at a position and shifts the rest of the String to the right.
* Will not overwrite existing values.
* For StringProperty, insert and insertRange work the same, except that .insert
* checks that in_value is a string and .insertRange will accept an array of strings.
* @param in_position target index
* @param in_value value to be inserted
* @throws if in_position is smaller than zero, larger than the length of the string or not a number
*/
insertRange<T = string>(in_offset: number, in_array: T | T[]): void;
/**
* Removes an element of the array (or a letter in a StringProperty) and shifts remaining elements to the left
* E.g. [1, 2, 3] .remove(1) => [1, 3]
* E.g. (StringProperty) 'ABCDE' .remove(1) => 'ACDE'
*/
remove(): BaseProperty | any;
/**
* Removes the last element of the array or the last letter of a string (for StringProperty)
*/
pop(): BaseProperty | any;
/**
* Returns the name of all the sub-properties of this property.
* Numerical indexes from the array will be returned as strings.
* E.g. ['0', '1', '2']
*/
getIds(): Array<string>;
getLength(): number;
/**
* Modifies the property according to the given changeset
*/
applyChangeSet(in_changeSet: SerializedChangeSet): void;
}
class Float32ArrayProperty extends ValueArrayProperty { }
class Float64ArrayProperty extends ValueArrayProperty { }
class Uint8ArrayProperty extends ValueArrayProperty { }
class Int8ArrayProperty extends ValueArrayProperty { }
class Uint16ArrayProperty extends ValueArrayProperty { }
class Int16ArrayProperty extends ValueArrayProperty { }
class Uint32ArrayProperty extends ValueArrayProperty { }
class Int32ArrayProperty extends ValueArrayProperty { }
class Integer64ArrayProperty extends ValueArrayProperty { }
class Int64ArrayProperty extends Integer64ArrayProperty {
/**
* Inserts the content of a given array into the array property
* It will not overwrite the existing values but push them to the right instead.
* E.g. [1, 2, 3] .insertRange(1, [9, 8]) => [1, 9, 8, 2, 3]
* @param {number} in_offset target index
* @param {Array<*>} in_array the array to be inserted
* @throws if in_offset is smaller than zero, larger than the length of the array or not a number.
* @throws if trying to insert a property that already has a parent.
* @throws if tyring to modify a referenced property.
*/
insertRange<T = any>(in_offset: number, in_array: T[]): void;
/**
* Sets the array properties elements to the content of the given array
* All changed elements must already exist. This will overwrite existing elements.
* E.g. [1, 2, 3, 4, 5] .setRange(1, [7, 8]) => [1, 7, 8, 4, 5]
*/
setRange(in_offset: number, in_array: Array<number>): void;
}
class Uint64ArrayProperty extends Integer64ArrayProperty {
/**
* Inserts the content of a given array into the array property
* It will not overwrite the existing values but push them to the right instead.
* E.g. [1, 2, 3] .insertRange(1, [9, 8]) => [1, 9, 8, 2, 3]
* @param {number} in_offset target index
* @param {Array<*>} in_array the array to be inserted
* @throws if in_offset is smaller than zero, larger than the length of the array or not a number.
* @throws if trying to insert a property that already has a parent.
* @throws if tyring to modify a referenced property.
*/
insertRange<T = any>(in_offset: number, in_array: T[]): void;
/**
* Sets the array properties elements to the content of the given array
* All changed elements must already exist. This will overwrite existing elements.
* E.g. [1, 2, 3, 4, 5] .setRange(1, [7, 8]) => [1, 7, 8, 4, 5]
*/
setRange(in_offset: number, in_array: Array<number>): void;
}
class StringArrayProperty extends ValueArrayProperty { }
class BoolArrayProperty extends ValueArrayProperty { }
class BinaryProperty extends NamedProperty {
/**
* BinaryProperty encapsulates everything required for upload and download of binary objects.
* @param in_params Input parameter list.
*/
constructor(in_params: BinaryProperty_BinaryProperty_in_params_TYPE);
/**
* Removes the binary object from the external storage.
*/
delete(): Promise<any>;
/**
* Downloads the object from OSS into any class which inherits the DataSource
* base class.
*/
download(): Promise<number>;
/**
* Creates a signed url for the binary object and assigns the url to it's signedUrl property.
*/
generateSignedURL(): Promise<string>;
/**
* Gets the internal data source.
*/
getDataSource(): DataSource | undefined;
/**
* Gets the internal data store.
*/
getDatastore(): Datastore | undefined;
/**
* Gets the status of the Binary Property.
*/
getState(): BINARY_PROPERTY_STATUS_TYPE;
/**
* Gets the metadata from the datastore array.
*/
getMetadata(): NodeProperty;
/**
* Gets the parameters object from the datastore array.
*/
getParameters(): NodeProperty;
/**
* Initializes the Binary Property with the required instance items.
* @param in_params List of parameters.
*/
initialize(in_params: BinaryProperty_initialize_in_params_TYPE): Promise<any>;
/**
* Checks to see whether the BinaryProperty is in the passed in state.
*/
isStateAt(): boolean;
/**
* Synchronizes the metadata from the external storage's metadata.
*/
refreshMetadata(): Promise<any>;
/**
* Sets the internal data source.
*/
setDataSource(): void;
/**
* Uploads the binary object to specified datastore.
*/
upload(): Promise<any>;
/**
* Returns a string identifying the property
*
* If an id has been explicitly set on this property we return that one, otherwise the GUID is used.
*/
getId(): string;
/**
* Returns the GUID of this named property
* A Guid is a unique identifier for a branch, commit or repository,
* similar to a URN. Most functions in the API will us a URN but the
* Guid is used to traverse the commit graph.
*/
getGuid(): string;
/**
* Returns the name of all the sub-properties of this property.
*/
getIds(): Array<string>;
/**
* Given an object that mirrors a PSet Template, assigns the properties to the values
* found in that object.
* eg.
* <pre>
* Templates = {
* properties: [
* { id: 'foo', typeid: 'String' },
* { id: 'bar', properties: [{id: 'baz', typeid: 'Uint32'}] }
* ]
* }
* </pre>
*/
setValues(): void;
}
interface IPropertyFactory {
/**
* Add a listener for a given type of event.
*/
addListener(eventName: string, eventListener: (...args: any[]) => any): void;
/**
* Remove a listener for a given type of event. Iff a listener was removed,
* an event 'removeListener' will be emitted.
*/
removeListener(eventName: string, eventListener: (...args: any[]) => any): void;
/**
* Register template which are used to instantiate properties.
*
* In addition to json structures
* it also accepts typeids, as well as arrays of jsons ans arrays of typeids
* as arguments. IN the case of jsons, the behavior is similar to the behavior of registerLocal.
* In the case of typeids, it adds it to a list of unknown dependencies if the corresponding template
* is not known locally. The case of arrays is a a repetitive application of the scalar type.
*/
register(in_input: PropertyTemplate | object | string | any[]): void;
/**
* Recursively parses the object of the specified type and returns the created
* array of PropertySets Templates. It does the same thing as the registerFrom()
* function, but it returns the array of templates instead of registering them.
* Throws an error if any conversion error occurs.
*/
convertToTemplates(): Array<object>;
/**
* Recursively parses the object of the specified type and registers the created
* Property Sets Templates. It does the same work as the convertToTemplates()
* function, but it registers the templates for you instead of returning them.
* Throws an error if any conversion error occurs.
*/
registerFrom(in_fromType: string, in_toConvert: object): void;
/**
* Validate a template
* Check that the template is syntactically correct as well as semantically correct.
*/
validate(in_template: PropertyTemplate | PropertyTemplateType): object | undefined;
/**
* Get template based on typeid
*
* @param in_typeid the type unique identifier
*/
getTemplate(in_typeid: string): PropertyTemplate | undefined;
/**
* Create an instance of the given property typeid if there is a template registered for it.
* Otherwise, this method returns undefined.
* @param in_typeid The type unique identifier
* @param in_context The type of collection of values that the property contains.
* Accepted values are "single" (default), "array", "map" and "set".
* @param in_initialProperties A set of initial values for the PropertySet being created
* @param in_options Additional options
*/
create<T extends BaseProperty>(in_typeid: string, in_context?: string, in_initialProperties?: any, in_options?: PropertyFactory_create_in_options_TYPE): T;
/**
* Checks whether the template with typeid in_templateTypeid inherits from the template in in_baseTypeid
*
* Note: By default, this also returns true if in_templateTypeid === in_baseTypeid, since in most use cases
* the user wants to check whether a given template has all members as another template and so this is
* true for the template itself
* @param in_templateTypeid Template for which we want to check, whether in_baseTypeid is a parent
* @param in_baseTypeid The base template to check for
* @param in_options Additional options
*/
inheritsFrom(in_templateTypeid: string, in_baseTypeid: string, in_options?: PropertyFactory_inheritsFrom_in_options_TYPE): boolean;
/**
* Returns all the typeids the template inherits from (including all possible paths through multiple inheritance).
* The order of the elements in the array is unspecified.
* @param in_typeid typeid of the template
* @param in_options Additional options
*/
getAllParentsForTemplate(in_typeid: string, in_options?: PropertyFactory_getAllParentsForTemplate_in_options_TYPE): Array<string>;
/**
* Initializes the schema store.
* @param in_options the store settings.
*/
initializeSchemaStore(in_options: PropertyFactory_initializeSchemaStore_in_options_TYPE): Promise<any>;
/**
* Tries to resolve dependencies after some calls to register() have been made
*/
resolveSchemas(): Promise<any>;
/**
* Determines whether the given property is an instance of the property type corresponding to the given native
* property typeid and context.
*
* @param in_property The property to test
* @param in_primitiveTypeid - Native property typeid
* @param in_context - Context of the property
* @return True, if the property is an instance of the corresponding type
*/
instanceOf(in_property: BaseProperty, in_primitiveTypeid: string, in_context?: string): boolean;
}
var PropertyFactory: IPropertyFactory;
class Workspace extends EventEmitter {
/**
* The Workspace object encapsulates a PropertyTree to proxy function calls.
* A Workspace can be seen as a view to the state of the data at a point in time.
* It is the main interface for adding/removing/modifying high frequency data.
*/
constructor();
/**
* Initialize an empty workspace or load an existing workspace
*
* If an URN is provided in in_options.urn (either a branch URN or a commit URN),
* this URN is checked out. Otherwise, a new repository is created and the
* main branch is checked out.
* @param in_options Additional options
* @param in_options.metadata.name The human readable name of the branch.
* If not specified, it defaults to the guid.
*/
initialize(in_options?: Workspace_initialize_in_options_TYPE): Promise<BranchNode>;
/**
* Create and checkout a branch from the currently active commit
* @param in_options Additional options
* @param in_options.metadata.name The human readable name of the branch.
* If not specified, it defaults to the guid.
*/
branch(in_options?: Workspace_branch_in_options_TYPE): Promise<BranchNode>;
/**
* Commit the current pending changes. The new commit node will be
* the new head of the current branch. In detached head state, a new branch will be created.
* If the the PropertyTree is connected to the backend, the new commit will also be persisted and broadcasted.
* If SYNC_MODE is set to SYNCHRONIZE, any conflict occurred will be resolved by automatically
* rebasing the local branch and synchronizing with the remote repository.
* @param in_options Additional options
*/
commit(in_options?: Workspace_commit_in_options_TYPE): Promise<CommitNode>;
/**
* Check whether the Workspace has checked out a urn
*/
isCheckedOut(): boolean;
/**
* Return the active commit of the workspace
*/
getActiveCommit(): CommitNode | string;
/**
* get the active branch of the workspace if a branch urn was initialized/checkedout
* Or if you checked out a commit that was not the latest in its branch, this will
* return 'Repository.DETACHED_HEAD'
*/
getActiveBranch(): BranchNode | string;
/**
* Returns if the active branch is detached. This happens if you checkout a commit
* that is not at the head of its branch. Your workspace is then detached from
* the branch. You can still commit changes but they will not be commited to
* the original branch.
*/
isDetachedHead(): Boolean;
/**
* Get the Urn currently used by the workspace
* It can be a commit Urn (if the workspace was initialized with a specific commit Urn)
* or a branch Urn (if the workspace was initialized with a branch Urn)
*/
getActiveUrn(): string | undefined;
/**
* Set whether repository references should be automatically or explicitly loaded.
*/
setLazyLoadRepositoryReferences(): void;
/**
* Returns whether there are changes that have not yet been committed.
*/
hasPendingChanges(): Boolean;
/**
* Returns the ChangeSet of all pending changes.
*/
getPendingChanges(): ChangeSet;
/**
* Whether or not the workspace is up to date with the latest commit of a branch.
* Will return false if the workspace has local commits not yet pushed to the remote
* branch, or if the remote branches has commits not yet pulled to the workspace.
*/
isSynchronized(): Boolean;
/**
* Whether a workspace is destroyed
*/
isDestroyed(): Boolean;
/**
* Performs a rebase of a branch onto another branch.
*
* This will re-arrange the local commit history to be applied on top of the latest state of the branch.
* For baseProperties this will be done automatically, for more complex transformations, the user can
* supply a callback by using Workspace.setRebaseCallback
* @param in_options Rebase Options has the following members:
*/
rebase(in_options?: Workspace_rebase_in_options_TYPE): Promise<boolean>;
/**
* Resets an existing workspace to pre initialized state/ checkedout state.
*/
reset(): void;
/**
* Reverts the state of the workspace to that of a previous commit.
* The changes are applied as pending changes.
* @param in_commitUrn The urn of the commit to revertTo
* @param in_options Additional options to pass in.
*/
revertTo(in_commitUrn: string, in_options?: Workspace_revertTo_in_options_TYPE): Promise<void>;
/**
* Set the conflict handling configuration of the Workspace.
* Here you can set a global conflict handling strategy for each commit to be processed by the server.
* see Workspace.SERVER_AUTO_REBASE_MODES for more info.
* You can also set the notification callback to react to conflicts during a rebase.
* @param in_modeopt The server side conflict handling mode on each commit.
*/
setServerAutoRebaseMode(in_modeopt?: SERVER_AUTO_REBASE_MODES_TYPE, in_options?: object): void;
/**
* Set the conflict handling callback to be invoked when a conflict occurs during a rebase operation.
* @param in_callback Callback invoked for every ChangeSet that is applied
* It will be passed an Object with these members:
* * {SerializedChangeSet} transformedChangeSet - The ChangeSet that resulted from performing the
* rebase operation on the base types. This
* ChangeSet can be modified to adapt the changes
* to the changes in the onto-branch.
* * {SerializedChangeSet} originalChangeSet - The original ChangeSet before the rebase
* * {SerializedChangeSet} ontoBranchChangeSet - The changes between the common parent commit and
* the tip of the onto branch
* * {SerializedChangeSet} [currentState] - The normalized ChangeSet for the whole Repository
* before the application of the
* transformedChangeSet. It will only be supplied
* when in_options.trackState===true, since
* computing this state can be expensive.
* * {Array.<ConflictInfo>} conflicts - List with the conflicts that occurred during the
* rebase
* * {CommitNode} [commitNode] - The commit node that is rebased. This is
* undefined, when the pending changes are rebased
* @param in_options Set of options
*/
setRebaseCallback(in_callback?: Function | undefined, in_options?: Workspace_setRebaseCallback_in_options_TYPE): void;
/**
* Synchronize the workspace with remote branch. This will pull all new remote commits and push
* all new local commits.
*/
synchronize(): Promise<boolean>;
/**
* Synchronize the workspace with the latest version of the remote branch,
* but do not push local changes. Local changes will be rebased on top of the
* pulled changes.
*/
pull(): Promise<boolean>;
/**
* Set the synchronization mode of the Workspace.
* These include:
* - MANUAL: Application needs to update and push manually. Commit is local in this mode.
* - PUSH: Workspace automatically pushes local commits to the server
* - PULL: Workspace automatically pulls remote changes without pushing it's changes back
* - SYNCHRONIZE: Workspace updates and pushes automatically
* Defaults to SYNCHRONIZE
* @param syncMode The sync mode to set.
*/
setSynchronizeMode(syncMode: SYNC_MODE_TYPE): void;
/**
* Push local commits onto the remote branch. If the local workspace is not up to date
* with remote commits, it will rebase before pushing the local commits.
*/
push(): Promise<any>;
/**
* Checks out the given Repository into the supplied checkout view.
* If a commit Urn is passed in, the workspace will checkout that commit. When checking out an old
* commit, you will no longer be notified of changes to the branch. You will be in detached head
* state. If you commit new changes, a new branch will be created.
* If a branch Urn is passed in, the workspace will checkout the latest commit on that branch.
* @param in_commitOrBranchUrn URN identifying the commit or branch to check out
* @param in_options List of additional options.
*/
checkout(in_commitOrBranchUrn: string, in_options?: Workspace_checkout_in_options_TYPE): Promise<any>;
/**
* Expand a path to a given property within the PropertySet that the workspace has checked out and
* return the value at the end.
* @param in_path Path to be resolved.
* @param in_options parameter object
*/
resolvePath<T = BaseProperty>(in_path: string, in_options?: Workspace_resolvePath_in_options_TYPE): T | undefined;
/**
* Delays notifications until popModifiedEventScope has been called the same number of times as
* pushModifiedEventScope.
* For example, calling pushModifiedEventScope will stop the application from running the
* on('modified') callback until popModifiedEventScope is called.
*/
pushModifiedEventScope(): void;
/**
* Reenables notifications when popModifiedEventScope has been called the same number of times as
* pushModifiedEventScope.
* For example, calling pushModifiedEventScope will stop the application from running the
* on('modified') callback until popModifiedEventScope is called.
*/
popModifiedEventScope(): void;
/**
* Insert a property at the root of the PropertySet that the workspace has checked out.
* NOTE: This will throw an error if the workspace is not at the HEAD of the checked out branch
* or if the repository hasn't been checked out yet.
*/
insert(in_id: string, in_property: BaseProperty): void;
/**
* Remove a property from the root of the PropertySet that the workspace has checked out.
* NOTE: This will throw an error if the workspace is not at the HEAD of the checked out branch
* or if the repository hasn't been checked out yet.
*/
remove(in_property: string | BaseProperty): void;
/**
* Returns the name of all the properties at the root of the PropertySet that
* the workspace has checked out.
*/
getIds(): Array<string>;
/**
* Returns the property having the given id at the root of the PropertySet
* that the workspace has checked out.
* @param in_ids the ID of the property or an array of IDs
* if an array is passed, the .get function will be performed on each id in sequence
* for example .get(['position','x']) is equivalent to .get('position').get('x').
* If .get resolves to a ReferenceProperty, it will return the property that the ReferenceProperty
* refers to.
* @param in_options parameter object
*/
get<T extends BaseProperty>(in_ids: string | number | Array<string | number>, in_options?: Workspace_get_in_options_TYPE): T | undefined;
/**
* Checks whether a property with the given id exists at the root of the
* PropertySet that the workspace has checked out.
*/
has(in_id: string): boolean;
/**
* Get all properties at the root of the PropertySet that the workspace has checked out.
* Caller MUST NOT modify the properties.
*/
getEntriesReadOnly(): BaseProperty | null;
/**
* Returns the number of local commits that have not yet been pushed to the remote branch.
* The count can be brought back to zero by calling .push() or .synchronize()
* If there is no remote branch, will return 0.
*/
getPushCount(): number;
/**
* Returns the number of remote commits that have not yet been pulled to the local repository.
* the count can be brought to zero by calling .pull() or .synchronize()
* If no remote branch exists, will return 0.
*/
getPullCount(): number;
/**
* Get the root property of the workspace. This is effectively the PropertySet that the workspace has checked out.
*/
getRoot(): NodeProperty;
/**
* Checks if there is a template with a specific name loaded in the workspace, returns it if found.
* To get all the loaded templates, pass a null name.
*/
getTemplate(in_name?: string | null): { [index: string]: PropertyTemplateType } | PropertyTemplateType | undefined;
/**
* Leaves the branch if working on an active branch then destroys the workspace
* NOTE: The workspace will no longer be usable after calling this function
*/
destroy(): Promise<any>;
/**
* Generate a human-readable representation of the workspace and all of its objects
*/
prettyPrint(printFn?: (...args: any[]) => any): void;
/**
* Change the AutoUpload flag state. This flag is used to indicate whether to upload binary
* properties on commit and is set to true by default.
*/
setAutoUpload(): boolean;
SYNC_MODE: SYNC_MODE_ENUM;
static REBASE_CALLBACK_NOTIFICATION_MODES: REBASE_CALLBACK_NOTIFICATION_MODES_ENUM;
SERVER_AUTO_REBASE_MODES: SERVER_AUTO_REBASE_MODES_ENUM;
}
class BranchNode {
/**
* Node representing a branch in the commit graph
* @param in_params List of branch meta data
* @param in_headNode The head node of the branch
*/
constructor(in_params: BranchNode_BranchNode_in_params_TYPE, in_headNode: CommitNode);
/**
* Returns the name of the branch. If no name was specified, returns a unique id.
*/
getName(): string;
/**
* Check whether this branch is remote
*/
isRemoteBranch(): boolean;
/**
* Get the remote branch
*/
getRemoteBranch(): BranchNode | undefined;
/**
* Get the local branch
*/
getLocalBranch(): BranchNode | undefined;
/**
* Return the Guid of the branch
* A Guid is a unique identifier for a branch, commit or repository,
* similar to a URN. Most functions in the API will us a URN but the
* Guid is used to traverse the commit graph.
*/
getGuid(): string;
/**
* Gets the URN of this branch
*/
getUrn(): string;
/**
* Returns the head of the branch
*/
getHead(): CommitNode;
/**
* Comparison function between this branch node and another one to check
* for equality.
*/
isEqual(): boolean;
/**
* Returns true if the branch is currently not tracking the server branch, false otherwise.
*/
isUntracked(): boolean;
/**
* Returns true if the branch is currently in the process of tracking the server branch, false otherwise.
*/
isTracking(): boolean;
/**
* Returns true if the server branch is currently properly tracked, false otherwise.
*/
isTracked(): boolean;
/**
* Returns the tracking state as text, either 'UNTRACKED', 'TRACKING' or 'TRACKED'.
*/
getTrackState(): string;
/**
* Returns the local commits that have been pushed to the server but haven't been confirmed yet.
* If there is no remote branch, will return an empty array.
*/
getCommitsInFlight(): Array<CommitNode>;
/**
* Returns the remote commits that have not yet been pulled to the local repository.
* If no remote branch exists, will return an empty array.
*/
getCommitsToPull(): Array<CommitNode>;
/**
* Returns the local commits that have not yet been pushed to the remote branch.
* If there is no remote branch, will return an empty array.
*/
getCommitsToPush(): Array<CommitNode>;
}
class CommitNode {
/**
* A commit node in the commit graph
* The commit node stores the bits of information that are used to represent a
* particular set of changes with regards to its input (the parent).
* Change Sets are the data stored by these nodes but there is no logic around
* the data itself, only the connectivity between N parent nodes to N children nodes.
* These nodes are used to build the topology for the change graph, but no knowledge
* about data is kept here.
*
* A Commit node has N inputs, and N outputs. Change sets are retrieved from the
* node itself.
*
* ____________________
* | CommitNode |
* | |
* ---i [parent] |
* | |
* | |
* | |
* | [children] o----
* |____________________|
*/
constructor();
/**
* Get metadata on this node with a key
*/
getMetadata(): any;
/**
* Copies the meta data from another node.
*/
copyMetaDataFromNode(): void;
/**
* Gets the URN of this commit
*/
getUrn(): string;
/**
* Get a reference to the guid of the old commit that was used to generate this rebased commit
*/
getRebaseParentGuid(): string;
/**
* Returns the primary parent of the commit.
*/
getFirstParent(): RootProperty | CommitNode | undefined;
/**
* Return all the parent nodes of the commit, starting with the primary parent.
*/
getParents(): Array<RootProperty | CommitNode>;
/**
* Return all the children nodes of the commit.
*/
getChildren(): Array<CommitNode>;
/**
* Gets the GUID of this commit
* A Guid is a unique identifier for a branch, commit or repository,
* similar to a URN. Most functions in the API will us a URN but the
* Guid is used to traverse the commit graph.
*/
getGuid(): string;
/**
* Gets the GUID this commit had when it was last pushed to the server (valid only for local commits).
*/
getGuidOnLastPush(): string | undefined;
/**
* Returns the GUIDs this commit had each time it was pushed to the server (valid only for local commits).
*/
getGuidsOnPush(): Array<string> | undefined;
/**
* Comparison function between this commit node and another one to check
* for equality.
*/
isEqual(): boolean;
/**
* Return the changeset data of a commit node.
*/
getChangeSetReadOnly(): SerializedChangeSet;
/**
* A commit is normalized if the commit node does not contain a ChangeSet relative
* to its parent, but actually a full serialization as a normalized ChangeSet.
* (A normalized ChangeSet is a ChangeSet that only contains insert operations as
* well as base property assignments. So all children definitions and collections
* only consist of insert operations. Insert operations on strings and arrays
* MUST insert only one range starting at position 0.)
*/
isNormalized(): boolean;
/**
* Returns the path from the supplied parent commit to this node
*
* Note: This function assumes that the given commit is direct parent (e.g. not in a branch of a merge commit,
* but a direct ancestor, as returned by getFirstParent).
*
* @param in_parentCommit - The node from which the path is computed.
* If a function is provided, it is used
* as predicate to determine whether the
* node is the parent.
* @param in_includeParent - Should the parent node itself be
* included in the supplied path?
*
* @return The nodes on the path from the supplied parent
*/
_getPathFromParentCommit(in_parentCommit: CommitNode, in_includeParent?: boolean): Array<CommitNode>;
}
class MapProperty extends IndexedCollectionBaseProperty {
/**
* A MapProperty is a collection class that can contain an dictionary that maps from strings to properties.
*/
constructor();
/**
* Returns the full property type identifier for the ChangeSet including the map type id
* @param in_hideCollection - if true the collection type (if applicable) will be omitted
* since that is not aplicable here, this param is ignored. Default to false
* @return The typeid
*/
getFullTypeid(in_hideCollection: boolean): string;
/**
* Inserts a property or value into the map
*
* Note: This will trigger an exception when this key already exists in the map. If you want to overwrite
* existing entries you can use the set function.
*/
insert(in_key: string, in_property: BaseProperty): void;
/**
* Removes the entry with the given key from the map
*/
remove(in_key: string): any;
/**
* deprecated - replaced by set
*/
setValue(): void;
/**
* set all the values
*/
setValues<T>(in_values: Object): void;
/**
* Sets the entry with the given key to the property passed in
*
* Note: this will overwrite an already existing value
*/
set(in_key: string, in_value: any): void;
/**
* Checks whether an entry with the given name exists
* @param in_id Name of the property
*/
has(in_id: string): boolean;
/**
* Returns all entries of the map as an array.
*
* NOTE: This function creates a copy and thus is less efficient as getEntriesReadOnly.
*/
getAsArray(): Array<BaseProperty | any>;
/**
* Returns all keys found in the map
*
* NOTE: This function creates a copy and thus is less efficient as getEntriesReadOnly.
*/
getIds(): Array<string>;
/**
* Deletes all values from the Map
*/
clear(): void;
getAbsolutePath(): string;
}
class ReferenceMapProperty extends StringMapProperty {
/**
* A StringMapProperty which stores reference values
*/
constructor();
/**
* Returns the typeid for the target of this reference
*
* Note: This is the type that is specified in the typeid of this reference and not the actual type
* of the referenced object, which might inherit from that typeid.
*/
getReferenceTargetTypeId(): string;
/**
* Removes the entry with the given key from the map
*/
remove(key: string): string;
/**
* Sets the reference to point to the given property object or to be equal to the given path string.
*/
set(): void;
/**
* Inserts the reference that points to the given property object or a given path string.
*/
insert(key: string, value: string | BaseProperty | undefined): void;
/**
* Checks whether the reference is valid. This is either the case when it is empty or when the referenced
* property exists.
*/
isReferenceValid(in_key: string): boolean;
/**
* Sets the entry with the given key to the value passed in.
*/
setValue(): void;
/**
* Returns the string value stored in the map
* @param in_key the key of the reference
* Returns: the path string
*/
getValue<T = string>(in_key: string): T;
/**
* Given an object that mirrors a PSet Template, assigns the properties to the values
* found in that object.
* eg.
* <pre>
* Templates = {
* properties: [
* { id: 'foo', typeid: 'String' },
* { id: 'bar', properties: [{id: 'baz', typeid: 'Uint32'}] }
* ]
* }
* </pre>
*/
setValues(): void;
/**
* Returns all entries of the map as an array.
*
* NOTE: This function creates a copy and thus is less efficient as getEntriesReadOnly.
*/
getAsArray(): Array<BaseProperty | any>;
/**
* Returns all keys found in the map
*
* NOTE: This function creates a copy and thus is less efficient as getEntriesReadOnly.
*/
getIds(): Array<string>;
/**
* Deletes all values from the Map
*/
clear(): void;
getAbsolutePath(): string;
}
class ValueMapProperty extends MapProperty {
/**
* A ValueMapProperty is a collection class that can contain an dictionary that maps from strings to primitive types.
*/
constructor();
/**
* Inserts a value into the map. Using insert with a key that already exists will throw an error.
*/
insert(in_key: string, in_value: any): void;
/**
* Sets the value of a property into the map.
*/
set(in_key: string, in_value: any): void;
/**
* Given an object that mirrors a PSet Template, assigns the properties to the values
* found in that object.
* eg.
* <pre>
* Templates = {
* properties: [
* { id: 'foo', typeid: 'String' },
* { id: 'bar', properties: [{id: 'baz', typeid: 'Uint32'}] }
* ]
* }
* </pre>
*/
setValues<T>(in_values: Object): void;
/**
* Removes the entry with the given key from the map
*/
remove(key: string): any;
/**
* deprecated - replaced by set
*/
setValue(): void;
/**
* Returns all entries of the map as an array.
*
* NOTE: This function creates a copy and thus is less efficient as getEntriesReadOnly.
*/
getAsArray(): Array<BaseProperty | any>;
/**
* Returns all keys found in the map
*
* NOTE: This function creates a copy and thus is less efficient as getEntriesReadOnly.
*/
getIds(): Array<string>;
/**
* Deletes all values from the Map
*/
clear(): void;
}
class Float32MapProperty extends ValueMapProperty { }
class Float64MapProperty extends ValueMapProperty { }
class Uint32MapProperty extends ValueMapProperty { }
class Uint16MapProperty extends ValueMapProperty { }
class Uint8MapProperty extends ValueMapProperty { }
class Int32MapProperty extends ValueMapProperty { }
class Integer64MapProperty extends ValueMapProperty {
// TODO: Add Int64 | Uint64 to the accepted values
/**
* Sets the entry with the given key to the value passed in
*
* Note: this will overwrite an already existing value
*
* @param in_key The key under which the entry is stored
* @param in_value The value or property to store in the map
*/
set(key: string, value: string | number): void;
}
class Int64MapProperty extends Integer64MapProperty { }
class Uint64MapProperty extends Integer64MapProperty { }
class Int16MapProperty extends ValueMapProperty { }
class Int8MapProperty extends ValueMapProperty { }
class StringMapProperty extends ValueMapProperty { }
class BoolMapProperty extends ValueMapProperty { }
class NamedNodeProperty extends NodeProperty {
/**
* A NamedNodeProperty is a NodeProperty that has a GUID which unique identifies the property object.
* This makes it possible to store it in a set collection.
* @param in_params List of parameters
*/
constructor(in_params: NamedNodeProperty_NamedNodeProperty_in_params_TYPE);
/**
* Appends a property
*/
insert(): void;
/**
* Removes the given property
*/
remove(): BaseProperty;
getGuid: NamedProperty['getGuid'];
getId: NamedProperty['getId'];
share: NamedProperty['share'];
unshare: NamedProperty['unshare'];
getShareInfo: NamedProperty['getShareInfo'];
}
class NodeProperty extends IndexedCollectionBaseProperty {
/**
* A property object that allows to add child properties dynamically.
*/
constructor();
isDynamic(): boolean;
/**
* Appends a property
*/
insert(in_id: string, in_property: BaseProperty): void;
/**
* Removes the given property
*/
remove(in_property: string | BaseProperty): BaseProperty;
/**
* Removes all dynamic children
*/
clear(): void;
/**
* Stores the information to which CheckedOutRepositoryInfo object this root property belongs.
* Note: these functions should only be used internally (within the PropertySets library)
*/
protected _setCheckedOutRepositoryInfo(): void;
/**
* Stores the information to which CheckedOutRepositoryInfo object this root property belongs.
* Note: these functions should only be used internally (within the PropertySets library)
*/
protected _getCheckedOutRepositoryInfo(): CheckedOutRepositoryInfo | undefined;
/**
* Returns the name of all the static sub-properties of this property.
*/
getStaticIds(): Array<string>;
/**
* Returns the name of all the dynamic sub-properties of this property.
*/
getDynamicIds(): Array<string>;
/**
* Indicate that all static members have been added to the property
*
* This function is invoked by the PropertyFactory once all static members have been added to the template
*/
protected _signalAllStaticMembersHaveBeenAdded(): void;
/**
* Returns the name of all the sub-properties of this property.
*/
getIds(): Array<string>;
/**
* Cleans the cache of static children per typeid. Calling this should only be necessary if a template has been
* reregistered.
*/
protected _cleanStaticChildrenCache(): void;
}
class SetProperty extends IndexedCollectionBaseProperty {
/**
* A SetProperty is a collection class that can contain an unordered set of properties. These properties
* must derive from NamedProperty and their URN is used to identify them within the set.
*/
constructor();
/**
* Returns the path segment for a child
* @param in_childNode - The child for which the path is returned
* @return The path segment to resolve the child property under this property
*/
protected _getPathSegmentForChildNode(in_childNode: NamedProperty): string;
/**
* Inserts a property into the set
*/
insert(in_property: NamedProperty): void;
/**
* Adds a property to the set
* - If the property's key exists, the entry is replaced with new one.
* - If the property's key does not exist, the property is appended.*
*/
set(): void;
/**
* Removes the given property from the set
*/
remove(in_entry: NamedProperty | string): NamedProperty;
/**
* Returns the name of all the sub-properties of this property.
*/
getIds(): Array<string>;
/**
* Given an object that mirrors a PSet Template, assigns the properties to the values
* found in that object.
* eg.
* <pre>
* Templates = {
* properties: [
* { id: 'foo', typeid: 'String' },
* { id: 'bar', properties: [{id: 'baz', typeid: 'Uint32'}] }
* ]
* }
* </pre>
*/
setValues(): void;
/**
* Returns all entries of the set as an array.
*
* NOTE: This function creates a copy and thus is less efficient as getEntriesReadOnly.
*/
getAsArray(): Array<NamedProperty>;
/**
* Delete all values from Set
*/
clear(): void;
/**
* Returns the full property type identifier for the ChangeSet including the set type id
* @param in_hideCollection - if true the collection type (if applicable) will be omitted
* since that is not aplicable here, this param is ignored. Default to false
* @return The typeid
*/
getFullTypeid(in_hideCollection: boolean): string;
}
class PropertyTemplate {
/**
* Constructor for creating a PropertyTemplate based on the given parameters.
* @param in_params List of parameters
*/
constructor(in_params: PropertyTemplateType);
/**
* Clones the PropertyTemplate
*/
clone(): PropertyTemplate;
/**
* Return the version number of the template.
*/
getVersion(): string;
/**
* Return the serialized parameters passed in the constructor
*/
serialize(): PropertyTemplateType;
/**
* Return the serialized parameters passed in the constructor, in a template canonical form
*/
serializeCanonical(): object;
/**
* Return the typeid of the template without the version number
* i.e. autodesk.core:color instead of autodesk.core:color-1.0.0
*/
getTypeidWithoutVersion(): string;
/**
* Determines if the argument is a template structure
*/
public isTemplate(): Boolean;
/**
* Extracts typeids directly referred to in a template
*/
public extractDependencies(): Array<any>;
constants: any[];
context: string;
id: string;
inherits: string[];
annotation: { [key: string]: string };
properties: any[];
typeid: string;
}
class BaseProperty {
/**
* Default constructor for BaseProperty
* @param in_params List of parameters
*/
constructor(in_params: BaseProperty_BaseProperty_in_params_TYPE);
getTypeid(): string;
getContext(): string;
/**
* Returns the full property type identifier for the ChangeSet including the enum type id
* @param in_hideCollection if true the collection type (if applicable) will be omitted
* since that is not aplicable here, this param is ignored. Default to false
* @return The typeid
*/
getFullTypeid(in_hideCollection?: boolean): string;
/**
* Is this property the root of the property set tree?
*/
isRoot(): boolean;
/**
* Is this property the ancestor of in_otherProperty?
* Note: A property is not considered an ancestor of itself
*/
isAncestorOf(): boolean;
/**
* Is this property the descendant of in_otherProperty?
* Note: A property is not considered a descendant of itself
*/
isDescendantOf(): boolean;
/**
* Get the parent of this property
*/
getParent(): BaseProperty | undefined;
/**
* checks whether the property is dynamic (only properties inherting from NodeProperty are)
*/
isDynamic(): boolean;
/**
* Modifies the property according to the given changeset
*/
applyChangeSet(in_changeSet: SerializedChangeSet): void;
/**
* Removes the dirtiness flag from this property and recursively from all of its children
*/
public cleanDirty(flags?: MODIFIED_STATE_FLAGS_ENUM): void
/**
* Indicates that the property has been modified and a corresponding modified call has not yet been sent to the
* application for runtime scene updates.
*/
isDirty(): boolean;
/**
* The property has pending changes in the current ChangeSet.
*/
hasPendingChanges(): boolean;
/**
* Returns the ChangeSet of all sub-properties
*/
getPendingChanges(): ChangeSet;
/**
* Get the id of this property
*/
getId(): string | undefined;
/**
* Sets the checkoutview.
*/
protected _setCheckoutView(): void;
/**
* Returns the Workspace
*/
getWorkspace(): any | undefined;
/**
* Returns the path segment for a child
* @param in_childNode - The child for which the path is returned
* @return The path segment to resolve the child property under this property
*/
protected _getPathSegmentForChildNode(in_childNode: BaseProperty): string;
/**
* Resolves a direct child node based on the given path segment
*
* @param in_segment The path segment to resolve
* @param in_segmentType - The type of segment in the tokenized path
*
* @return The child property that has been resolved
* @protected
*/
protected _resolvePathSegment(in_segment: string, in_segmentType: TOKEN_TYPES_TYPE): BaseProperty | undefined;
/**
* Return a clone of this property
*/
clone(): BaseProperty;
/**
* Returns true if the property is a primitive type
*/
isPrimitiveType(): boolean;
/**
* Repeatedly calls back the given function with human-readable string representations
* of the property and of its sub-properties. By default it logs to the console.
* If printFct is not a function, it will default to console.log
*/
prettyPrint(printFn?: (...args: any[]) => any): void;
/**
* Returns the path from the given from_property to this node if such a path exists.
* If more than one paths exist (as might be the case with multiple repository references
* pointing to the same repository), it will return the first valid path found.
* For example, if you have this structure:
* <code>prop1
* --prop2
* ----prop3</code>
* and call: <code>prop1.getRelativePath(prop3);</code>
* You will get the path from prop3 to prop1, which would be '../../'
*/
getRelativePath(from_property: BaseProperty): string;
/**
* Returns the path from the root of the workspace to this node
* (including a slash at the beginning)
*/
getAbsolutePath(): string;
/**
* Traverses the property hierarchy upwards until the a node without parent is reached
*/
traverseUp(): string | undefined;
/**
* Returns the root of the property hierarchy
*/
getRoot(): NodeProperty;
/**
* Deserialize takes a currently existing property and sets it to the hierarchy described in the normalized
* ChangeSet passed as parameter. It will return a ChangeSet that describes the difference between the
* current state of the property and the passed in normalized property
*/
deserialize(in_serializedObj: SerializedChangeSet): SerializedChangeSet;
/**
* Serialize the property
* @param in_options Options for the serialization
*/
serialize(in_options?: BaseProperty_serialize_in_options_TYPE): object;
/**
* Indicate that all static members have been added to the property
*
* This function is invoked by the PropertyFactory once all static members have been added to the template
*/
/**
* Removes the dirtiness flag from this property and recursively from all of its children
*/
cleanDirty(): void;
protected _signalAllStaticMembersHaveBeenAdded(): void;
static REFERENCE_RESOLUTION: REFERENCE_RESOLUTION_ENUM;
static MODIFIED_STATE_FLAGS: MODIFIED_STATE_FLAGS_ENUM;
static PATH_TOKENS: PATH_TOKENS_ENUM;
value: any;
}
class NamedProperty extends ContainerProperty {
/**
* A NamedProperty has a URN which uniquely identifies the property object. This makes it possible to store it in a
* set collection.
* @param in_params List of parameters
*/
constructor(in_params: NamedProperty_NamedProperty_in_params_TYPE);
/**
* Returns the GUID of this named property
* A Guid is a unique identifier for a branch, commit or repository,
* similar to a URN. Most functions in the API will us a URN but the
* Guid is used to traverse the commit graph.
*/
getGuid(): string;
/**
* Returns a string identifying the property
* If an id has been explicitly set on this property we return that one, otherwise the GUID is used.
* @return String identifying the property
*/
getId(): string;
/**
* Share property with given subject(s)
*/
share(permissions: NamedProperty_share_permission_TYPE, options?: NamedProperty_share_options_TYPE): Promise<any>;
/**
* Unshare property with given subject(s)
*/
unshare(permissions: NamedProperty_unshare_permission_TYPE, options?: NamedProperty_unshare_options_TYPE): Promise<any>;
/**
* Get share info for the property
*/
getShareInfo(): Promise<any>;
}
class ReferenceProperty extends ValueProperty {
/**
* This class serves as a view to read, write and listen to changes in an
* object's value field. To do this we simply keep a pointer to the object and
* it's associated data field that we are interested in. If no data field is
* present this property will have an undefined value.
*/
constructor();
/**
* Returns the typeid for the target of this reference
*
* Note: This is the type that is specified in the typeid of this reference and not the actual type
* of the referenced object, which might inherit from that typeid.
*/
getReferenceTargetTypeId(): string;
/**
* Resolves the referenced property
* @param in_ids the ID of the property or an array of IDs
* if an array is passed, the .get function will be performed on each id in sequence
* for example .get(['position','x']) is equivalent to .get('position').get('x').
* If .get resolves to a ReferenceProperty, it will return the property that the ReferenceProperty
* refers to.
* @param in_options parameter object
*/
get<T extends BaseProperty>(in_ids?: string | number | Array<string | number>, in_options?: ReferenceProperty_get_in_options_TYPE): T | undefined;
/**
* Expand a path returning the value or property at the end.
* @param in_path the path
* @param in_options parameter object
*/
resolvePath<T = BaseProperty>(in_path: string, in_options?: ReferenceProperty_resolvePath_in_options_TYPE): T | undefined;
/**
* Sets the reference to point to the given property object
*/
set(in_property?: BaseProperty): void;
/**
* Checks whether the reference is valid. This is either the case when it is empty or when the referenced
* property exists.
*/
isReferenceValid(): boolean;
/**
* Evaluates Reference properties as primitives.
* @return true since Reference properties are primitives.
*/
isPrimitiveType(): boolean;
}
class RepositoryReferenceProperty extends ContainerProperty {
/**
* A RepositoryReferenceProperty is used to manage references in between repositories. It stores the
* reference to a commit in a separate repository (by storing a repository, branch and commit GUID).
* Adding such a property will trigger loading the corresponding sub-tree into the view.
*
* // TODO: Should this inherit from a NamedProperty?
* @param in_params List of parameters
*/
constructor(in_params: RepositoryReferenceProperty_RepositoryReferenceProperty_in_params_TYPE);
/**
* This method enable write on repository reference by turning then into workspace.
* Workspace method are then available by calling .getReferencedWorkspace().
* This will automatically move you to the head of the branch.
* It will then follow the branch.
* This change is persisted through the followBranch property.
*/
enableWrite(): Promise<any>;
/**
* This method disable write on repository reference.
* This change is persisted through the followBranch property.
*/
disableWrite(): void; getReferencedWorkspace(): Workspace;
/**
* Returns the state of this RepositoryReferenceProperty
*/
getState(): STATE_TYPE;
/**
* Load a reference
*/
load(): void;
/**
* Returns the root property of the referenced repository
*/
getReferencedRepositoryRoot(): NodeProperty;
/**
* Checks whether the referenced properties are available
*/
areReferencesAvailable(): Boolean;
/**
* Update the reference and set it to the given commit, branch and repository
* TODO: Can we also provide automatic updates for the repository when this property is already in a repository?
*/
updateReference(): void;
/**
* Returns an object with all the nested values contained in this property
*/
getValues<T = object>(): T;
static STATE: STATE_TYPE;
}
/**
* A primitive property for a boolean value
*/
class BoolProperty extends ValueProperty<boolean> { }
class EnumProperty extends Int32Property {
/**
* A primitive property for enums.
*/
constructor();
/**
* Returns the current enum string
*/
getEnumString(): string;
/**
* Sets the (internal, integer) value of the property
*/
setValue(): void;
/**
* Sets the property by an enum string
*/
setEnumByString(): void;
/**
* Returns the full property type identifier for the ChangeSet including the enum type id
* @param in_hideCollection - if true the collection type (if applicable) will be omitted
* since that is not aplicable here, this param is ignored. Default to false
* @return The typeid
*/
getFullTypeid(in_hideCollection: boolean): string;
/**
* let the user to query all valid entries of an enum
*/
getValidEnumList(): { [key: string]: { value: any, annotation: any } };
/**
* Returns true if the property is a primitive type
*/
isPrimitiveType(): boolean;
}
/**
* A primitive property for a 32 bit floating point value.
*/
class Float32Property extends ValueProperty<number> { }
/**
* A primitive property for a 64 bit floating point value.
*/
class Float64Property extends ValueProperty<number> { }
/**
* A primitive property for an signed 8 bit integer value.
*/
class Int8Property extends ValueProperty<number> { }
/**
* A primitive property for an signed 16 bit integer value.
*/
class Int16Property extends ValueProperty<number> { }
/**
* A primitive property for an signed 32 bit integer value.
*/
class Int32Property extends ValueProperty<number> { }
class Integer64Property extends ValueProperty<number> {
/**
* A primitive property base class for big integer values.
*/
constructor();
getValueHigh(): number;
getValueLow(): number;
setValueHigh(value: number): boolean;
setValueLow(value: number): boolean;
/**
* The toString() method returns a string representing the specified Integer64 object.
*/
toString(): string;
/**
* The Integer64.fromString() method parses a string argument updates object's lower and higher 32 bit integer parts.
*/
fromString(): void;
}
/**
* A primitive property class for big signed integer values.
*/
class Int64Property extends Integer64Property {
setValue(): void;
}
/**
* A primitive property class for big unsingned integer values.
*/
class Uint64Property extends Integer64Property {
setValue(): void;
}
/**
* A primitive property for an unsigned 8 bit integer value.
*/
class Uint8Property extends ValueProperty<number> { }
/**
* A primitive property for an unsigned 16 bit integer value.
*/
class Uint16Property extends ValueProperty<number> { }
/**
* A primitive property for an unsigned 32 bit integer value.
*/
class Uint32Property extends ValueProperty<number> { }
class ValueProperty<T = any> extends BaseProperty {
/**
* This class serves as a view to read, write and listen to changes in an
* object's value field. To do this we simply keep a pointer to the object and
* its associated data field that we are interested in. If no data field is
* present this property will fail constructing.
* @param in_params the parameters
*/
constructor(in_params: ValueProperty_ValueProperty_in_params_TYPE);
/**
* returns the current value of ValueProperty
*/
getValue(): T;
setValue(in_value: T): void;
}
class CheckedOutRepositoryInfo {
/**
* Data-structure that contains information about a specific check out state for a given repository
*/
constructor();
}
class ScopeProperty {
/**
* Dummy property used to return the scope to the underlying properties
* @param in_params BaseProperty parameters
*/
constructor(in_params: ScopeProperty_ScopeProperty_in_params_TYPE);
}
class _createTemplateValidator {
/**
* Creates an instance of the TemplateValidator
*/
constructor();
}
}
export = PROPERTY_TREE_NS;
} | the_stack |
import { NoPos, Position, SrcFileSet } from "./pos"
import { ErrorCode } from "./error"
import { Diagnostic, Diag, DiagKind } from "./diag"
import { Scanner, Mode as ScanMode } from "./scanner"
import { Parser } from "./parser"
import { PkgBinder } from "./bind"
import { TypeSet } from "./typeset"
import { Universe } from "./universe"
import { TypeResolver } from "./resolve"
import { token } from "./token"
import { serialize } from "./util"
import * as ast from "./ast"
import * as utf8 from "./utf8"
import * as ssa from "./ir/ssa"
import { Config } from "./ir/config"
import { IRBuilder, IRBuilderFlags } from "./ir/builder"
import { runPassesDev as runIRPasses } from "./ir/passes"
import { printir } from "./ir/repr"
import { archs } from "./ir/arch"
import { ArchInfo } from "./ir/arch_info"
// input source text is either UTF-8 encoded data or a JavaScript string
export type SourceData = Uint8Array | string
// input source is either a filename with data or just a filename
export type Source = [string,SourceData]|string
// called when diagnostics is emitted.
// note that you can also retrieve diagnostics with getDiagnostics()
export type DiagnosticCallback = (d :Diagnostic)=>void
// ScanCallback is called with the current token. Returning false stops scanning.
// Any data associated with the token can be read from the third argument; s,
// which is the scanner itself.
export type ScanCallback = (t :token, s :Scanner)=>false|any
// Scanning mode
export { ScanMode }
// Diagnostic describes an issue or notice regarding source code
// DiagnosticKind is the kind, or "level", of diagnostic (e.g. "error" or "info")
export { Diagnostic, DiagKind as DiagnosticKind }
// ast describes the Co syntax as an Abstract Syntax Tree
export { ast }
// IRBuilderFlags
export { IRBuilderFlags }
// CompilerHost represents the full suite of functionality for parsing and compiling programs.
export interface CompilerHost {
readonly fs :FileSystem
scanFile(filename :string, f: ScanCallback, cb? :DiagnosticCallback, mode? :ScanMode) :Promise<void>
scanFile(filename :string, source :SourceData, f: ScanCallback, cb? :DiagnosticCallback, mode? :ScanMode) :void
parseFile(filename :string, gscope? :ast.Scope, cb? :DiagnosticCallback, mode? :ScanMode) :Promise<ast.File>
parseFile(filename :string, source :SourceData, gscope? :ast.Scope, cb? :DiagnosticCallback, mode? :ScanMode) :ast.File
parsePackage(name :string, sources :Iterable<Source>, cb? :DiagnosticCallback, mode? :ScanMode) :Promise<ast.Package>
compilePackage(pkg :ast.Package, target :string|Config, cb? :DiagnosticCallback, flags? :IRBuilderFlags) :ssa.Pkg
//[DEBUG only]
// traceInDebugMode controls output of trace-level messages in DEBUG builds.
// When left undefined, the bult-in default is used.
traceInDebugMode? :bool
}
// FileSystem represents the interface to some underlying file system.
// This could be an "actual" file system or a virtual one.
export interface FileSystem {
readfile(path :string) :Promise<Uint8Array>
readfileSync(path :string) :Uint8Array
existsSync(path :string) :bool
readdirSync(path :string) :string[]
}
// Create a new compiler host
export function createCompilerHost(fs? :FileSystem) :CompilerHost {
return new CHost(fs || getDefaultFileSystem())
}
// List of names of supported target architectures
export function getSupportedTargets() :string[] {
return Array.from(archs.keys())
}
// Create a target configuration to be used with compilation
export function createTargetConfig(name :string, props?: Partial<Config>) :Config {
return new Config(name, props)
}
// Retrieve read-only target information
export function getTargetInfo(name :string) :ArchInfo {
let a = archs.get(name)
if (!a) { throw new Error(`unknown target ${JSON.stringify(name)}`) }
return a
}
// Access diagnostics produced during scanning, parsing and binding
export function getDiagnostics(n :ast.Node) :Diagnostic[] {
return (n as any)[diagKey] || []
}
// Access the number of errors encountered during scanning, parsing and binding.
// Useful as a check after parsing to know if an AST is valid.
export function getErrorCount(n :ast.Node) :int {
return (n as any)[errcountKey] || 0
}
// Returns the FileSystem for the current runtime environment
export function getDefaultFileSystem() :FileSystem {
return _defaultFileSystem || (_defaultFileSystem = createDefaultFileSystem())
}
// isNoFileSystem returns true if the provided file system is the non-functional
// implementation used when the environment does not have or support an actual
// file system.
export function isNoFileSystem(fs :FileSystem) :bool {
return dummyKey in fs
}
// end of external API
// ---------------------------------------------------------------------
// start of implementation
let _defaultFileSystem :FileSystem|null = null
function createNodeJSFileSystem(fs :{[k:string]:any}) :FileSystem {
return {
existsSync: fs.existsSync,
readfileSync: fs.readFileSync as (s:string)=>Uint8Array,
readfile: (path :string) => new Promise((resolve, reject) => {
fs.readFile(path, (err :Error, buf :Uint8Array) =>
err ? reject(err) : resolve(buf))
}),
readdirSync: (path :string) :string[] => fs.readdirSync(path, "utf8"),
}
}
function createDefaultFileSystem() :FileSystem {
if (typeof require != "undefined") {
let fs :any ; try { fs = require('fs') } catch(_) {}
if (fs && typeof fs.readFile == "function") {
return createNodeJSFileSystem(fs)
}
}
let notimplAsync = () => Promise.reject(new Error("no file system"))
let notimplSync = () :never => { throw new Error("no file system") }
let fs :FileSystem = {
readfile(_ :string) :Promise<Uint8Array> { return notimplAsync() },
readfileSync(_ :string) :Uint8Array { return notimplSync(), new Uint8Array() },
existsSync(_ :string) :bool { return notimplSync(), false },
readdirSync(_ :string) :string[] { return notimplSync(), [] },
}
;(fs as any)[dummyKey] = true
return fs
}
// ---------------------------------------------------------------------
const diagKey = Symbol("diag")
const errcountKey = Symbol("errcount")
const dummyKey = Symbol("dummy")
class Pool<T> {
_free :T[] = []
_factory :()=>T
constructor(factory :()=>T) {
this._factory = factory
}
alloc() :T {
let obj = this._free.pop()
return obj || this._factory()
}
free(obj :T) {
this._free.push(obj)
}
}
class DiagReporter {
diag :Diagnostic[] = []
constructor(cb? :DiagnosticCallback|null) {
let diag :Diagnostic[] = (this.diag = [])
this.errh = (pos :Position, msg :string, c :ErrorCode) => {
let d = new Diag("error", msg, pos, c)
diag.push(d)
cb && cb(d)
}
this.diagh = (pos :Position, msg :string, kind :DiagKind) => {
let d = new Diag(kind, msg, pos)
diag.push(d)
cb && cb(d)
}
}
errh(pos :Position, msg :string, c :ErrorCode) {}
diagh(pos :Position, msg :string, kind :DiagKind) {}
assignTo(obj :any) {
if (this.diag.length > 0) {
obj[diagKey] = this.diag
}
}
}
class CHost implements CompilerHost {
readonly fs :FileSystem
// Universe is shared amongs all incovations.
// It houses type interning in addition to intrinsic bindings.
universe = new Universe(new TypeSet())
// Exclusive resources
typeres = new Pool(()=>new TypeResolver(this.traceInDebugMode))
parser = new Pool(()=>new Parser(this.traceInDebugMode))
scanner = new Pool(()=>new Scanner(this.traceInDebugMode))
irbuilder = new Pool(()=>new IRBuilder())
parseComments = true // TODO: pass this to parse/scan invocations somehow
serialMode = false // do not perform work in a concurrent "async" manner
traceInDebugMode? :bool
constructor(fs :FileSystem) {
this.fs = fs
}
importPackage = (imps :Map<string,ast.Ent>, path :ast.StringLit) :Promise<ast.Ent> => {
// TODO: FIXME implement
print(`TODO: CHost.importPackage ${path}`)
// let name = strings.get(utf8.encodeString(path))
// return Promise.resolve(new Ent(name, new Stmt(NoPos, nilScope), null))
return Promise.reject(new Error("import not implemented"))
}
async parsePackage(
name :string,
sources :Iterable<Source>,
cb? :DiagnosticCallback,
smode? :ScanMode,
) :Promise<ast.Package> {
let pkgscope = new ast.Scope(this.universe.scope)
let pkg = new ast.Package(name, pkgscope)
let fset = new SrcFileSet()
let diags = new DiagReporter(cb)
let typeres = this.typeres.alloc()
typeres.init(fset, this.universe, diags.errh)
let errcount = 0
// sources => [filename,SourceData|null]
let src :[string,SourceData|null][] = []
for (let source of sources) {
src.push(typeof source == "string" ? [source,null] : source)
}
// parse source files
if (this.serialMode) {
for (let [filename, source] of src) {
let data = this.loadFileSync(filename, source)
let [f, nerrs] = this._parseFile(filename, data, pkgscope, fset, typeres, diags, smode)
pkg.files.push(f)
errcount += nerrs
}
} else {
await Promise.all(src.map(([filename, source]) =>
this.loadFile(filename, source).then(data => {
let [f, nerrs] = this._parseFile(filename, data, pkgscope, fset, typeres, diags, smode)
pkg.files.push(f)
errcount += nerrs
})
))
}
// bind package together, resolving cross-file references and imports
if (errcount == 0 && typeres.errorCount == 0) {
let binder = new PkgBinder(fset, typeres, diags.errh, this.traceInDebugMode)
errcount += typeres.errorCount + await binder.importAndBind(this.importPackage, pkg.files)
} else {
// add errors from type resolver (avoids double counting)
errcount += typeres.errorCount
}
// save error count to ast node
if (errcount > 0) {
;(pkg as any)[errcountKey] = errcount
}
this.typeres.free(typeres)
diags.assignTo(pkg)
return pkg
}
// calling with SourceData yields immediate results, else async
parseFile(_ :string, ps? :ast.Scope, cb? :DiagnosticCallback, m? :ScanMode) :Promise<ast.File>
parseFile(_ :string, s :SourceData, ps? :ast.Scope, cb? :DiagnosticCallback, m? :ScanMode) :ast.File
parseFile(
filename :string,
source? :SourceData|ast.Scope,
gscope? :ast.Scope|DiagnosticCallback,
cb? :DiagnosticCallback|ScanMode,
smode? :ScanMode,
) :Promise<ast.File>|ast.File {
let parse = (data :Uint8Array, ps :ast.Scope|null, cb? :DiagnosticCallback, m? :ScanMode) => {
let fset = new SrcFileSet()
let diags = new DiagReporter(cb)
let typeres = this.typeres.alloc()
typeres.init(fset, this.universe, diags.errh)
let [f, errcount] = this._parseFile(filename, data, ps, fset, typeres, diags, smode)
errcount += typeres.errorCount
this.typeres.free(typeres)
diags.assignTo(f)
if (errcount == 0) {
let binder = new PkgBinder(fset, typeres, diags.errh, this.traceInDebugMode)
errcount += typeres.errorCount + binder.bind([ f ])
}
// save error count to ast node
if (errcount > 0) {
;(f as any)[errcountKey] = errcount
}
return f
}
if (typeof source == "string") {
// parseFile(filename, source, gscope, cb, mode)
source = utf8.encodeString(String(source))
}
if (source instanceof Uint8Array) {
// parseFile(filename, source, gscope, cb, mode)
let _gscope = (gscope as ast.Scope||null) || new ast.Scope(this.universe.scope)
return parse(source, _gscope, cb as DiagnosticCallback, smode)
}
// parseFile(filename, gscope, cb, mode)
let _gscope = (source as ast.Scope||null) || new ast.Scope(this.universe.scope)
return this.loadFile(filename, null).then(data =>
parse(data, _gscope, gscope as DiagnosticCallback, cb as ScanMode)
)
}
_parseFile(
filename :string,
data :Uint8Array,
pkgscope :ast.Scope|null,
fset :SrcFileSet,
typeres :TypeResolver,
diags :DiagReporter,
smode :ScanMode|undefined,
) :[ast.File,int] {
let sfile = fset.addFile(filename, data.length)
let parser = this.parser.alloc()
parser.initParser(sfile, data, this.universe, pkgscope, typeres, diags.errh, diags.diagh, smode)
let file = parser.parseFile()
let errcount = parser.errorCount
this.parser.free(parser)
return [file, errcount]
}
// calling with SourceData yields immediate results, else async
scanFile(fn :string, f: ScanCallback, cb? :DiagnosticCallback, m? :ScanMode) :Promise<void>
scanFile(fn :string, s :SourceData, f: ScanCallback, cb? :DiagnosticCallback, m? :ScanMode) :void
scanFile(
filename :string,
source :SourceData|ScanCallback,
f :ScanCallback|DiagnosticCallback|undefined,
cb? :DiagnosticCallback|ScanMode,
smode? :ScanMode,
) :Promise<void>|void {
let scan = (data :Uint8Array, f :ScanCallback, cb? :DiagnosticCallback, m? :ScanMode) => {
let fset = new SrcFileSet()
let diags = new DiagReporter(cb)
let sfile = fset.addFile(filename, data.length)
let scanner = this.scanner.alloc()
scanner.init(sfile, data, diags.errh, smode)
try {
scanner.next()
while (scanner.tok != token.EOF) {
if (f(scanner.tok, scanner) === false) {
break
}
scanner.next()
}
} finally {
this.scanner.free(scanner)
}
}
if (typeof source == "string") {
source = utf8.encodeString(String(source))
}
if (source instanceof Uint8Array) {
scan(source, f as ScanCallback, cb as DiagnosticCallback, smode)
} else {
return this.loadFile(filename, null).then(data => {
scan(data, source as ScanCallback, f as DiagnosticCallback, cb as ScanMode)
})
}
}
loadFileSync(filename :string, source :SourceData|null|undefined) :Uint8Array {
if (source === null || source === undefined) {
return this.fs.readfileSync(filename)
} else if (source instanceof Uint8Array) {
return source
} else {
return utf8.encodeString(String(source))
}
}
loadFile(filename :string, source :SourceData|null|undefined) :Promise<Uint8Array> {
return (
source === null || source === undefined ? this.fs.readfile(filename) :
Promise.resolve(this.loadFileSync(filename, source))
)
}
compilePackage(
pkg :ast.Package,
target :string|Config,
cb? :DiagnosticCallback,
flags? :IRBuilderFlags,
) :ssa.Pkg {
let diags = new DiagReporter(cb)
let config = typeof target == "string" ? new Config(target) : target
let irbuilder = this.irbuilder.alloc()
irbuilder.init(config, diags.diagh, flags)
for (let file of pkg.files) {
for (let d of file.decls) {
let fn = irbuilder.addTopLevel(file.sfile, d)
if (DEBUG) {
print(`\n-----------------------\n`)
fn ? printir(fn) : print(fn)
print(
`━━━━━━━━━━━━━━━━━━━━━━━━` +
`━━━━━━━━━━━━━━━━━━━━━━━━`
)
}
}
}
let irpkg = irbuilder.pkg
this.irbuilder.free(irbuilder)
// run IP passes separately for debugging (normally run online)
let stopAtPass = config.arch == "generic" ? "lower" : ""
// stopAtPass = "lowered deadcode"
for (let f of irpkg.funs) {
runIRPasses(f, config, stopAtPass, pass => {
// if (DEBUG) {
// print(`after ${pass.name}\n`)
// printir(f)
// print(
// `━━━━━━━━━━━━━━━━━━━━━━━━` +
// `━━━━━━━━━━━━━━━━━━━━━━━━`
// )
// }
})
}
if (DEBUG) {
for (let f of irpkg.funs) {
print("")
printir(f)
}
}
return irpkg
}
// codegen() {
// let prog = new Program(f, config)
// prog.gen()
// }
} | the_stack |
import { NavbarComponent } from '../custom-navbar-component'
type PrivilegeType = 1 | 2
export class UserInfo extends NavbarComponent {
userInfo: any = {
mid: getUID(),
isLogin: Boolean(getUID()),
}
constructor() {
super()
this.boundingWidth = 240
this.noPadding = true
this.href = 'https://space.bilibili.com'
this.html = /*html*/`
<div class="user-face-container">
<img src='${EmptyImageUrl}' class="user-face"></img>
<img src='${EmptyImageUrl}' class="user-pendant"></img>
</div>
`
this.popupHtml = /*html*/`<div class="user-info-panel"></div>`
this.requestedPopup = true
this.init()
}
get name(): keyof CustomNavbarOrders {
return 'userInfo'
}
async init() {
const panel = await SpinQuery.select('.custom-navbar .user-info-panel') as HTMLElement
const face = await SpinQuery.select('.custom-navbar .user-face-container .user-face') as HTMLElement
const userInfoJson = await Ajax.getJsonWithCredentials('https://api.bilibili.com/x/web-interface/nav')
const userStatJson = await Ajax.getJsonWithCredentials('https://api.bilibili.com/x/web-interface/nav/stat')
Object.assign(this.userInfo, userInfoJson.data)
Object.assign(this.userInfo, userStatJson.data)
const vm = new Vue({
template: /*html*/`
<div class="user-info-panel">
<div v-if="isLogin" class="logged-in">
<a class="name" target="_blank" href="https://space.bilibili.com/">{{uname}}</a>
<a class="type" target="_blank" href="https://account.bilibili.com/account/big">{{userType}}</a>
<div class="privileges row" v-if="this.vipStatus === 1 && this.vipType === 2">
<div class="b-coin" :class="{received: privileges.bCoin.received}" @click="privilegeReceive(1)" :title="'有效期限: ' + privileges.bCoin.expire">
{{privileges.bCoin.received ? '已领取B币' : '领取B币'}}
</div>
<div class="coupons" :class="{received: privileges.coupons.received}" @click="privilegeReceive(2)" :title="'有效期限: ' + privileges.coupons.expire">
{{privileges.coupons.received ? '已领取优惠券' : '领取优惠券'}}
</div>
</div>
<div class="level-info row">
<a target="_blank" title="等级" href="https://account.bilibili.com/account/record"
class="level">
<i class="custom-navbar-iconfont-extended" :class="'custom-navbar-icon-lv' + level_info.current_level"></i>
</a>
<span class="level-progress-label">{{level_info.current_exp}} / {{level_info.next_exp}}</span>
</div>
<div class="level-progress separator">
<div class="level-progress-thumb" :style="levelProgressStyle"></div>
</div>
<div class="items">
<a class="item" target="_blank" title="手机验证"
href="https://passport.bilibili.com/account/security#/bindphone">
<i class="custom-navbar-iconfont-new-home custom-navbar-icon-bind-phone"></i>
<i v-if="mobile_verified" class="custom-navbar-iconfont-new-home custom-navbar-icon-ok"></i>
<i v-else class="custom-navbar-iconfont-new-home custom-navbar-icon-cancel"></i>
</a>
<a class="item" target="_blank" title="邮箱验证"
href="https://passport.bilibili.com/account/security#/bindmail">
<i class="custom-navbar-iconfont-new-home custom-navbar-icon-bind-email"></i>
<i v-if="email_verified" class="custom-navbar-iconfont-new-home custom-navbar-icon-ok"></i>
<i v-else class="custom-navbar-iconfont-new-home custom-navbar-icon-cancel"></i>
</a>
<a class="item" target="_blank" href="https://account.bilibili.com/site/coin" title="硬币">
<i class="custom-navbar-iconfont-new-home custom-navbar-icon-coin"></i>
<span>{{money}}</span>
</a>
<a class="item" target="_blank" href="https://pay.bilibili.com/bb_balance.html" title="B币">
<i class="custom-navbar-iconfont-new-home custom-navbar-icon-b-coin"></i>
<span>{{wallet.bcoin_balance}}</span>
</a>
</div>
<div class="separator"></div>
<div class="stats">
<a class="stats-item" :href="'https://space.bilibili.com/' + mid + '/fans/follow'" target="_blank">
<div class="stats-number">{{following | count}}</div>
关注
</a>
<a class="stats-item" :href="'https://space.bilibili.com/' + mid + '/fans/fans'" target="_blank">
<div class="stats-number">{{follower | count}}</div>
粉丝
</a>
<a class="stats-item" :href="'https://space.bilibili.com/' + mid + '/dynamic'" target="_blank">
<div class="stats-number">{{dynamic_count | count}}</div>
动态
</a>
</div>
<div class="separator"></div>
<a class="operation" target="_blank" href="https://account.bilibili.com/account/home">
<i class="icon custom-navbar-icon-profile custom-navbar-iconfont-new-home"></i>
个人中心
</a>
<a class="operation" target="_blank" href="https://member.bilibili.com/v2#/upload-manager/article">
<i class="icon custom-navbar-icon-posts custom-navbar-iconfont-new-home"></i>
投稿管理
</a>
<a class="operation" target="_blank" href="https://pay.bilibili.com/">
<i class="icon custom-navbar-icon-wallet custom-navbar-iconfont-new-home"></i>
B币钱包
</a>
<a class="operation" target="_blank" href="https://link.bilibili.com/p/center/index">
<i class="icon custom-navbar-icon-live-center custom-navbar-iconfont-new-home"></i>
直播中心
</a>
<a class="operation" target="_blank" href="https://show.bilibili.com/orderlist">
<i class="icon custom-navbar-icon-order-center custom-navbar-iconfont-new-home"></i>
订单中心
</a>
<a class="operation" target="_blank" href="https://www.bilibili.com/v/cheese/mine">
<i class="icon custom-navbar-icon-course custom-navbar-iconfont-new-home"></i>
我的课程
</a>
<div class="logout grey-button" @click="logout()">
退出登录
</div>
</div>
<div v-else class="not-logged-in">
<h1 class="welcome">欢迎来到 bilibili</h1>
<a href="https://passport.bilibili.com/register/phone.html" class="signup grey-button">注册</a>
<a href="https://passport.bilibili.com/login" class="login theme-button">登录</a>
</div>
</div>
`,
data: {
...this.userInfo,
privileges: {
bCoin: {
received: false,
expire: '',
},
coupons: {
received: false,
expire: '',
},
},
},
filters: {
count(value: number) {
return formatCount(value)
}
},
computed: {
userType() {
if (!this.isLogin) {
return '未登录'
}
if (this.level_info.current_level === 0) {
return '注册会员'
}
if (this.vipStatus === 1) {
if (this.vipType === 1) {
return this.vip_theme_type ? '小会员' : '大会员'
}
else if (this.vipType === 2) {
return this.vip_theme_type ? '年度小会员' : '年度大会员'
}
}
return '正式会员'
},
levelProgressStyle() {
const progress = (this.level_info.current_exp - this.level_info.current_min) / (this.level_info.next_exp - this.level_info.current_min)
return {
transform: `scaleX(${progress})`
}
}
},
methods: {
async privilegeReceive(type: PrivilegeType) {
const typeMapping = {
1: 'bCoin',
2: 'coupons'
}
if (this.privileges[typeMapping[type]].received) {
return
}
this.privileges[typeMapping[type]].received = true
const csrf = getCsrf()
const result = await (await fetch('https://api.bilibili.com/x/vip/privilege/receive',
{
credentials: 'include',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: `type=${type}&csrf=${csrf}`,
method: 'POST'
})).json()
console.log(result)
if (result.code === 0) {
if (typeMapping[type] === 'bCoin') {
this.wallet.bcoin_balance += 5
}
} else if (result.code === 69801) { // 已领过
return
} else {
this.privileges[typeMapping[type]].received = false
logError(result.message)
}
},
async logout() {
/** b 站 源 码
*
* ```js
* export const postLogout = () => {
* const Cookie = require('js-cookie')
* const qs = require('qs')
* return axios({
* method: 'post',
* url: '//passport.bilibili.com/login/exit/v2',
* withCredentials: true,
* headers: {
* 'Content-type': 'application/x-www-form-urlencoded',
* },
* data: qs.stringify({
* biliCSRF: Cookie.get('bili_jct')
* }),
* })
* }
* // ...
* async logout() {
* try {
* const { data } = await postLogout()
* if(data && data.data.redirectUrl) {
* window.location = data.data.redirectUrl
* }
* } catch (_) {
* }
* }
* ```
*/
const response = await Ajax.postTextWithCredentials(
'https://passport.bilibili.com/login/exit/v2',
formData({
biliCSRF: getCsrf(),
})
)
const url = _.get(JSON.parse(response), 'data.redirectUrl', '')
if (url) {
window.location.assign(url)
}
}
},
})
vm.$mount(panel)
if (this.userInfo.isLogin) {
const faceUrl = this.userInfo.face.replace('http', 'https')
const noFaceUrl = '//static.hdslb.com/images/member/noface.gif'
if (!faceUrl.includes(noFaceUrl)) { // 没上传过头像的不做缩放
const faceBaseSize = 68
face.setAttribute('srcset', getDpiSourceSet(faceUrl, faceBaseSize))
} else {
face.setAttribute('src', noFaceUrl)
}
if (this.userInfo.pendant.image) {
const pendant = await SpinQuery.select('.custom-navbar .user-face-container .user-pendant') as HTMLElement
const pendantUrl = this.userInfo.pendant.image.replace('http', 'https')
const pendantBaseSize = 116
pendant.setAttribute('srcset', getDpiSourceSet(pendantUrl, pendantBaseSize, 'png'))
}
if (this.userInfo.vipType === 2) { // 年度大会员权益
const privileges = await Ajax.getJsonWithCredentials('https://api.bilibili.com/x/vip/privilege/my')
if (privileges.code === 0) {
const bCoin = privileges.data.list.find((it: { type: PrivilegeType }) => it.type === 1)
vm.privileges.bCoin.received = bCoin.state === 1
vm.privileges.bCoin.expire = new Date(bCoin.expire_time * 1000).toLocaleDateString()
const coupons = privileges.data.list.find((it: { type: PrivilegeType }) => it.type === 2)
vm.privileges.coupons.received = coupons.state === 1
vm.privileges.coupons.expire = new Date(coupons.expire_time * 1000).toLocaleDateString()
}
}
}
else {
face.setAttribute('src', 'https://static.hdslb.com/images/akari.jpg')
}
}
}
export default {
export: {
UserInfo,
},
} | the_stack |
import { expect } from 'chai';
//import * as sinon from 'sinon';
import { BigNumber } from '@ethersproject/bignumber';
import { Zero, MaxUint256 } from '@ethersproject/constants';
import { Contract } from '@ethersproject/contracts';
import { JsonRpcProvider } from '@ethersproject/providers';
import { Wallet } from '@ethersproject/wallet';
import { ZenethRelayer } from '../src/index';
import * as ERC20Abi from '../src/abi/ERC20.json';
import * as SwapBriberAbi from '../src/abi/SwapBriber.json';
import { mainnetRelayUrl, goerliRelayUrl } from '../src/constants';
import * as DeployInfo from '@scopelift/zeneth-contracts/deploy-history/goerli-latest.json';
// Verify environment variables
const infuraId = process.env.INFURA_ID;
if (!infuraId) throw new Error('Please set your INFURA_ID in the .env file');
const authPrivateKey = process.env.AUTH_PRIVATE_KEY;
if (!authPrivateKey) throw new Error('Please set your AUTH_PRIVATE_KEY in the .env file');
// Setup providers
const mainnetProviderUrl = `https://mainnet.infura.io/v3/${infuraId}`;
const mainnetProvider = new JsonRpcProvider(mainnetProviderUrl);
const goerliProviderUrl = `https://goerli.infura.io/v3/${infuraId}`;
const goerliProvider = new JsonRpcProvider(goerliProviderUrl);
// Uniswap V2 addresses (on Goerli)
const uniRouterAddress = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';
const wethAddress = '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6';
// Get instance of Goerli DAI
const dai = new Contract('0xCdC50DB037373deaeBc004e7548FA233B3ABBa57', ERC20Abi, goerliProvider);
// Setup account of user that has no ETH. This is a random account that was given Goerli testnet tokens and no ETH
const user = new Wallet('0x6eea9d8bafc2440aa2fb29533f9139b2cce891c89d6088bc74517ea1fbbaf7df', goerliProvider); // address: 0x47550514d0Ed597413ae944e25A62B4bFE28aD55
// Define Goerli address of our swapAndBribe contract
const swapAndBribe = new Contract(DeployInfo.contracts.SwapBriber, SwapBriberAbi, goerliProvider);
describe('Flashbots relayer', () => {
describe('Initialization', () => {
it('initializes a relayer instance with mainnet as the default', async () => {
const zenethRelayer = await ZenethRelayer.create(mainnetProvider, process.env.AUTH_PRIVATE_KEY as string);
expect(zenethRelayer.provider.connection.url).to.equal(mainnetProviderUrl);
expect(zenethRelayer.flashbotsProvider.connection.url).to.equal(mainnetRelayUrl);
});
it('initializes a relayer instance against a Goerli', async () => {
const zenethRelayer = await ZenethRelayer.create(goerliProvider, process.env.AUTH_PRIVATE_KEY as string);
expect(zenethRelayer.provider.connection.url).to.equal(goerliProviderUrl);
expect(zenethRelayer.flashbotsProvider.connection.url).to.equal(goerliRelayUrl);
});
it('throws if initialized with an unsupported network', async () => {
const rinkebyProviderUrl = `https://rinkeby.infura.io/v3/${infuraId}`;
const rinkebyProvider = new JsonRpcProvider(rinkebyProviderUrl);
await expectRejection(
ZenethRelayer.create(rinkebyProvider, process.env.AUTH_PRIVATE_KEY as string),
'Unsupported network'
);
});
});
describe('Usage', () => {
let zenethRelayer: ZenethRelayer;
const transferAmount = 100n * 10n ** 18n; // 100 DAI
const feeAmount = 25n * 10n ** 18n; // 25 DAI
const bribeAmount = 1n * 10n ** 15n; // 0.001 ETH (must be less than feeAmount/ethPrice)
let chainId: number;
beforeEach(async () => {
zenethRelayer = await ZenethRelayer.create(goerliProvider, process.env.AUTH_PRIVATE_KEY as string);
({ chainId } = await goerliProvider.getNetwork());
// Verify user has no ETH
expect(await goerliProvider.getBalance(user.address)).to.equal(0);
// Verify user has sufficient DAI balance before each test
const minBalance = transferAmount + feeAmount;
const userBalance = await dai.balanceOf(user.address);
expect(userBalance.gt(minBalance), 'Please mint more Goerli DAI to the user to continue with testing').to.be.true;
});
describe('Sends bundles', () => {
it('sends simple bundle where user sends tokens and relayer pays ETH', async () => {
// Get nonce of the first transaction
let nonce = await goerliProvider.getTransactionCount(user.address);
// TRANSACTION 1
// User signs transaction to send DAI to arbitrary recipient
const recipient = Wallet.createRandom(); // random recipient simplifies testing since balance will be 0
const transferData = dai.interface.encodeFunctionData('transfer', [recipient.address, transferAmount]);
const tx1 = {
chainId,
data: transferData,
from: user.address,
gasLimit: BigNumber.from('250000'),
gasPrice: Zero,
nonce,
to: dai.address,
value: Zero,
};
const sig1 = await user.signTransaction(tx1);
nonce += 1; // must track nonce manually
// TRANSACTION 2
// User signs transaction approving SwapBribe contract to spend their DAI
const approveData = dai.interface.encodeFunctionData('approve', [swapAndBribe.address, MaxUint256]);
const tx2 = {
chainId,
data: approveData,
from: user.address,
gasLimit: BigNumber.from('250000'),
gasPrice: Zero,
nonce,
to: dai.address,
value: Zero,
};
const sig2 = await user.signTransaction(tx2);
nonce += 1;
// TRANSACTION 3
// User signs transaction approving SwapBribe contract to spend their DAI
const swapAndBribeData = swapAndBribe.interface.encodeFunctionData('swapAndBribe', [
dai.address,
feeAmount,
bribeAmount,
uniRouterAddress,
[dai.address, wethAddress], // swap path
'2000000000', //deadline, very far into the future
]);
const tx3 = {
chainId,
data: swapAndBribeData,
from: user.address,
gasLimit: BigNumber.from('1000000'),
gasPrice: Zero,
nonce,
to: swapAndBribe.address,
value: Zero,
};
const sig3 = await user.signTransaction(tx3);
nonce += 1;
// PREPARE BUNDLE
const signedTxs = [sig1, sig2, sig3]; // put signed transactions into an array
const currentBlock = await goerliProvider.getBlockNumber(); // get block number of most recently mined block
const validBlock = currentBlock + 2; // only block number we allow this bundle be mined for
// SEND BUNDLE
const flashbotsTx = await zenethRelayer.sendBundle(signedTxs, validBlock);
// OUTPUT ASSERTIONS
if ('error' in flashbotsTx) {
// Here, flashbotsTx is of type RelayResponseError. For testing we do not expect to see this
console.log('RelayResponseError: ', flashbotsTx);
throw new Error('Promise resolved to RelayResponseError');
}
// If here, we now flashbotsTx is of type FlashbotsTransactionResponse
expect(flashbotsTx.bundleTransactions.length).to.equal(signedTxs.length);
const result = await flashbotsTx.wait(); // resolves to 0, 1, or 2 per type FlashbotsBundleResolution
expect([0, 1, 2].includes(result)).to.be.true;
});
it('does not send bundles with transactions that revert', async () => {
// Get nonce to use
const nonce = await goerliProvider.getTransactionCount(user.address);
// TRANSACTION
// Use a dai transfer
const transferData = dai.interface.encodeFunctionData('transfer', [user.address, transferAmount]);
const tx1 = {
chainId,
data: transferData,
from: user.address,
gasLimit: BigNumber.from('21000'), // but gas limit is too low
gasPrice: Zero,
nonce,
to: dai.address,
value: Zero,
};
const sig1 = await user.signTransaction(tx1);
// SEND BUNDLE
const errorMessage = 'Simulation error occurred, exiting. Please make sure you are sending a valid bundle';
const signedTxs = [sig1];
const validBlocks = 1;
await expectRejection(zenethRelayer.sendBundle(signedTxs, validBlocks), errorMessage);
});
});
describe('Transaction signing', () => {
it('populates transactions', async () => {
// Provide a transaction with the minimum number of fields
const tx = { from: user.address, to: dai.address, gasLimit: '21000' };
const populatedTx = await zenethRelayer.populateTransaction(tx);
expect(populatedTx.chainId).to.equal(goerliProvider.network.chainId);
expect(populatedTx.data).to.equal('0x');
expect(populatedTx.gasPrice).to.equal(Zero);
expect(populatedTx.gasLimit).to.equal(tx.gasLimit);
expect(populatedTx.nonce).to.equal(await goerliProvider.getTransactionCount(user.address));
expect(populatedTx.to).to.equal(tx.to);
expect(populatedTx.value).to.equal(Zero);
// Provide a transaction with the maximum number of fields
const nonce = await goerliProvider.getTransactionCount(user.address);
const tx2 = { from: user.address, to: dai.address, gasLimit: '21000', nonce, value: '1', data: '0x1234' };
const populatedTx2 = await zenethRelayer.populateTransaction(tx2);
expect(populatedTx2.chainId).to.equal(goerliProvider.network.chainId);
expect(populatedTx2.data).to.equal(tx2.data);
expect(populatedTx2.gasPrice).to.equal(Zero);
expect(populatedTx2.gasLimit).to.equal(tx2.gasLimit);
expect(populatedTx2.nonce).to.equal(tx2.nonce);
expect(populatedTx2.to).to.equal(tx2.to);
expect(populatedTx2.value).to.equal(tx2.value);
});
it('populates multiple transactions at once', async () => {
const recipient = Wallet.createRandom();
const txFragment1 = {
data: dai.interface.encodeFunctionData('transfer', [recipient.address, transferAmount]),
gasLimit: '200000',
to: dai.address,
value: '0',
};
const txFragment2 = {
data: dai.interface.encodeFunctionData('approve', [swapAndBribe.address, MaxUint256]),
gasLimit: '300000',
to: dai.address,
value: '0',
};
const txFragments = [txFragment1, txFragment2];
const populatedTxs = await zenethRelayer.populateTransactions(user.address, txFragments);
const initialNonce = await goerliProvider.getTransactionCount(user.address);
populatedTxs.forEach((populatedTx, index) => {
expect(populatedTx.chainId).to.equal(goerliProvider.network.chainId);
expect(populatedTx.data).to.equal(txFragments[index].data);
expect(populatedTx.gasLimit).to.equal(txFragments[index].gasLimit);
expect(populatedTx.gasPrice).to.equal(Zero);
expect(populatedTx.nonce).to.equal(initialNonce + index);
expect(populatedTx.to).to.equal(txFragments[index].to);
expect(populatedTx.value).to.equal(txFragments[index].value);
});
});
it('signs transactions correctly', async () => {
// TODO more robust test that uses eth_sign to replicate MetaMask behavior. This uses signTransaction which
// is currently not supported by MetaMask
const recipient = Wallet.createRandom();
const nonce = await goerliProvider.getTransactionCount(user.address);
const tx1 = {
chainId,
data: dai.interface.encodeFunctionData('transfer', [recipient.address, transferAmount]),
gasLimit: BigNumber.from('250000'),
gasPrice: Zero,
nonce,
to: dai.address,
value: Zero,
};
const sig1 = await user.signTransaction(tx1);
expect(sig1).to.have.length.greaterThan(0);
expect(typeof sig1 === 'string').to.be.true;
});
});
});
});
/**
* @notice Wrapper function to verify that an async function rejects with the specified message
* @param promise Promise to wait for
* @param message Expected rejection message
*/
export const expectRejection = async (promise: Promise<any>, message: string) => {
// Error type requires strings, so we set them to an arbitrary value and
// later check the values. If unchanged, the promise did not reject
let error: Error = { name: 'default', message: 'default' };
try {
await promise;
} catch (e) {
error = e;
} finally {
expect(error.name).to.not.equal('default');
expect(error.message).to.not.equal('default');
expect(error.message).to.equal(message);
}
}; | the_stack |
declare namespace Mpegts {
interface MediaSegment {
duration: number;
filesize?: number;
url: string;
}
interface MediaDataSource {
type: string;
isLive?: boolean;
cors?: boolean;
withCredentials?: boolean;
hasAudio?: boolean;
hasVideo?: boolean;
duration?: number;
filesize?: number;
url?: string;
segments?: MediaSegment[];
}
interface Config {
/**
* @desc Enable separated thread for transmuxing (unstable for now)
* @defaultvalue false
*/
enableWorker?: boolean;
/**
* @desc Enable IO stash buffer. Set to false if you need realtime (minimal latency) for live stream
* playback, but may stalled if there's network jittering.
* @defaultvalue true
*/
enableStashBuffer?: boolean;
/**
* @desc Indicates IO stash buffer initial size. Default is `384KB`. Indicate a suitable size can
* improve video load/seek time.
*/
stashInitialSize?: number;
/**
* @desc Same to `isLive` in **MediaDataSource**, ignored if has been set in MediaDataSource structure.
* @defaultvalue false
*/
isLive?: boolean;
/**
* @desc Chasing the live stream latency caused by the internal buffer in HTMLMediaElement
* `isLive` should also be set to `true`
* @defaultvalue false
*/
liveBufferLatencyChasing?: boolean;
/**
* @desc Maximum acceptable buffer latency in HTMLMediaElement, in seconds
* Effective only if `isLive: true` and `liveBufferLatencyChasing: true`
* @defaultvalue 1.5
*/
liveBufferLatencyMaxLatency?: number;
/**
* @desc Minimum buffer latency to be keeped in HTMLMediaElement, in seconds
* Effective only if `isLive: true` and `liveBufferLatencyChasing: true`
* @defaultvalue 0.5
*/
liveBufferLatencyMinRemain?: number;
/**
* @desc Abort the http connection if there's enough data for playback.
* @defaultvalue true
*/
lazyLoad?: boolean;
/**
* @desc Indicates how many seconds of data to be kept for `lazyLoad`.
* @defaultvalue 3 * 60
*/
lazyLoadMaxDuration?: number;
/**
* @desc Indicates the `lazyLoad` recover time boundary in seconds.
* @defaultvalue 30
*/
lazyLoadRecoverDuration?: number;
/**
* @desc Do load after MediaSource `sourceopen` event triggered. On Chrome, tabs which
* be opened in background may not trigger `sourceopen` event until switched to that tab.
* @defaultvalue true
*/
deferLoadAfterSourceOpen?: boolean;
/**
* @desc Do auto cleanup for SourceBuffer
* @defaultvalue false (from docs)
*/
autoCleanupSourceBuffer?: boolean;
/**
* @desc When backward buffer duration exceeded this value (in seconds), do auto cleanup for SourceBuffer
* @defaultvalue 3 * 60
*/
autoCleanupMaxBackwardDuration?: number;
/**
* @desc Indicates the duration in seconds to reserve for backward buffer when doing auto cleanup.
* @defaultvalue 2 * 60
*/
autoCleanupMinBackwardDuration?: number;
/**
* @defaultvalue 600
*/
statisticsInfoReportInterval?: number;
/**
* @desc Fill silent audio frames to avoid a/v unsync when detect large audio timestamp gap.
* @defaultvalue true
*/
fixAudioTimestampGap?: boolean;
/**
* @desc Accurate seek to any frame, not limited to video IDR frame, but may a bit slower.
* Available on Chrome > 50, FireFox and Safari.
* @defaultvalue false
*/
accurateSeek?: boolean;
/**
* @desc 'range' use range request to seek, or 'param' add params into url to indicate request range.
* @defaultvalue 'range'
*/
seekType?: 'range' | 'param' | 'custom';
/**
* @desc Indicates seek start parameter name for seekType = 'param'
* @defaultvalue 'bstart'
*/
seekParamStart?: string;
/**
* @desc Indicates seek end parameter name for seekType = 'param'
* @defaultvalue 'bend'
*/
seekParamEnd?: string;
/**
* @desc Send Range: bytes=0- for first time load if use Range seek
* @defaultvalue false
*/
rangeLoadZeroStart?: boolean;
/**
* @desc Indicates a custom seek handler
* @desc Should implement `SeekHandler` interface
*/
customSeekHandler?: CustomSeekHandlerConstructor;
/**
* @desc Reuse 301/302 redirected url for subsequence request like seek, reconnect, etc.
* @defaultvalue false
*/
reuseRedirectedURL?: boolean;
/**
* @desc Indicates the Referrer Policy when using FetchStreamLoader
* @defaultvalue 'no-referrer-when-downgrade' (from docs)
*/
referrerPolicy?: ReferrerPolicy;
/**
* @desc Indicates additional headers that will be added to request
*/
headers?: {
[k: string]: string
}
/**
* @desc Should implement `BaseLoader` interface
*/
customLoader?: CustomLoaderConstructor;
}
interface CustomSeekHandlerConstructor {
new(): SeekHandler;
}
interface SeekHandler {
getConfig(sourceURL: string, range: Range): SeekConfig;
removeURLParameters(url: string): string;
}
interface SeekConfig {
url: string;
headers: Headers | object;
}
interface BaseLoaderConstructor {
new(typeName: string): BaseLoader;
}
interface BaseLoader {
_status: number;
_needStash: boolean;
destroy(): void;
isWorking(): boolean;
readonly type: string;
readonly status: number;
readonly needStashBuffer: boolean;
onContentLengthKnown: (contentLength: number) => void;
onURLRedirect: (redirectedURL: string) => void;
onDataArrival: (chunk: ArrayBuffer, byteStart: number, receivedLength?: number) => void;
onError: (errorType: LoaderErrors, errorInfo: LoaderErrorMessage) => void;
onComplete: (rangeFrom: number, rangeTo: number) => void;
open(dataSource: MediaSegment, range: Range): void;
abort(): void;
}
interface CustomLoaderConstructor {
new(seekHandler: SeekHandler, config: Config): BaseLoader;
}
interface Range {
from: number;
to: number;
}
interface LoaderStatus {
readonly kIdle: 0;
readonly kConnecting: 1;
readonly kBuffering: 2;
readonly kError: 3;
readonly kComplete: 4;
}
interface LoaderErrors {
readonly OK: 'OK';
readonly EXCEPTION: 'Exception';
readonly HTTP_STATUS_CODE_INVALID: 'HttpStatusCodeInvalid';
readonly CONNECTING_TIMEOUT: 'ConnectingTimeout';
readonly EARLY_EOF: 'EarlyEof';
readonly UNRECOVERABLE_EARLY_EOF: 'UnrecoverableEarlyEof';
}
interface LoaderErrorMessage {
code: number;
msg: string;
}
interface FeatureList {
msePlayback: boolean;
mseLivePlayback: boolean;
networkStreamIO: boolean;
networkLoaderName: string;
nativeMP4H264Playback: boolean;
nativeWebmVP8Playback: boolean;
nativeWebmVP9Playback: boolean;
}
interface PlayerConstructor {
new (mediaDataSource: MediaDataSource, config?: Config): Player;
}
interface Player {
destroy(): void;
on(event: string, listener: (...args: any[]) => void): void;
off(event: string, listener: (...args: any[]) => void): void;
attachMediaElement(mediaElement: HTMLMediaElement): void;
detachMediaElement(): void;
load(): void;
unload(): void;
play(): Promise<void> | void;
pause(): void;
type: string;
buffered: TimeRanges;
duration: number;
volume: number;
muted: boolean;
currentTime: number;
/**
* @deprecated MSEPlayer/NativePlayer have its own `mediaInfo` field.
* @desc Keep it for backwards compatibility
* @since 1.4
*/
mediaInfo: NativePlayerMediaInfo | MSEPlayerMediaInfo;
/**
* @deprecated MSEPlayer/NativePlayer have its own `statisticsInfo` field.
* @desc Keep it for backwards compatibility
* @since 1.4
*/
statisticsInfo: NativePlayerStatisticsInfo | MSEPlayerStatisticsInfo;
}
interface NativePlayerStatisticsInfo {
playerType: 'NativePlayer';
url: string;
decodedFrames?: number;
droppedFrames?: number;
}
interface MSEPlayerReportStatisticsInfo {
url: string;
hasRedirect: boolean;
redirectedURL?: string;
speed: number; // KB/s
loaderType: string;
currentSegmentIndex: number;
totalSegmentCount: number;
}
interface MSEPlayerStatisticsInfo extends Partial<MSEPlayerReportStatisticsInfo> {
playerType: 'MSEPlayer';
decodedFrames?: number;
droppedFrames?: number;
}
interface NativePlayerMediaInfo {
mimeType: string;
duration?: number;
width?: number;
height?: number;
}
interface MSEPlayerMediaInfo extends NativePlayerMediaInfo {
audioCodec?: string;
videoCodec?: string;
audioDataRate?: number;
videoDataRate?: number;
hasAudio?: boolean;
hasVideo?: boolean;
chromaFormat?: string;
fps?: number;
[k: string]: any;
}
interface MSEPlayer extends Player {
mediaInfo: MSEPlayerMediaInfo;
statisticsInfo: MSEPlayerStatisticsInfo;
}
interface NativePlayer extends Player {
mediaInfo: NativePlayerMediaInfo;
statisticsInfo: NativePlayerStatisticsInfo;
}
interface LoggingControlConfig {
forceGlobalTag: boolean;
globalTag: string;
enableAll: boolean;
enableDebug: boolean;
enableVerbose: boolean;
enableInfo: boolean;
enableWarn: boolean;
enableError: boolean;
}
interface LoggingControl extends LoggingControlConfig {
getConfig(): LoggingControlConfig;
applyConfig(config: Partial<LoggingControlConfig>): void;
addLogListener(listener: (...args: any[]) => void): void;
removeLogListener(listener: (...args: any[]) => void): void;
}
interface Events {
ERROR: string;
LOADING_COMPLETE: string;
RECOVERED_EARLY_EOF: string;
MEDIA_INFO: string;
METADATA_ARRIVED: string;
SCRIPTDATA_ARRIVED: string;
TIMED_ID3_METADATA_ARRIVED: string;
PES_PRIVATE_DATA_DESCRIPTOR: string;
PES_PRIVATE_DATA_ARRIVED: string;
STATISTICS_INFO: string;
}
interface ErrorTypes {
NETWORK_ERROR: string;
MEDIA_ERROR: string;
OTHER_ERROR: string;
}
interface ErrorDetails {
NETWORK_EXCEPTION: string;
NETWORK_STATUS_CODE_INVALID: string;
NETWORK_TIMEOUT: string;
NETWORK_UNRECOVERABLE_EARLY_EOF: string;
MEDIA_MSE_ERROR: string;
MEDIA_FORMAT_ERROR: string;
MEDIA_FORMAT_UNSUPPORTED: string;
MEDIA_CODEC_UNSUPPORTED: string;
}
}
declare var Mpegts: {
createPlayer(mediaDataSource: Mpegts.MediaDataSource, config?: Mpegts.Config): Mpegts.Player;
isSupported(): boolean;
getFeatureList(): Mpegts.FeatureList;
/**
* @deprecated Use `Mpegts.BaseLoaderConstructor` instead.
* Because it's not available on `mpegts` variable.
* @desc implement interface `BaseLoader`
* @since 1.4
*/
BaseLoader: Mpegts.BaseLoaderConstructor;
/**
* @deprecated Use `Mpegts.BaseLoaderConstructor` instead.
* Because it's not available on `mpegts` variable.
* @since 1.4
*/
LoaderStatus: Mpegts.LoaderStatus;
/**
* @deprecated Use `Mpegts.BaseLoaderConstructor` instead.
* Because it's not available on `mpegts` variable.
* @since 1.4
*/
LoaderErrors: Mpegts.LoaderErrors;
readonly version: string;
readonly Events: Readonly<Mpegts.Events>;
readonly ErrorTypes: Readonly<Mpegts.ErrorTypes>;
readonly ErrorDetails: Readonly<Mpegts.ErrorDetails>;
readonly MSEPlayer: Mpegts.PlayerConstructor;
readonly NativePlayer: Mpegts.PlayerConstructor;
readonly LoggingControl: Mpegts.LoggingControl;
};
export default Mpegts; | the_stack |
import { expect } from "chai";
import {
Picker,
PickerList,
PickerListItem,
pickerListItemTemplate,
pickerListTemplate,
PickerMenu,
PickerMenuOption,
pickerMenuOptionTemplate,
pickerMenuTemplate,
pickerTemplate,
} from "./index.js";
import { fixture } from "../testing/fixture.js";
import { Updates } from "@microsoft/fast-element";
import {
keyArrowLeft,
keyArrowRight,
keyBackspace,
keyDelete,
keyEnter,
} from "@microsoft/fast-web-utilities";
const FASTPickerList = PickerList.compose({
baseName: "picker-list",
template: pickerListTemplate,
shadowOptions: null,
})
const FASTPickerListItem = PickerListItem.compose({
baseName: "picker-list-item",
template: pickerListItemTemplate
})
const FASTPickerMenu = PickerMenu.compose({
baseName: "picker-menu",
template: pickerMenuTemplate
})
const FASTPickerMenuOption = PickerMenuOption.compose({
baseName: "picker-menu-option",
template: pickerMenuOptionTemplate
})
const FASTPicker = Picker.compose({
baseName: "picker",
template: pickerTemplate,
shadowOptions: {
delegatesFocus: true,
},
})
const enterEvent = new KeyboardEvent("keydown", {
key: keyEnter,
bubbles: true,
} as KeyboardEventInit);
const arrowLeftEvent = new KeyboardEvent("keydown", {
key: keyArrowLeft,
bubbles: true,
} as KeyboardEventInit);
const arrowRightEvent = new KeyboardEvent("keydown", {
key: keyArrowRight,
bubbles: true,
} as KeyboardEventInit);
const backEvent = new KeyboardEvent("keydown", {
key: keyBackspace,
bubbles: true,
} as KeyboardEventInit);
const deleteEvent = new KeyboardEvent("keydown", {
key: keyDelete,
bubbles: true,
} as KeyboardEventInit);
async function setupPicker() {
const { element, connect, disconnect }: {
element: HTMLElement & Picker,
connect: () => void,
disconnect: () => void
} = await fixture(
[
FASTPicker(),
FASTPickerList(),
FASTPickerListItem(),
FASTPickerMenu(),
FASTPickerMenuOption()
]
);
return { element, connect, disconnect };
}
async function setupPickerList() {
const { element, connect, disconnect } = await fixture(FASTPickerList());
return { element, connect, disconnect };
}
async function setupPickerListItem() {
const { element, connect, disconnect } = await fixture(FASTPickerListItem());
return { element, connect, disconnect };
}
async function setupPickerMenu() {
const { element, connect, disconnect } = await fixture(FASTPickerMenu());
return { element, connect, disconnect };
}
async function setupPickerMenuOption() {
const { element, connect, disconnect } = await fixture(FASTPickerMenuOption());
return { element, connect, disconnect };
}
describe("Picker", () => {
/**
* Picker tests
*/
it("picker should create a list element when instanciated", async () => {
const { element, connect, disconnect } = await setupPicker();
await connect();
expect(element.listElement).to.be.instanceof(PickerList);
await disconnect();
});
it("picker should include a text input with role of 'combobox'", async () => {
const { element, connect, disconnect } = await setupPicker();
await connect();
expect(element.inputElement?.getAttribute("role")).to.equal("combobox");
await disconnect();
});
it("picker 'combobox' should reflect label/labbelledby/placeholder attributes on picker", async () => {
const { element, connect, disconnect } = await setupPicker();
element.label = "test label";
element.labelledBy = "test labelledby";
element.placeholder = "test placeholder";
await connect();
expect(element.inputElement?.getAttribute("aria-label")).to.equal("test label");
expect(element.inputElement?.getAttribute("aria-labelledby")).to.equal("test labelledby");
expect(element.inputElement?.getAttribute("placeholder")).to.equal("test placeholder");
await disconnect();
});
it("picker should create a menu element when instanciated", async () => {
const { element, connect, disconnect } = await setupPicker();
await connect();
expect(element.menuElement).to.be.instanceof(PickerMenu);
await disconnect();
});
it("picker should generate list items for selected elements", async () => {
const { element, connect, disconnect } = await setupPicker();
element.selection = "apples,oranges,bananas"
await connect();
await Updates.next();
expect(element.querySelectorAll("fast-picker-list-item").length).to.equal(3);
await disconnect();
});
it("picker should move focus to the input element when focused", async () => {
const { element, connect, disconnect } = await setupPicker();
await connect();
await Updates.next();
element.focus();
expect(document.activeElement === element.inputElement).to.equal(true);
await disconnect();
});
it("picker should move focus accross list items with left/right arrow keys", async () => {
const { element, connect, disconnect } = await setupPicker();
element.selection = "apples,oranges,bananas"
await connect();
await Updates.next();
element.focus();
expect(document.activeElement === element.inputElement).to.equal(true);
const listItems: Element[] = Array.from(element.querySelectorAll("fast-picker-list-item"));
element.dispatchEvent(arrowLeftEvent);
expect(document.activeElement === listItems[2]).to.equal(true);
element.dispatchEvent(arrowLeftEvent);
expect(document.activeElement === listItems[1]).to.equal(true);
element.dispatchEvent(arrowLeftEvent);
expect(document.activeElement === listItems[0]).to.equal(true);
element.dispatchEvent(arrowLeftEvent);
expect(document.activeElement === listItems[0]).to.equal(true);
element.dispatchEvent(arrowRightEvent);
expect(document.activeElement === listItems[1]).to.equal(true);
element.dispatchEvent(arrowRightEvent);
expect(document.activeElement === listItems[2]).to.equal(true);
element.dispatchEvent(arrowRightEvent);
expect(document.activeElement === element.inputElement).to.equal(true);
element.dispatchEvent(arrowRightEvent);
expect(document.activeElement === element.inputElement).to.equal(true);
await disconnect();
});
it("picker should delete entries with delete/backspace keystrokes", async () => {
const { element, connect, disconnect } = await setupPicker();
element.selection = "apples,oranges,bananas"
await connect();
await Updates.next();
element.focus();
let listItems: Element[] = Array.from(element.querySelectorAll("fast-picker-list-item"));
expect(listItems.length).to.equal(3);
expect(element.selection).to.equal("apples,oranges,bananas");
element.dispatchEvent(backEvent);
await Updates.next();
listItems = Array.from(element.querySelectorAll("fast-picker-list-item"));
expect(listItems.length).to.equal(2);
expect(element.selection).to.equal("apples,oranges");
element.dispatchEvent(deleteEvent);
await Updates.next();
listItems = Array.from(element.querySelectorAll("fast-picker-list-item"));
expect(listItems.length).to.equal(1);
expect(element.selection).to.equal("apples");
await disconnect();
});
it("picker should apply settings to place scaling menu below input by default", async () => {
const { element, connect, disconnect } = await setupPicker();
await connect();
await Updates.next();
expect(element.menuConfig.verticalDefaultPosition).to.equal("bottom");
expect(element.menuConfig.verticalScaling).to.equal("fill");
await disconnect();
});
it("picker should apply menu placement selections", async () => {
const { element, connect, disconnect } = await setupPicker();
element.menuPlacement = "top-fill";
await connect();
await Updates.next();
expect(element.menuConfig.verticalDefaultPosition).to.equal("top");
expect(element.menuConfig.verticalPositioningMode).to.equal("locktodefault");
expect(element.menuConfig.verticalScaling).to.equal("fill");
element.menuPlacement = "top";
await Updates.next();
expect(element.menuConfig.verticalDefaultPosition).to.equal("top");
expect(element.menuConfig.verticalPositioningMode).to.equal("locktodefault");
expect(element.menuConfig.verticalScaling).to.equal("content");
element.menuPlacement = "bottom";
await Updates.next();
expect(element.menuConfig.verticalDefaultPosition).to.equal("bottom");
expect(element.menuConfig.verticalPositioningMode).to.equal("locktodefault");
expect(element.menuConfig.verticalScaling).to.equal("content");
element.menuPlacement = "bottom-fill";
await Updates.next();
expect(element.menuConfig.verticalDefaultPosition).to.equal("bottom");
expect(element.menuConfig.verticalPositioningMode).to.equal("locktodefault");
expect(element.menuConfig.verticalScaling).to.equal("fill");
element.menuPlacement = "tallest-fill";
await Updates.next();
expect(element.menuConfig.verticalDefaultPosition).to.equal(undefined);
expect(element.menuConfig.verticalPositioningMode).to.equal("dynamic");
expect(element.menuConfig.verticalScaling).to.equal("fill");
element.menuPlacement = "tallest";
await Updates.next();
expect(element.menuConfig.verticalDefaultPosition).to.equal(undefined);
expect(element.menuConfig.verticalPositioningMode).to.equal("dynamic");
expect(element.menuConfig.verticalScaling).to.equal("content");
await disconnect();
});
/**
* Picker-list tests
*/
it("picker list should include a role of `list`", async () => {
const { element, connect, disconnect } = await setupPickerList();
await connect();
expect(element.getAttribute("role")).to.equal("list");
await disconnect();
});
/**
* Picker-list-item tests
*/
it("picker list-item should include a role of `listitem`", async () => {
const { element, connect, disconnect } = await setupPickerListItem();
await connect();
expect(element.getAttribute("role")).to.equal("listitem");
await disconnect();
});
it("picker list-item emits 'pickeriteminvoked' event when clicked", async () => {
const { element, connect, disconnect } = await setupPickerListItem();
let wasInvoked: boolean = false;
element.addEventListener("pickeriteminvoked", e => {
wasInvoked = true;
});
await connect();
element.click();
expect(wasInvoked).to.equal(true);
await disconnect();
});
it("picker menu-option emits 'pickeriteminvoked' event on 'Enter'", async () => {
const { element, connect, disconnect } = await setupPickerListItem();
let wasInvoked: boolean = false;
element.addEventListener("pickeriteminvoked", e => {
wasInvoked = true;
});
await connect();
element.dispatchEvent(enterEvent);
expect(wasInvoked).to.equal(true);
await disconnect();
});
/**
* Picker-menu tests
*/
it("picker menu should include a role of `list`", async () => {
const { element, connect, disconnect } = await setupPickerMenu();
await connect();
expect(element.getAttribute("role")).to.equal("list");
await disconnect();
});
/**
* Picker-menu-option tests
*/
it("picker menu-option should include a role of `listitem`", async () => {
const { element, connect, disconnect } = await setupPickerMenuOption();
await connect();
expect(element.getAttribute("role")).to.equal("listitem");
await disconnect();
});
it("picker menu-option emits 'pickeroptioninvoked' event when clicked", async () => {
const { element, connect, disconnect } = await setupPickerMenuOption();
let wasInvoked: boolean = false;
element.addEventListener("pickeroptioninvoked", e => {
wasInvoked = true;
});
await connect();
element.click();
expect(wasInvoked).to.equal(true);
await disconnect();
});
}); | the_stack |
import pretty from 'pretty-format';
import each from '../';
const noop = () => {};
const expectFunction = expect.any(Function);
const get = (object, lensPath) =>
lensPath.reduce((acc, key) => acc[key], object);
const getGlobalTestMocks = () => {
const globals: any = {
describe: jest.fn(),
fdescribe: jest.fn(),
fit: jest.fn(),
it: jest.fn(),
test: jest.fn(),
xdescribe: jest.fn(),
xit: jest.fn(),
xtest: jest.fn(),
};
globals.test.only = jest.fn();
globals.test.skip = jest.fn();
globals.test.concurrent = jest.fn();
globals.test.concurrent.only = jest.fn();
globals.test.concurrent.skip = jest.fn();
globals.it.only = jest.fn();
globals.it.skip = jest.fn();
globals.describe.only = jest.fn();
globals.describe.skip = jest.fn();
return globals;
};
describe('jest-each', () => {
[
['test'],
['test', 'concurrent'],
['test', 'concurrent', 'only'],
['test', 'concurrent', 'skip'],
['test', 'only'],
['it'],
['fit'],
['it', 'only'],
['describe'],
['fdescribe'],
['describe', 'only'],
].forEach(keyPath => {
describe(`.${keyPath.join('.')}`, () => {
test('throws an error when not called with an array', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)(undefined);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(() =>
globalMock.mock.calls[0][1](),
).toThrowErrorMatchingSnapshot();
});
test('throws an error when called with an empty array', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(() =>
globalMock.mock.calls[0][1](),
).toThrowErrorMatchingSnapshot();
});
test('calls global with given title', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([[]]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(1);
expect(globalMock).toHaveBeenCalledWith(
'expected string',
expectFunction,
undefined,
);
});
test('calls global with given title when multiple tests cases exist', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([[], []]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
'expected string',
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
'expected string',
expectFunction,
undefined,
);
});
test('calls global with title containing param values when using printf format', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([
[
'hello',
1,
null,
undefined,
1.2,
{foo: 'bar'},
() => {},
[],
Infinity,
NaN,
],
[
'world',
1,
null,
undefined,
1.2,
{baz: 'qux'},
() => {},
[],
Infinity,
NaN,
],
]);
const testFunction = get(eachObject, keyPath);
testFunction(
'expected string: %% %%s %s %d %s %s %d %j %s %j %d %d %#',
noop,
);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
`expected string: % %s hello 1 null undefined 1.2 ${JSON.stringify({
foo: 'bar',
})} () => {} [] Infinity NaN 0`,
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
`expected string: % %s world 1 null undefined 1.2 ${JSON.stringify({
baz: 'qux',
})} () => {} [] Infinity NaN 1`,
expectFunction,
undefined,
);
});
test('does not call global test with title containing more param values than sprintf placeholders', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([
['hello', 1, 2, 3, 4, 5],
['world', 1, 2, 3, 4, 5],
]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string: %s', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
'expected string: hello',
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
'expected string: world',
expectFunction,
undefined,
);
});
test('calls global test title with %p placeholder injected at the correct positions', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([
['string1', 'pretty1', 'string2', 'pretty2'],
['string1', 'pretty1', 'string2', 'pretty2'],
]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string: %s %p %s %p', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
`expected string: string1 ${pretty('pretty1')} string2 ${pretty(
'pretty2',
)}`,
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
`expected string: string1 ${pretty('pretty1')} string2 ${pretty(
'pretty2',
)}`,
expectFunction,
undefined,
);
});
test('does not calls global test title with %p placeholder when no data is supplied at given position', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([
['string1', 'pretty1', 'string2'],
['string1', 'pretty1', 'string2'],
]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string: %s %p %s %p', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
`expected string: string1 ${pretty('pretty1')} string2 %p`,
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
`expected string: string1 ${pretty('pretty1')} string2 %p`,
expectFunction,
undefined,
);
});
test('calls global with cb function containing all parameters of each test case when given 1d array', () => {
const globalTestMocks = getGlobalTestMocks();
const testCallBack = jest.fn();
const eachObject = each.withGlobal(globalTestMocks)(['hello', 'world']);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', testCallBack);
const globalMock = get(globalTestMocks, keyPath);
globalMock.mock.calls[0][1]();
expect(testCallBack).toHaveBeenCalledTimes(1);
expect(testCallBack).toHaveBeenCalledWith('hello');
globalMock.mock.calls[1][1]();
expect(testCallBack).toHaveBeenCalledTimes(2);
expect(testCallBack).toHaveBeenCalledWith('world');
});
test('calls global with cb function containing all parameters of each test case 2d array', () => {
const globalTestMocks = getGlobalTestMocks();
const testCallBack = jest.fn();
const eachObject = each.withGlobal(globalTestMocks)([
['hello', 'world'],
['joe', 'bloggs'],
]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', testCallBack);
const globalMock = get(globalTestMocks, keyPath);
globalMock.mock.calls[0][1]();
expect(testCallBack).toHaveBeenCalledTimes(1);
expect(testCallBack).toHaveBeenCalledWith('hello', 'world');
globalMock.mock.calls[1][1]();
expect(testCallBack).toHaveBeenCalledTimes(2);
expect(testCallBack).toHaveBeenCalledWith('joe', 'bloggs');
});
test('calls global with given timeout', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([['hello']]);
const testFunction = get(eachObject, keyPath);
testFunction('some test', noop, 10000);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledWith(
'some test',
expect.any(Function),
10000,
);
});
test('calls global with title containing object property when using $variable', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([
{
a: 'hello',
b: 1,
c: null,
d: undefined,
e: 1.2,
f: {key: 'foo'},
g: () => {},
h: [],
i: Infinity,
j: NaN,
},
{
a: 'world',
b: 1,
c: null,
d: undefined,
e: 1.2,
f: {key: 'bar'},
g: () => {},
h: [],
i: Infinity,
j: NaN,
},
]);
const testFunction = get(eachObject, keyPath);
testFunction(
'expected string: %% %%s $a $b $c $d $e $f $f.key $g $h $i $j $#',
noop,
);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
'expected string: % %s hello 1 null undefined 1.2 {"key": "foo"} foo [Function g] [] Infinity NaN 0',
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
'expected string: % %s world 1 null undefined 1.2 {"key": "bar"} bar [Function g] [] Infinity NaN 1',
expectFunction,
undefined,
);
});
test('calls global with title containing param values when using both % placeholder and $variable', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([
{
a: 'hello',
b: 1,
},
{
a: 'world',
b: 1,
},
]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string: %p %# $a $b $#', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
'expected string: {"a": "hello", "b": 1} 0 $a $b $#',
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
'expected string: {"a": "world", "b": 1} 1 $a $b $#',
expectFunction,
undefined,
);
});
});
});
describe('done callback', () => {
test.each([
[['test']],
[['test', 'only']],
[['test', 'concurrent']],
[['test', 'concurrent', 'only']],
[['it']],
[['fit']],
[['it', 'only']],
])(
'calls %O with done when cb function has more args than params of given test row',
keyPath => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([['hello']]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', (hello, done) => {
expect(hello).toBe('hello');
expect(done).toBe('DONE');
});
get(globalTestMocks, keyPath).mock.calls[0][1]('DONE');
},
);
test.each([[['describe']], [['fdescribe']], [['describe', 'only']]])(
'does not call %O with done when test function has more args than params of given test row',
keyPath => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([['hello']]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', function (hello, done) {
expect(hello).toBe('hello');
expect(arguments.length).toBe(1);
expect(done).toBe(undefined);
});
get(globalTestMocks, keyPath).mock.calls[0][1]('DONE');
},
);
});
[
['xtest'],
['test', 'skip'],
['test', 'concurrent', 'skip'],
['xit'],
['it', 'skip'],
['xdescribe'],
['describe', 'skip'],
].forEach(keyPath => {
describe(`.${keyPath.join('.')}`, () => {
test('calls global with given title', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([[]]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(1);
expect(globalMock).toHaveBeenCalledWith(
'expected string',
expectFunction,
undefined,
);
});
test('calls global with given title when multiple tests cases exist', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([[], []]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string', noop);
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
'expected string',
expectFunction,
undefined,
);
});
test('calls global with title containing param values when using sprintf format', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([
['hello', 1],
['world', 2],
]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string: %s %s', () => {});
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(2);
expect(globalMock).toHaveBeenCalledWith(
'expected string: hello 1',
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
'expected string: world 2',
expectFunction,
undefined,
);
});
test('calls global with title with placeholder values correctly interpolated', () => {
const globalTestMocks = getGlobalTestMocks();
const eachObject = each.withGlobal(globalTestMocks)([
['hello', '%d', 10, '%s', {foo: 'bar'}],
['world', '%i', 1991, '%p', {foo: 'bar'}],
['joe', '%d %d', 10, '%%s', {foo: 'bar'}],
]);
const testFunction = get(eachObject, keyPath);
testFunction('expected string: %s %s %d %s %p', () => {});
const globalMock = get(globalTestMocks, keyPath);
expect(globalMock).toHaveBeenCalledTimes(3);
expect(globalMock).toHaveBeenCalledWith(
'expected string: hello %d 10 %s {"foo": "bar"}',
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
'expected string: world %i 1991 %p {"foo": "bar"}',
expectFunction,
undefined,
);
expect(globalMock).toHaveBeenCalledWith(
'expected string: joe %d %d 10 %%s {"foo": "bar"}',
expectFunction,
undefined,
);
});
});
});
}); | the_stack |
import * as errors from './errors';
export type Arrayish = string | ArrayLike<number>;
export interface Hexable {
toHexString(): string;
}
export interface Signature {
r: string;
s: string;
/* At least one of the following MUST be specified; the other will be derived */
recoveryParam?: number;
v?: number;
}
///////////////////////////////
export function isHexable(value: any): value is Hexable {
return !!value.toHexString;
}
function addSlice(array: Uint8Array): Uint8Array {
if (typeof array === 'object' && typeof array.slice === 'function') {
return array;
}
// tslint:disable-next-line: only-arrow-functions
array.slice = function() {
const args = Array.prototype.slice.call(arguments);
return addSlice(new Uint8Array(Array.prototype.slice.apply(array, [args[0], args[1]])));
};
return array;
}
export function isArrayish(value: any): value is Arrayish {
if (
!value ||
// tslint:disable-next-line: radix
parseInt(String(value.length)) !== value.length ||
typeof value === 'string'
) {
return false;
}
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < value.length; i++) {
const v = value[i];
// tslint:disable-next-line: radix
if (v < 0 || v >= 256 || parseInt(String(v)) !== v) {
return false;
}
}
return true;
}
export function arrayify(value: Arrayish | Hexable): Uint8Array | null {
if (value == null) {
errors.throwError('cannot convert null value to array', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
if (isHexable(value)) {
value = value.toHexString();
}
if (typeof value === 'string') {
const match = value.match(/^(0x)?[0-9a-fA-F]*$/);
if (!match) {
errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
if (match !== null && match[1] !== '0x') {
errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
value = value.substring(2);
if (value.length % 2) {
value = '0' + value;
}
const result = [];
for (let i = 0; i < value.length; i += 2) {
result.push(parseInt(value.substr(i, 2), 16));
}
return addSlice(new Uint8Array(result));
}
if (isArrayish(value)) {
return addSlice(new Uint8Array(value));
}
errors.throwError('invalid arrayify value', null, {
arg: 'value',
value,
type: typeof value,
});
return null;
}
export function concat(objects: Arrayish[]): Uint8Array {
if (objects === null) {
throw new Error(`concat objects is null`);
}
const arrays = [];
let length = 0;
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < objects.length; i++) {
const object = arrayify(objects[i]);
if (object == null) {
throw new Error('arrayify failed');
}
arrays.push(object);
length += object.length;
}
const result = new Uint8Array(length);
let offset = 0;
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < arrays.length; i++) {
result.set(arrays[i], offset);
offset += arrays[i].length;
}
return addSlice(result);
}
export function stripZeros(value: Arrayish): Uint8Array {
let result: Uint8Array | null = arrayify(value);
if (result === null) {
throw new Error('arrayify failed');
}
if (result.length === 0) {
return result;
}
// Find the first non-zero entry
let start = 0;
while (result[start] === 0) {
start++;
}
// If we started with zeros, strip them
if (start) {
result = result.slice(start);
}
return result;
}
export function padZeros(value: Arrayish, length: number): Uint8Array {
const arrayifyValue = arrayify(value);
if (arrayifyValue === null) {
throw new Error('arrayify failed');
}
if (length < arrayifyValue.length) {
throw new Error('cannot pad');
}
const result = new Uint8Array(length);
result.set(arrayifyValue, length - arrayifyValue.length);
return addSlice(result);
}
export function isHexString(value: any, length?: number): boolean {
if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) {
return false;
}
if (length && value.length !== 2 + 2 * length) {
return false;
}
return true;
}
const HexCharacters: string = '0123456789abcdef';
export function hexlify(value: Arrayish | Hexable | number): string {
if (isHexable(value)) {
return value.toHexString();
}
if (typeof value === 'number') {
if (value < 0) {
errors.throwError('cannot hexlify negative value', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
// @TODO: Roll this into the above error as a numeric fault (overflow); next version, not backward compatible
// We can about (value == MAX_INT) to as well, since that may indicate we underflowed already
if (value >= 9007199254740991) {
errors.throwError('out-of-range', errors.NUMERIC_FAULT, {
operartion: 'hexlify',
fault: 'out-of-safe-range',
});
}
let hex = '';
while (value) {
hex = HexCharacters[value & 0x0f] + hex;
value = Math.floor(value / 16);
}
if (hex.length) {
if (hex.length % 2) {
hex = '0' + hex;
}
return '0x' + hex;
}
return '0x00';
}
if (typeof value === 'string') {
const match = value.match(/^(0x)?[0-9a-fA-F]*$/);
if (!match) {
errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
if (match !== null && match[1] !== '0x') {
errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
if (value.length % 2) {
value = '0x0' + value.substring(2);
}
return value;
}
if (isArrayish(value)) {
const result = [];
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < value.length; i++) {
const v = value[i];
result.push(HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]);
}
return '0x' + result.join('');
}
errors.throwError('invalid hexlify value', null, {
arg: 'value',
value,
});
return 'never';
}
export function hexDataLength(data: string) {
if (!isHexString(data) || data.length % 2 !== 0) {
return null;
}
return (data.length - 2) / 2;
}
export function hexDataSlice(data: string, offset: number, endOffset?: number): string {
if (!isHexString(data)) {
errors.throwError('invalid hex data', errors.INVALID_ARGUMENT, {
arg: 'value',
value: data,
});
}
if (data.length % 2 !== 0) {
errors.throwError('hex data length must be even', errors.INVALID_ARGUMENT, {
arg: 'value',
value: data,
});
}
offset = 2 + 2 * offset;
if (endOffset != null) {
return '0x' + data.substring(offset, 2 + 2 * endOffset);
}
return '0x' + data.substring(offset);
}
export function hexStripZeros(value: string): string {
if (!isHexString(value)) {
errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
while (value.length > 3 && value.substring(0, 3) === '0x0') {
value = '0x' + value.substring(3);
}
return value;
}
export function hexZeroPad(value: string, length: number): string {
if (!isHexString(value)) {
errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
while (value.length < 2 * length + 2) {
value = '0x0' + value.substring(2);
}
return value;
}
export function bytesPadLeft(value: string, byteLength: number): string {
if (!isHexString(value)) {
errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
const striped = value.substring(2);
if (striped.length > byteLength * 2) {
throw new Error(`hex string length = ${striped.length} beyond byteLength=${byteLength}`);
}
const padLength = byteLength * 2 - striped.length;
const returnValue = '0x' + '0'.repeat(padLength) + striped;
return returnValue;
}
export function bytesPadRight(value: string, byteLength: number): string {
if (!isHexString(value)) {
errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, {
arg: 'value',
value,
});
}
const striped = value.substring(2);
if (striped.length > byteLength * 2) {
throw new Error(`hex string length = ${striped.length} beyond byteLength=${byteLength}`);
}
const padLength = byteLength * 2 - striped.length;
const returnValue = '0x' + striped + '0'.repeat(padLength);
return returnValue;
}
export function isSignature(value: any): value is Signature {
return value && value.r != null && value.s != null;
}
export function splitSignature(signature: Arrayish | Signature): Signature {
if (signature !== undefined) {
let v = 0;
let r = '0x';
let s = '0x';
if (isSignature(signature)) {
if (signature.v == null && signature.recoveryParam == null) {
errors.throwError(
'at least on of recoveryParam or v must be specified',
errors.INVALID_ARGUMENT,
{ argument: 'signature', value: signature },
);
}
r = hexZeroPad(signature.r, 32);
s = hexZeroPad(signature.s, 32);
v = signature.v || 0;
if (typeof v === 'string') {
v = parseInt(v, 16);
}
let recoveryParam = signature.recoveryParam || 0;
if (recoveryParam == null && signature.v != null) {
recoveryParam = 1 - (v % 2);
}
v = 27 + recoveryParam;
} else {
const bytes: Uint8Array = arrayify(signature) || new Uint8Array();
if (bytes.length !== 65) {
throw new Error('invalid signature');
}
r = hexlify(bytes.slice(0, 32));
s = hexlify(bytes.slice(32, 64));
v = bytes[64];
if (v !== 27 && v !== 28) {
v = 27 + (v % 2);
}
}
return {
r,
s,
recoveryParam: v - 27,
v,
};
} else {
throw new Error('signature is not found');
}
}
export function joinSignature(signature: Signature): string {
signature = splitSignature(signature);
return hexlify(concat([signature.r, signature.s, signature.recoveryParam ? '0x1c' : '0x1b']));
}
/**
* hexToByteArray
*
* Convers a hex string to a Uint8Array
*
* @param {string} hex
* @returns {Uint8Array}
*/
export const hexToByteArray = (hex: string): Uint8Array => {
const res = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
res[i / 2] = parseInt(hex.substring(i, i + 2), 16);
}
return res;
};
/**
* hexToIntArray
*
* @param {string} hex
* @returns {number[]}
*/
export const hexToIntArray = (hex: string): number[] => {
if (!hex || !isHex(hex)) {
return [];
}
const res = [];
for (let i = 0; i < hex.length; i++) {
const c = hex.charCodeAt(i);
const hi = c >> 8;
const lo = c & 0xff;
hi ? res.push(hi, lo) : res.push(lo);
}
return res;
};
/**
* isHex
*
* @param {string} str - string to be tested
* @returns {boolean}
*/
export const isHex = (str: string): boolean => {
const plain = str.replace('0x', '');
return /[0-9a-f]*$/i.test(plain);
}; | the_stack |
import { Nullable } from "../../types";
import { Scene } from "../../scene";
import { Matrix } from "../../Maths/math.vector";
import { InternalTexture } from "../../Materials/Textures/internalTexture";
import { BaseTexture } from "../../Materials/Textures/baseTexture";
import { Constants } from "../../Engines/constants";
import { RegisterClass } from "../../Misc/typeStore";
import { ThinEngine } from "../../Engines/thinEngine";
// Ensures Raw texture are included
import "../../Engines/Extensions/engine.rawTexture";
/**
* This represents a color grading texture. This acts as a lookup table LUT, useful during post process
* It can help converting any input color in a desired output one. This can then be used to create effects
* from sepia, black and white to sixties or futuristic rendering...
*
* The only supported format is currently 3dl.
* More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
*/
export class ColorGradingTexture extends BaseTexture {
/**
* The texture URL.
*/
public url: string;
/**
* Empty line regex stored for GC.
*/
private static _noneEmptyLineRegex = /\S+/;
private _textureMatrix: Matrix;
private _onLoad: Nullable<() => void>;
/**
* Instantiates a ColorGradingTexture from the following parameters.
*
* @param url The location of the color grading data (currently only supporting 3dl)
* @param sceneOrEngine The scene or engine the texture will be used in
* @param onLoad defines a callback triggered when the texture has been loaded
*/
constructor(url: string, sceneOrEngine: Scene | ThinEngine, onLoad: Nullable<() => void> = null) {
super(sceneOrEngine);
if (!url) {
return;
}
this._textureMatrix = Matrix.Identity();
this.name = url;
this.url = url;
this._onLoad = onLoad;
this._texture = this._getFromCache(url, true);
if (!this._texture) {
const scene = this.getScene();
if (scene) {
if (!scene.useDelayedTextureLoading) {
this.loadTexture();
} else {
this.delayLoadState = Constants.DELAYLOADSTATE_NOTLOADED;
}
}
else {
this.loadTexture();
}
}
else {
this._triggerOnLoad();
}
}
/**
* Fires the onload event from the constructor if requested.
*/
private _triggerOnLoad(): void {
if (this._onLoad) {
this._onLoad();
}
}
/**
* Returns the texture matrix used in most of the material.
* This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
*/
public getTextureMatrix(): Matrix {
return this._textureMatrix;
}
/**
* Occurs when the file being loaded is a .3dl LUT file.
*/
private load3dlTexture() {
var engine = this._getEngine()!;
var texture: InternalTexture;
if (!engine._features.support3DTextures) {
texture = engine.createRawTexture(null, 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_BILINEAR_SAMPLINGMODE, null, Constants.TEXTURETYPE_UNSIGNED_INT);
}
else {
texture = engine.createRawTexture3D(null, 1, 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_BILINEAR_SAMPLINGMODE, null, Constants.TEXTURETYPE_UNSIGNED_INT);
}
this._texture = texture;
this._texture.isReady = false;
this.isCube = false;
this.is3D = engine._features.support3DTextures;
this.wrapU = Constants.TEXTURE_CLAMP_ADDRESSMODE;
this.wrapV = Constants.TEXTURE_CLAMP_ADDRESSMODE;
this.wrapR = Constants.TEXTURE_CLAMP_ADDRESSMODE;
this.anisotropicFilteringLevel = 1;
var callback = (text: string | ArrayBuffer) => {
if (typeof text !== "string") {
return;
}
var data: Nullable<Uint8Array> = null;
var tempData: Nullable<Float32Array> = null;
var line: string;
var lines = text.split('\n');
var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
var maxColor = 0;
for (let i = 0; i < lines.length; i++) {
line = lines[i];
if (!ColorGradingTexture._noneEmptyLineRegex.test(line)) {
continue;
}
if (line.indexOf('#') === 0) {
continue;
}
var words = line.split(" ");
if (size === 0) {
// Number of space + one
size = words.length;
data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
tempData = new Float32Array(size * size * size * 4);
continue;
}
if (size != 0) {
var r = Math.max(parseInt(words[0]), 0);
var g = Math.max(parseInt(words[1]), 0);
var b = Math.max(parseInt(words[2]), 0);
maxColor = Math.max(r, maxColor);
maxColor = Math.max(g, maxColor);
maxColor = Math.max(b, maxColor);
var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
if (tempData) {
tempData[pixelStorageIndex + 0] = r;
tempData[pixelStorageIndex + 1] = g;
tempData[pixelStorageIndex + 2] = b;
}
// Keep for reference in case of back compat problems.
// pixelIndexSlice++;
// if (pixelIndexSlice % size == 0) {
// pixelIndexH++;
// pixelIndexSlice = 0;
// if (pixelIndexH % size == 0) {
// pixelIndexW++;
// pixelIndexH = 0;
// }
// }
pixelIndexH++;
if (pixelIndexH % size == 0) {
pixelIndexSlice++;
pixelIndexH = 0;
if (pixelIndexSlice % size == 0) {
pixelIndexW++;
pixelIndexSlice = 0;
}
}
}
}
if (tempData && data) {
for (let i = 0; i < tempData.length; i++) {
if (i > 0 && (i + 1) % 4 === 0) {
data[i] = 255;
}
else {
var value = tempData[i];
data[i] = (value / maxColor * 255);
}
}
}
if (texture.is3D) {
texture.updateSize(size, size, size);
engine.updateRawTexture3D(texture, data, Constants.TEXTUREFORMAT_RGBA, false);
}
else {
texture.updateSize(size * size, size);
engine.updateRawTexture(texture, data, Constants.TEXTUREFORMAT_RGBA, false);
}
texture.isReady = true;
this._triggerOnLoad();
};
let scene = this.getScene();
if (scene) {
scene._loadFile(this.url, callback);
}
else {
engine._loadFile(this.url, callback);
}
return this._texture;
}
/**
* Starts the loading process of the texture.
*/
private loadTexture() {
if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
this.load3dlTexture();
}
}
/**
* Clones the color grading texture.
*/
public clone(): ColorGradingTexture {
var newTexture = new ColorGradingTexture(this.url, this.getScene() || this._getEngine()!);
// Base texture
newTexture.level = this.level;
return newTexture;
}
/**
* Called during delayed load for textures.
*/
public delayLoad(): void {
if (this.delayLoadState !== Constants.DELAYLOADSTATE_NOTLOADED) {
return;
}
this.delayLoadState = Constants.DELAYLOADSTATE_LOADED;
this._texture = this._getFromCache(this.url, true);
if (!this._texture) {
this.loadTexture();
}
}
/**
* Parses a color grading texture serialized by Babylon.
* @param parsedTexture The texture information being parsedTexture
* @param scene The scene to load the texture in
* @param rootUrl The root url of the data assets to load
* @return A color grading texture
*/
public static Parse(parsedTexture: any, scene: Scene): Nullable<ColorGradingTexture> {
var texture = null;
if (parsedTexture.name && !parsedTexture.isRenderTarget) {
texture = new ColorGradingTexture(parsedTexture.name, scene);
texture.name = parsedTexture.name;
texture.level = parsedTexture.level;
}
return texture;
}
/**
* Serializes the LUT texture to json format.
*/
public serialize(): any {
if (!this.name) {
return null;
}
var serializationObject: any = {};
serializationObject.name = this.name;
serializationObject.level = this.level;
serializationObject.customType = "BABYLON.ColorGradingTexture";
return serializationObject;
}
}
RegisterClass("BABYLON.ColorGradingTexture", ColorGradingTexture); | the_stack |
import { readFileSync } from 'fs'
import { resolve } from 'path'
import * as prettier from 'prettier'
import { sourceTextToKey } from '../util/locale'
import { needTranslate, wrapCode as wrap } from './wrap/tsx-wrapper'
const format = (str: string) => {
return prettier.format(str, { parser: 'babel-ts' })
}
const wrapCode = (...args: Parameters<typeof wrap>) => wrap(...args).output
describe('wrap', () => {
test('needTranslate() should return true for non-ascii words and sentences', () => {
const n = needTranslate
expect(n('')).toBe(false)
expect(n(' ')).toBe(false)
expect(n('\t')).toBe(false)
expect(n(' ')).toBe(false) // nbsp
expect(n(' \n ')).toBe(false)
expect(n('some')).toBe(false)
expect(n('some thing')).toBe(false)
expect(n('+-*/!@#$%^&*()_+|-=`~[]{};\':",./<>?')).toBe(false)
expect(n('中文')).toBe(true)
const hellos = [
// 'Afrikaans ~ Hallo (Don.Rodrigo)',
'Albanian ~ Mirë dita (OKAMOTO_Yusuke)',
'Amharic ~ ታዲያስ Pronunciation: tadiyas (Adamyoung97)',
'Arabic ~ مرحبا or مَرْحَبًا Pronunciation: marhaban or Marhabaa (Adamyoung97 and MaeeSafaee)',
'Azerbaijani ~ Салам or سلام Pronunciation: Salam (Andro777)',
'Bengali ~ নমস্কার Pronunciation: nomoshkaar or namaskar (TanytopiSal)',
// 'Bosnian ~ Zdravo (89Edina89 )',
'Bulgarian (Formal) ~ Здравей Pronunciation: zdravey (samuelianadams)',
'Bulgarian (Informal) ~ Здрасти Pronunciation: zdrasti (samuelianadams)',
// 'Croatian ~ Bok (Diogo.D)',
// 'Czech ~ ahoj (Inkybaba)',
// 'Danish ~ Hej (Brenzo44)',
// 'Dutch ~ Hallo (Snowflake_s)',
// 'English ~ Hello',
// 'Esperanto ~ Saluton (JessePaedia and Rythmixed)',
// 'Estonian ~ Tere (Inkybaba)',
'Farsi ~ سلام or درود بر تو or درود بر شما Pronunciation: Salaam or Dorood bar to or D orood bar shoma (MaeeSafaee and Andro777)',
// 'Fijian ~ Bula (JessePaedia)',
// 'Finnish ~ Terve (CreeperGhostGirl)',
// 'French (Formal)~ Bonjour (CatGirl97)',
// 'French (Informal) ~ Salut (CatGirl97)',
// 'German ~Hallo (Snowflake_s)',
'Greek ~ Γεια σου Pronunciation: yiassoo (Diogo.D)',
// 'Hawaiian ~ Aloha (jabramsohn)',
'Hebrew ~ שלום Pronunciation: Shalom (HellerM and Adamyoung97)',
'Hindi ~ नमस्ते Pronunciation: Namastē (Remoonline)',
// 'Hungarian (Plural) ~ Sziasztok (Stuttgart3)',
// 'Hungarian (Singular) ~ Szia (Adamyoung97)',
// 'Indonesian ~ Halo or Hai (JessePaedia)',
// 'Irish (Plural) ~ Dia dhaoibh (BryanEDU)',
// 'Irish (Singular)~ Dia dhuit (BryanEDU)',
// 'Italian (Formal) ~ Salve (AV_5100)',
// 'Italian (Informal) ~ Ciao (Jaycat1234)',
"Japanese ~ こんにちは Pronunciation: Kon'nichiwa (CreeperGhostGirl and Nitram15)",
'Kannada ~ ನಮಸ್ಕಾರ Pronunciation: namaskār (LeMaitre)',
'Khmer (Formal) ~ ជំរាបសួរ Pronunciation: cham reap sour (Anna._)',
'Korean (Formal) ~ 안녕하세요 Pronunciation: an-nyeong-ha-se-yo (Anna._)',
'Korean (Informal) ~ 안녕 Pronunciation: annyeong (TheBryce and Anna._)',
'Lao: ~ ສະບາຍດີ Pronunciation: Sabaai-dii (OKAMOTO_Yusuke)',
// 'Latin (Plural) ~ Salvete (Knittingirl)',
// 'Latin (Singular) ~ Salve (Knittingirl)',
// 'Latvian ~ Sveiki (Inkybaba)',
// 'Limburgish ~ Hallau (Don.Rodrigo)',
// 'Lithuanian ~ Sveiki (Inkybaba)',
'Macedonian ~ Добар ден Pronunciation: Dobar den (OKAMOTO_Yusuke)',
// 'Malaysian (Noon to 2pm) ~ Selamat tengahari (OKAMOTO_Yusuke)',
// 'Malaysian (2pm to sunset) ~ Selamat petang (OKAMOTO_Yusuke)',
'Maltese ~ Ħelow (CreeperGhostGirl and StrapsOption)',
'Mandarin Chinese ~ 你好 Pronunciation: nǐ hǎo (Rhythmialex)',
// 'Maori ~ Kia ora (JessePaedia)',
// 'Norwegian ~ Hei (AV_5100)',
'Odia ~ ନମସ୍କାର Pronunciation: Namaskār (Remoonline)',
'Polish ~ Cześć or Hej (Baakamono)',
// 'Portuguese ~ Oi (Diogo.D)',
// 'Romanian ~ alo or salut (Inkybaba)',
'Russian ~ Здравствуйте Pronunciation: Zdrahstvootye or Привет Pronunciation: Preevyet (Language020)',
'Scottish Gaelic ~ Haló (ADSharpe)',
'Serbian ~ Здраво Pronunciation: Zdravo (De_aapje)',
'Shanghainese ~ 侬好 Pronunciation: noŋ hɔ (OKAMOTO_Yusuke)',
// 'Slovak ~ ahoj (Inkybaba)',
// 'Spanish ~ Hola',
'Swabian ~ Grüss Gott (DrWho100)',
// 'Swahili ~ Hujambo (S-G-Miller)',
'Swedish ~ Hej or Hallá (Brenzo44 and Krekt)',
// 'Swiss German (Informal) ~ Hoi (Jabramsohn)',
'Swiss German (Plural, Formal) ~ Grüezi mitenand (Jabramsohn)',
'Swiss German (Singular, Formal) ~ Grüezi (Jabramsohn)',
'Tamil ~ வனக்கம் Pronunciation: vanakkam (LeMaitre)',
'Telugu ~ నమస్కారం Pronunciation: namaskāram (LeMaitre)',
'Thai (Female) ~ สวัสดีค่ะ Pronunciation: sawatdeekha (Anna._)',
'Thai (Male) ~ สวัสดีครับ pronunciation: sawatdeekhrap (Anna._)',
// 'Turkish ~ Merhaba (AV_5100)',
'Vietnamese ~ Xin chào (Krekt)',
// 'Woiworung ~ Womenjeka (JessePaedia)',
'Yiddish ~ שלום Pronunciation: Sholem (S-G-Miller and Jabramsohn)',
]
hellos.forEach((str) => {
let [_, word] = /~ ([^\(]+) \(/.exec(str) || []
word = word.replace(/pronunciation.+$/gi, '')
expect(n(word)).toEqual(true)
})
})
test('add a18n() calls ', () => {
const source = readFileSync(
resolve(__dirname, '../../src/cli/__test__/wrap-input.mock.tsx'),
{ encoding: 'utf-8' },
)
const expected = readFileSync(
resolve(__dirname, '../../src/cli/__test__/wrap-output.mock.tsx'),
{ encoding: 'utf-8' },
)
expect(format(wrapCode(source, { namespace: undefined }))).toBe(
format(expected),
)
// ensure we don't double wrap a18n()
expect(wrapCode(expected, { namespace: undefined })).toBe(expected)
})
test('returns unwrapped "sourceTexts" when checkOnly=true', () => {
const source = readFileSync(
resolve(__dirname, '../../src/cli/__test__/wrap-input.mock.tsx'),
{ encoding: 'utf-8' },
)
const { sourceTexts } = wrap(source, { checkOnly: true })
const keys = sourceTexts.map(sourceTextToKey)
expect(keys).toEqual([
'中文',
'中文',
'中文2',
'中文22',
'eng 中间有中文 lish',
'中文%s',
'星期%s',
'周%s',
'我喜欢',
'这样子',
'生活',
'我喜欢',
'这样子',
'中文3',
])
})
test('igore file containing `@a18n-ignore-file` ', () => {
const source = `// @a18n-ignore-file
const s = '中文'
`
const expected = `// @a18n-ignore-file
const s = '中文'
`
expect(wrapCode(source, { namespace: undefined })).toBe(expected)
// ensure we don't double wrap a18n()
expect(wrapCode(expected, { namespace: undefined })).toBe(expected)
})
describe('add import statement: without namespace', () => {
test(`don't add if not needed`, () => {
expect(wrapCode(`const s = 'english'`, { namespace: undefined })).toBe(
`const s = 'english'`,
)
})
test('add import statement', () => {
expect(wrapCode(`const s = '中文'`, { namespace: undefined }))
.toBe(`import a18n from 'a18n'
const s = a18n('中文')`)
})
test(`don't add import statement if existed`, () => {
expect(
wrapCode(
`import a18n from 'a18n'
const s = '中文'`,
{ namespace: undefined },
),
).toBe(`import a18n from 'a18n'
const s = a18n('中文')`)
})
test(`don't unnecessarily change existed import statement`, () => {
expect(
wrapCode(
`import * as React from 'react'
import a18n from 'a18n'
const s = '中文'`,
{ namespace: undefined },
),
).toBe(`import * as React from 'react'
import a18n from 'a18n'
const s = a18n('中文')`)
})
test(`add require() if code base is using require()`, () => {
expect(
wrapCode(
`const React = require('react')
const s = '中文'`,
{ namespace: undefined },
),
).toBe(`const a18n = require('a18n')
const React = require('react')
const s = a18n('中文')`)
})
})
describe('add import statement: with namespace', () => {
test("don't need import/require", () => {
expect(
wrapCode(`const s = 'english'`, { namespace: 'my-namespace' }),
).toBe(`const s = 'english'`)
})
test(`add import`, () => {
expect(wrapCode(`const s = '中文'`, { namespace: 'my-namespace' }))
.toBe(`import { getA18n } from 'a18n'
const a18n = getA18n('my-namespace')
const s = a18n('中文')`)
})
test(`replace import: replace non-namespaced a18n`, () => {
expect(
wrapCode(
`import a18n from 'a18n'
const s = '中文'`,
{ namespace: 'my-namespace' },
),
).toBe(`import { getA18n } from 'a18n'
const a18n = getA18n('my-namespace')
const s = a18n('中文')`)
})
test(`replace import: replace namespaced a18n`, () => {
expect(
wrapCode(
`import { getA18n } from 'a18n'
const a18n = getA18n('your-namespace')
const s = a18n('中文')`,
{ namespace: 'my-namespace' },
),
).toBe(`import { getA18n } from 'a18n'
const a18n = getA18n('my-namespace')
const s = a18n('中文')`)
})
test(`retain import: don't make unnecessary change`, () => {
expect(
wrapCode(
`import * as React from 'react'
import { getA18n } from 'a18n'
const a18n = getA18n('your-namespace')
const s = a18n('中文')`,
{ namespace: 'your-namespace' },
),
).toBe(`import * as React from 'react'
import { getA18n } from 'a18n'
const a18n = getA18n('your-namespace')
const s = a18n('中文')`)
})
test(`add require`, () => {
expect(
wrapCode(
`const React = require('react')
const s = '中文'`,
{ namespace: 'my-namespace' },
),
).toBe(`const { getA18n } = require('a18n')
const a18n = getA18n('my-namespace')
const React = require('react')
const s = a18n('中文')`)
})
test(`replace require: replace non-namespaced a18n`, () => {
expect(
wrapCode(
`const a18n = require('a18n')
const s = '中文'`,
{ namespace: 'my-namespace' },
),
).toBe(`const { getA18n } = require('a18n')
const a18n = getA18n('my-namespace')
const s = a18n('中文')`)
})
test(`replace require: replace namespaced a18n`, () => {
expect(
wrapCode(
`const { getA18n } = require('a18n')
const a18n = getA18n('your-namespace')
const s = a18n('中文')`,
{ namespace: 'my-namespace' },
),
).toBe(`const { getA18n } = require('a18n')
const a18n = getA18n('my-namespace')
const s = a18n('中文')`)
})
})
}) | the_stack |
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Organization } from './org-form/Organization';
import { Asset } from './asset-form/Asset';
import { Assessment } from './assessment-form/Assessment';
import { DomSanitizer } from '@angular/platform-browser';
import { environment } from '../environments/environment';
import { User } from './interfaces/User';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class AppService {
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {}
api = environment.apiUrl;
/**
* Function is responsible for initial retrevial of organizations on dashboard loading
* @returns all organization information to the dashboard
*/
getOrganizations() {
return this.http
.get(`${this.api}/organization`)
.toPromise()
.then(async (res) => {
return res;
});
}
/**
* Function responsible for retreval of organizations archived status.
* @returns Data for organizations that have been archived.
*/
getArchivedOrganizations() {
const httpOptions = {
responseType: 'blob' as 'json',
};
return this.http
.get(`${this.api}/organization/archive`)
.toPromise()
.then(async (res) => {
return res;
});
}
/**
* Function is responsible for retreval of images as blogs using the ID association
* @param file accepts the id assigned to a file
* @returns the image associated with the id
*/
getImageById(file: any) {
const httpOptions = {
responseType: 'blob' as 'json',
};
return this.http
.get(`${this.api}/file/${file.id}`, httpOptions)
.toPromise()
.then((res: Blob) => {
return this.createObjectUrl(res, file.mimetype);
});
}
/**
* Function is responsible for retreving an organization based on ID passed
* @param id is the ID of the organization being requested
* @returns all information related to the organization requested
*/
getOrganizationById(id: number) {
return this.http
.get(`${this.api}/organization/${id}`)
.toPromise()
.then((res) => {
return res;
});
}
/**
* Function returns all active assets related to the organization ID
* @param id is the ID of the organization
* @returns all assets related to the organization passed
*/
getOrganizationAssets(id: number) {
return this.http
.get(`${this.api}/organization/asset/${id}`)
.toPromise()
.then((res) => {
return res;
});
}
/**
* Function returns all open vulnerabilities by Asset ID
* @param assetId
* @returns open asset vulnerabilities
*/
getOpenVulnsByAssetId(assetId: number) {
return this.http.get(`${this.api}/asset/${assetId}/open/vulnerabilities`);
}
/**
* Function returns all archived assets related to the organization ID
* @param id is the ID of the organization
* @returns all assets related to the organization passed
*/
getOrganizationArchiveAssets(id: number) {
return this.http.get(`${this.api}/organization/${id}/asset/archive`);
}
/**
* Function is responsible for archiving an organization by altering it's status
* @param id is the organization being passed for archiving
* @returns updates the status of the organization and reports the http status returned
*/
archiveOrganization(id: number) {
return this.http.patch(`${this.api}/organization/${id}/archive`, null);
}
/**
* Function is responsible for unarchving an organization by alterint it's status
* @param id is the organization being passed for archiving
* @returns updates the status of the organization and reports the http status returned
*/
activateOrganization(id: number) {
return this.http.patch(`${this.api}/organization/${id}/activate`, null);
}
/**
* Function is responsible for returning all assessements related to an organization
* @param id is the organization ID associated with the assessements
* @returns all assessments related to the organization
*/
getAssessments(id: number) {
return this.http
.get(`${this.api}/assessment/${id}`)
.toPromise()
.then((res) => {
return res as object[];
});
}
/**
* Delete assessment by ID
* @returns success/error message
*/
deleteAssessment(assessmentId: number) {
return this.http.delete(`${this.api}/assessment/${assessmentId}`);
}
/**
* Function is responsible for returning all vulnerabilites related to an assessment
* @param assessmentId is the ID associated with the assessment
* @returns all vulnerablities related to the assessment
*/
getVulnerabilities(assessmentId: number) {
return this.http.get(
`${this.api}/assessment/${assessmentId}/vulnerability`
);
}
/**
* Function is responsible for returning a vulnerablity called by it's ID
* @param id associated to the vulnerability requested
* @returns all object related data to the vulnerability requested
*/
getVulnerability(id: number) {
return this.http.get(`${this.api}/vulnerability/${id}`);
}
exportVulnToJira(vulnId: number) {
return this.http.get(`${this.api}/vulnerability/jira/${vulnId}`);
}
exportAssessmentToJira(assessmentId: number) {
return this.http.get(`${this.api}/assessment/jira/${assessmentId}`);
}
getConfig() {
return this.http.get(`${this.api}/config`);
}
updateConfig(config: FormData) {
return this.http.post(`${this.api}/config`, config);
}
/**
* Function is responsible for updating a vulnerability by ID
* @param id is associated with the requested vulnerability
* @param vuln is associated with the form data passed as an object
* @returns http status code for the return value
*/
updateVulnerability(id: number, vuln: FormData) {
return this.http.patch(`${this.api}/vulnerability/${id}`, vuln);
}
/**
* Function is responsible for creating a vulnerability for an assessment
* @param vuln contains the form object data for all required fields
* @returns http status code of the request
*/
createVuln(vuln: FormData) {
return this.http.post(`${this.api}/vulnerability`, vuln);
}
/**
* Function is responsible for deletion of a vulnerability
* @param vulnId is the ID association to the vulnerability
* @returns http status code of the request
*/
deleteVuln(vulnId: number) {
return this.http.delete(`${this.api}/vulnerability/${vulnId}`);
}
/**
* Function is responsible for creating a new organization
* @param org object of the form data passed to the API
* @returns http status code of the request
*/
createOrg(org: Organization) {
return this.http.post(`${this.api}/organization`, org);
}
/**
* Function is responsible for updating an organization
* @param id is the organization ID being updated
* @param org is the form object data passed to the API
* @returns http status code of the request
*/
updateOrg(id: number, org: Organization) {
return this.http.patch(`${this.api}/organization/${id}`, org);
}
/**
* Function is responsible for creating a new asset tied to an organization
* @param asset is the form object data for the new asset
* @returns http status code of the request
*/
createAsset(asset: Asset) {
return this.http.post(
`${this.api}/organization/${asset.organization}/asset`,
asset
);
}
purgeJira(assetId: number) {
return this.http.delete(`${this.api}/asset/jira/${assetId}`);
}
/**
* Function is responsible for fetching assets
* @param assetId asset ID being requested
* @param orgId associated organization ID attached to the asset
* @returns https status code of the request
*/
getAsset(assetId: number, orgId: number) {
return this.http.get(`${this.api}/organization/${orgId}/asset/${assetId}`);
}
/**
* Function is responsible for updating an asset
* @param asset is the ID associated to the asset
* @returns http status code of the request
*/
updateAsset(asset: Asset) {
return this.http.patch(
`${this.api}/organization/${asset.organization}/asset/${asset.id}`,
asset
);
}
/**
* Function is responsible for archiving an asset
* @param asset is the ID associated to the asset
* @returns http status code of the request
*/
archiveAsset(asset: Asset) {
return this.http.patch(`${this.api}/asset/archive/${asset.id}`, {});
}
/**
* Function is responsible for activating an asset
* @param asset is the ID associated to the asset
* @returns http status code of the request
*/
activateAsset(asset: Asset) {
return this.http.patch(`${this.api}/asset/activate/${asset.id}`, {});
}
/**
* Function is responsible for creating new assessments
* @param assessment data contained in the assessment form object
* @returns http status code of the request
*/
createAssessment(assessment: Assessment) {
return this.http.post(`${this.api}/assessment`, assessment);
}
/**
* Function is responsible for updating an assessment's data
* @param assessment form object data of the assessment
* @param assessmentId associated ID of the assessment being altered
* @param assetId asset ID attached to the request ties into the assessment ID
* @returns http status code of the request
*/
updateAssessment(
assessment: Assessment,
assessmentId: number,
assetId: number
) {
return this.http.patch(
`${this.api}/asset/${assetId}/assessment/${assessmentId}`,
assessment
);
}
/**
* Function is responsible for retrevial of assessments
* @param assetId associated asset ID required
* @param assessmentId associated assessment ID required
* @returns http status code with object data from the API call
*/
getAssessment(assetId: number, assessmentId: number) {
return this.http.get(
`${this.api}/asset/${assetId}/assessment/${assessmentId}`
);
}
/**
* Function is responsible for uploading files, attaching them to the resource requesting it
* @param fileToUpload form object data for the files associated in the request
* @returns http status code of the request
*/
upload(fileToUpload: File) {
const formData: FormData = new FormData();
formData.append('file', fileToUpload);
return this.http.post(`${this.api}/upload`, formData);
}
/**
* Function is responsible for uploading multi-part data associated with files.
* @param fileToUpload form object data holding the file objects required
* @returns http status code of the request
*/
uploadMultiple(fileToUpload: FormData) {
return this.http.post(`${this.api}/upload-multiple`, fileToUpload);
}
/**
* Function is responsible for report retrevial
* @param assessmentId required ID of the assessment for object data relations
* @returns http status request and object data for the report
*/
getReport(assessmentId: number) {
return this.http.get(`${this.api}/assessment/${assessmentId}/report`);
}
/**
* Function is responsible for report generation
* @param orgId requires associated data from the organization ID
* @param assetId requires associated data from the asset ID
* @param assessmentId requires associated data from the assessment ID
* @returns http status code of the request along with a new tab with a generated report
*/
generateReport(orgId: number, assetId: number, assessmentId: number) {
const httpOptions = {
responseType: 'blob' as 'json',
};
const generateObject = {
orgId,
assetId,
assessmentId,
};
return this.http.post(
`${this.api}/report/generate`,
generateObject,
httpOptions
);
}
/**
* Function is responsible for generating URL's to provide accessable data, reports, images, and
* any other downloadble content.
* @param file requires the file object to be called
* @param [mimetype] requires the mimetype of the data
* @returns new URL with the object requested in a sanatized manner
*/
public createObjectUrl(file, mimetype?: string) {
// Preview unsaved form
const blob = new Blob([file], {
type: mimetype || file.type,
});
const url = window.URL.createObjectURL(blob);
return this.sanitizer.bypassSecurityTrustUrl(url);
}
} | the_stack |
import React, { useState } from 'react';
import styled from 'styled-components';
import { useLocation, match, useHistory, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { getPath, getRouteMatch, KnownURLParams } from '../../utils/routing';
import Button, { ButtonLink, ButtonCSS, BigButton } from '../Button';
import Icon from '../Icon';
import { PopoverStyles } from '../Popover';
import { ItemRow } from '../Structure';
import useAutoComplete from '../../hooks/useAutoComplete';
import { takeLastSplitFromURL } from '../../utils/url';
import { AutoCompleteLine } from '../AutoComplete';
import HeightAnimatedContainer from '../HeightAnimatedContainer';
import InputWrapper from '../Form/InputWrapper';
import useOnKeyPress from '../../hooks/useOnKeyPress';
//
// Component
//
const Breadcrumb: React.FC = () => {
const location = useLocation();
const { t } = useTranslation();
const history = useHistory();
const routeMatch = getRouteMatch(location.pathname);
const buttonList = findAdditionalButtons(routeMatch, location.search);
const currentBreadcrumbPath = buttonList.map((item) => item.label).join('/');
const [activeAutoCompleteOption, setActiveOption] = useState<string | null>(null);
const [edit, setEdit] = useState(false);
const [str, setStr] = useState(currentBreadcrumbPath.replace(/\s/g, ''));
const [warning, setWarning] = useState('');
const autoCompleteUrl = urlFromString(str);
const { result: autoCompleteResult, reset: resetAutocomplete } = useAutoComplete<string>({
url: autoCompleteUrl.url || '',
params: autoCompleteUrl.params,
enabled: !!autoCompleteUrl.url,
finder: (item, input) => {
const last = takeLastSplitFromURL(item.label);
return !input ? true : last.toLowerCase().includes(input.toLowerCase());
},
input: takeLastSplitFromURL(str),
searchEmpty: str.split('/').length > 1,
});
//
// Handlers
//
//
// Try to move to given url
//
const tryMove = (str: string) => {
const path = pathFromString(str);
if (path) {
localStorage.removeItem('home-params');
history.push(path);
closeUp();
} else {
setWarning(t('breadcrumb.no-match'));
closeUp();
}
};
//
// Handles submitting path on breadcrumb
//
const onKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.charCode === 13) {
if (activeAutoCompleteOption) {
const item = autoCompleteResult.data.find((r) => r.value === activeAutoCompleteOption);
if (item) {
setStr((s) => mergeWithString(s, item.value) + '/');
}
setActiveOption(null);
} // If user presses enter without changing value, lets hide popup
else if (notEmptyAndEqual(e.currentTarget.value, currentBreadcrumbPath)) {
closeUp();
} else {
tryMove(e.currentTarget.value);
}
}
};
//
// Handles movement on suggested routes on autocomplete
//
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault();
if (autoCompleteResult.data.length === 0) {
return;
}
const index = autoCompleteResult.data.findIndex((item) => item.value === activeAutoCompleteOption);
const newIndex = e.key === 'ArrowDown' ? index + 1 : index - 1;
if (newIndex < 0 || newIndex > Math.min(3, autoCompleteResult.data.length)) {
setActiveOption(null);
} else {
setActiveOption(autoCompleteResult.data[newIndex].value);
}
}
};
const closeUp = () => {
setEdit(false);
setWarning('');
};
const openModal = () => {
setEdit(true);
setStr(currentBreadcrumbPath.replace(/\s/g, ''));
};
//
// Esc listeners
//
useOnKeyPress('Escape', () => closeUp());
return (
<StyledBreadcrumb pad="md">
<ButtonLink
to={'/'}
tabIndex={0}
data-testid={'home-button'}
variant="primaryText"
disabled={location.pathname === '/'}
>
{t('home.home')}
</ButtonLink>
{/* On home page, when not editing breadcrumb */}
{buttonList.length === 0 && !edit && (
<BreadcrumbEmptyInput
active={true}
onClick={openModal}
onKeyPress={openModal}
data-testid="breadcrumb-goto-input-inactive"
>
<input placeholder={t('breadcrumb.goto')} />
</BreadcrumbEmptyInput>
)}
{/* Rendering breadcrumb items when not in home and not editing. */}
{!edit && buttonList.length > 0 && (
<>
<BreadcrumbGroup data-testid="breadcrumb-button-container">
{buttonList.map(({ label, path }, index) => {
const isLastItem = index + 1 === buttonList.length;
return (
<CrumbComponent key={index}>
{isLastItem ? (
<ButtonCrumb key={index} textOnly active={isLastItem} title={label} onClick={() => openModal()}>
{label}
</ButtonCrumb>
) : (
<Link to={path}>
<ButtonCrumb key={index} textOnly active={isLastItem} title={label} onClick={() => null}>
{label}
</ButtonCrumb>
</Link>
)}
{!isLastItem && <BreadcrumbDivider />}
</CrumbComponent>
);
})}
<EditButton
onClick={openModal}
onKeyPress={(e) => {
if (e && e.charCode === 13) {
openModal();
}
}}
tabIndex={0}
textOnly
>
<Icon name="pen" size="md" />
</EditButton>
</BreadcrumbGroup>
</>
)}
{/* Rendering edit block when active */}
{edit && (
<>
<GoToHolder data-testid="breadcrumb-goto-container">
<GoToContainer>
<ItemRow>
<BreadcrumbInputWrapper active={edit}>
<input
type="text"
placeholder={t('breadcrumb.goto')}
value={str}
onKeyPress={onKeyPress}
onKeyDown={onKeyDown}
onChange={(e) => {
setStr(e?.target.value?.replace(/\s/g, '') || '');
if (!e?.target.value?.replace(/\s/g, '')) {
resetAutocomplete();
}
}}
onFocus={() => {
resetAutocomplete();
}}
autoFocus={true}
/>
</BreadcrumbInputWrapper>
<GotoClose onClick={() => closeUp()}>
<Icon name="times" size="md" />
</GotoClose>
</ItemRow>
<HeightAnimatedContainer>
{autoCompleteResult.status === 'Ok' && autoCompleteResult.data.length > 0 && str !== '' ? (
<BreadcrumbInfo>
{autoCompleteResult.data.slice(0, 4).map((item) => (
<AutoCompleteLine
active={item.value === activeAutoCompleteOption}
key={item.value}
onClick={() => {
const value = mergeWithString(str, item.value);
setStr(value);
tryMove(value);
closeUp();
}}
>
{takeLastSplitFromURL(item.label)}
</AutoCompleteLine>
))}
</BreadcrumbInfo>
) : (
<BreadcrumbInfo>
{warning && <BreadcrumbWarning>{warning}</BreadcrumbWarning>}
<BreadcrumbKeyValueList
items={[
{ key: t('items.flow'), value: t('breadcrumb.example-flow') },
{ key: t('items.run'), value: t('breadcrumb.example-run') },
{ key: t('items.step'), value: t('breadcrumb.example-step') },
{ key: t('items.task'), value: t('breadcrumb.example-task') },
]}
/>
</BreadcrumbInfo>
)}
</HeightAnimatedContainer>
</GoToContainer>
</GoToHolder>
<ModalOutsideClickDetector onClick={() => closeUp()} />
</>
)}
</StyledBreadcrumb>
);
};
const BreadcrumbKeyValueList: React.FC<{ items: { key: string; value: string }[] }> = ({ items }) => (
<div>
{items.map(({ key, value }) => (
<KeyValueListItem key={key}>
<KeyValueListLabel>{key}</KeyValueListLabel>
<KeyValueListValue>{value}</KeyValueListValue>
</KeyValueListItem>
))}
</div>
);
//
// Utils
//
export function notEmptyAndEqual(value: string, current: string): boolean {
return (value || '').length > 0 && value === current;
}
//
// Take given string and try to parse valid path in our app for it.
//
export function pathFromString(str: string): string | null {
const parts = str.split('/').filter((item) => item);
if (parts.length === 0) {
return getPath.home();
} else if (parts.length === 1) {
return getPath.home() + '?flow_id=' + parts[0];
} else if (parts.length === 2) {
return getPath.timeline(parts[0], parts[1]);
} else if (parts.length === 3) {
return getPath.step(parts[0], parts[1], parts[2]);
} else if (parts.length === 4) {
return getPath.task(parts[0], parts[1], parts[2], parts[3]);
}
return null;
}
//
// Figure out path for auto complete request pased on path.
//
function urlFromString(str: string): { url: string | null; params: Record<string, string> } {
const parts = str.split('/');
const lastSplit = takeLastSplitFromURL(str);
if (parts.length < 2) {
return { url: '/flows/autocomplete', params: { 'flow_id:co': lastSplit } };
} else if (parts.length === 2) {
return { url: `/flows/${parts[0]}/runs/autocomplete`, params: { 'run:co': lastSplit } };
} else if (parts.length === 3) {
return { url: `/flows/${parts[0]}/runs/${parts[1]}/steps/autocomplete`, params: { 'step_name:co': lastSplit } };
}
return { url: null, params: {} };
}
//
// Add one item to path string. So a/b/c d -> a/b/c/d
//
function mergeWithString(str: string, toAdd: string): string {
return str
.split('/')
.slice(0, str.split('/').length - 1)
.concat([toAdd])
.join('/');
}
type BreadcrumbButtons = { label: string; path: string };
/**
* Find need for various buttons in breadcrumb. This is now very attached to fixed urls we have now
* so we might need to make this more generic later.
* @param routeMatch
* @param location
*/
export function findAdditionalButtons(routeMatch: match<KnownURLParams> | null, location: string): BreadcrumbButtons[] {
if (routeMatch === null) return [];
const queryParams = new URLSearchParams(location);
const buttons = [];
const params = routeMatch.params;
const flowValue = queryParams.get('flow_id') || params.flowId;
if (flowValue && flowValue.split(',').length === 1) {
buttons.push({
label: `${flowValue}`,
path: getPath.home() + '?flow_id=' + flowValue,
});
}
if (params.flowId && params.runNumber) {
buttons.push({
label: `${params.runNumber}`,
path: getPath.timeline(params.flowId, params.runNumber),
});
}
// Special case since step name might be found from route params or query params.
const stepValue = queryParams.get('steps') || params.stepName;
if (params.flowId && params.runNumber && stepValue) {
buttons.push({
label: stepValue,
path: getPath.step(params.flowId, params.runNumber, stepValue || 'undefined'),
});
}
if (params.flowId && params.runNumber && params.stepName && params.taskId) {
buttons.push({
label: params.taskId,
path: getPath.task(params.flowId, params.runNumber, params.stepName, params.taskId),
});
}
return buttons;
}
//
// Styles
//
const BreadcrumbGroup = styled.div`
${ButtonCSS}
border-color: ${(p) => p.theme.color.text.blue};
`;
const BreadcrumbEmptyInput = styled(InputWrapper)`
width: 35rem;
border: 1px solid ${(p) => p.theme.color.text.blue};
input {
padding-left: 0;
margin-left: -0.25rem;
&::placeholder {
color: #808080;
}
}
`;
const CrumbComponent = styled.div`
white-space: nowrap;
&:first-child {
padding-left: 0.25rem;
}
`;
const ButtonCrumb = styled(BigButton)`
display: inline-block;
padding-left: ${(p) => p.theme.spacer.sm}rem;
padding-right: ${(p) => p.theme.spacer.sm}rem;
color: ${(p) => p.theme.color.text.dark};
overflow-x: hidden;
max-width: 18.75rem;
text-overflow: ellipsis;
background: transparent;
&.active {
background: transparent;
}
&:hover {
background-color: transparent;
color: ${(p) => p.theme.color.text.dark};
}
`;
const BreadcrumbDivider = styled.div`
display: inline-block;
pointer-events: none;
color: ${(p) => p.theme.color.text.dark};
font-weight: bold;
&:after {
content: '/';
}
z-index: 1;
`;
const EditButton = styled(Button)`
background: transparent;
height: 2.375rem;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
margin-left: 0.25rem;
border-left: ${(p) => p.theme.border.thinPrimary};
&:hover {
border-left: ${(p) => p.theme.border.thinPrimary};
background: transparent;
}
.icon {
height: 1.5rem;
}
`;
const StyledBreadcrumb = styled(ItemRow)`
font-size: 0.875rem;
.button {
font-size: 0.875rem;
}
input[type='text'] {
line-height: 1.875rem;
font-size: 0.875rem;
width: 35rem;
background: #fff;
padding-left: 0;
margin-left: -0.25rem;
}
`;
const BreadcrumbInputWrapper = styled(InputWrapper)`
border: 1px solid ${(p) => p.theme.color.text.blue};
`;
const GoToHolder = styled.div`
position: relative;
font-size: 0.875rem;
height: 2rem;
margin-top: -0.5625rem;
z-index: 2;
`;
const GoToContainer = styled.div`
position: absolute;
top: -${(p) => p.theme.spacer.sm}rem;
left: -${(p) => p.theme.spacer.sm}rem;
${PopoverStyles}
`;
const GotoClose = styled.div`
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
`;
const BreadcrumbInfo = styled.div`
padding: ${(p) => p.theme.spacer.sm}rem;
`;
const BreadcrumbWarning = styled.div`
color: ${(p) => p.theme.notification.danger.text};
`;
const KeyValueListLabel = styled.div`
color: ${(p) => p.theme.color.text.mid};
width: 4.6875rem;
`;
const KeyValueListValue = styled.div`
color: ${(p) => p.theme.color.text.dark};
`;
const KeyValueListItem = styled.div`
display: flex;
padding: 0.3125rem 0;
`;
const ModalOutsideClickDetector = styled.div`
position: fixed;
zindex: 0;
width: 100%;
height: 100%;
top: 0;
left: 0;
`;
export default Breadcrumb; | the_stack |
import * as aqm from '../aqm/aqm';
import * as caesar from '../transformers/caesar';
import * as churn_types from '../churn/churn.types';
import * as decompression from '../transformers/decompressionShaper';
import * as fragmentation from '../transformers/fragmentationShaper';
import * as ipaddr from 'ipaddr.js';
import * as logging from '../logging/logging';
import * as net from '../net/net.types';
import PassThrough from '../transformers/passthrough';
import * as promises from '../promises/promises';
import * as protean from '../transformers/protean';
import * as rc4 from '../transformers/rc4';
import * as sequence from '../transformers/byteSequenceShaper';
import * as transformer from '../transformers/transformer';
import Socket = freedom.UdpSocket.Socket;
declare const freedom: freedom.FreedomInModuleEnv;
var log :logging.Log = new logging.Log('churn-pipe');
// Maps transformer names to class constructors.
var transformers :{[name:string] : new() => transformer.Transformer} = {
'caesar': caesar.CaesarCipher,
'decompressionShaper': decompression.DecompressionShaper,
'fragmentationShaper': fragmentation.FragmentationShaper,
'none': PassThrough,
'protean': protean.Protean,
'rc4': rc4.Rc4Transformer,
'sequenceShaper': sequence.ByteSequenceShaper
};
// Local socket rebinding retry timing (see bindLocal)
const INITIAL_REBIND_INTERVAL_MS = 10;
const MAX_REBIND_INTERVAL_MS = 2000;
interface MirrorSet {
// If true, these mirrors represent a remote endpoint that has been
// explicitly signaled to us.
signaled:boolean;
// This array may be transiently sparse for signaled mirrors, and
// persistently sparse for non-signaled mirrors (i.e. peer-reflexive).
// Taking its length is therefore likely to be unhelpful.
sockets:Promise<Socket>[];
}
/**
* A Churn Pipe is a transparent obfuscator/deobfuscator for transforming the
* apparent type of browser-generated UDP datagrams.
*
* This implementation makes the simplifying assumption that the browser only
* allocates one endpoint per interface. Relaxing this assumption would allow
* us to achieve the same performance while allocating fewer ports, at the cost
* of slightly more complex logic.
*/
export default class Pipe {
// Number of instances created, for logging purposes.
private static id_ = 0;
// For each physical network interface, this provides a list of the open
// public sockets on that interface. Each socket corresponds to a port that
// is intended to be publicly routable (possibly thanks to NAT), and is
// used only for sending and receiving obfuscated traffic with the remote
// endpoints.
private publicSockets_ :{ [address:string]:Socket[] } = {};
// Promises to track the progress of binding any public port. This is used
// to return the appropriate Promise when there is a redundant call to
// |bindLocal|.
private publicPorts_ :{ [address:string]:{ [port:number]:Promise<void> } } =
{};
// The maximum number of bound remote ports on any single interface. This is
// also the number of mirror sockets that are needed for each signaled remote
// port.
private maxSocketsPerInterface_ :number = 0;
// Each mirror socket is bound to a port on localhost, and corresponds to a
// specific remote endpoint. When the public socket receives an obfuscated
// packet from that remote endpoint, the mirror socket sends the
// corresponding deobfuscated message to the browser endpoint. Similarly,
// when a mirror socket receives a (unobfuscated) message from the browser
// endpoint, the public socket sends the corresponding obfuscated packet to
// that mirror socket's remote endpoint.
private mirrorSockets_ :{ [address:string]:{ [port:number]:MirrorSet } } =
{};
// Obfuscates and deobfuscates messages.
private transformer_ :transformer.Transformer;
// Endpoint to which incoming obfuscated messages are forwarded on each
// interface. The key is the interface, and the value is the port.
// This requires the simplifying assumption that the browser allocates at
// most one port on each interface.
private browserEndpoints_ :{ [address:string]:number } = {};
// The set of ports used by the browser. All values are true.
// This is only needed because Pipe's mirror sockets are bound to the ANY
// interface (0.0.0.0). If the browser also binds to ANY, packets between
// these interfaces may appear to originate from any local interface, so we
// can't require that source addresses and ports match.
// This object allows O(1) lookup of whether ports are available.
private browserPorts_: {[port:number]:boolean } = {};
// The most recently set public interface for IPv6 and IPv4. Used to
// report mirror endpoints.
private lastInterface_ : {v6?:string; v4?:string;} = {};
// There is an implicit queue between this class, running in a module, and
// the actual send call, which runs in the core environment. Under high
// CPU load, that IPC queue can grow very large. This Active Queue Manager
// drops packets when the queue gets too large, so that the browser slows
// down its sending, which reduces CPU load.
private queueManager_ :aqm.AQM<[Socket, ArrayBuffer, net.Endpoint]>;
// TODO: define a type for event dispatcher in freedom-typescript-api
constructor(
private dispatchEvent_:(name:string, args:Object) => void,
private name_:string = 'unnamed-pipe-' + Pipe.id_) {
Pipe.id_++;
// The delay target is 10 milliseconds maximum roundtrip delay to the core.
// This is twice 5 milliseconds, which is CoDel's recommended
// one-way delay.
// TODO: Tune the tracing fraction (1 / 5). Higher should be more stable,
// but lower should be more efficient.
this.queueManager_ = new aqm.CoDelIsh<[Socket, ArrayBuffer, net.Endpoint]>(
this.tracedSend_,
this.fastSend_,
1 / 5,
10);
}
// Set transformer parameters.
public setTransformer = (
transformerConfig:churn_types.TransformerConfig) : Promise<void> => {
try {
if (!(transformerConfig.name in transformers)) {
throw new Error('unknown transformer: ' + transformerConfig.name);
}
log.info('%1: using %2 obfuscator', this.name_, transformerConfig.name);
this.transformer_ = new transformers[transformerConfig.name]();
if (transformerConfig.config !== undefined) {
this.transformer_.configure(transformerConfig.config);
} else {
log.warn('%1: no transformer config specified', this.name_);
}
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
}
/**
* Returns a promise to create a socket, bind to the specified address, and
* start listening for datagrams, which will be deobfuscated and forwarded to the
* browser endpoint.
*/
// TODO: Clarify naming between bindLocal (binds local public obfuscated
// candidate) and bindRemote (set up private local bindings to allow
// sending to that remote candidate).
public bindLocal = (publicEndpoint:net.Endpoint) :Promise<void> => {
if (ipaddr.IPv6.isValid(publicEndpoint.address)) {
this.lastInterface_.v6 = publicEndpoint.address;
} else if (ipaddr.IPv4.isValid(publicEndpoint.address)) {
this.lastInterface_.v4 = publicEndpoint.address;
} else {
return Promise.reject(
new Error('Invalid address: ' + publicEndpoint.address));
}
if (!this.publicPorts_[publicEndpoint.address]) {
this.publicPorts_[publicEndpoint.address] = {};
}
var portPromise =
this.publicPorts_[publicEndpoint.address][publicEndpoint.port];
if (portPromise) {
log.debug('%1: redundant public endpoint: %2', this.name_, publicEndpoint);
return portPromise;
}
var socket :freedom.UdpSocket.Socket = freedom['core.udpsocket']();
var index = this.addPublicSocket_(socket, publicEndpoint);
// Firefox only supports binding to ANY and localhost, so bind to ANY.
// TODO: Figure out how to behave correctly when we are instructed
// to bind the same port on two different interfaces. Currently, this
// code will bind the port twice, probably duplicating all incoming
// packets (but this is not verified).
var anyInterface = Pipe.anyInterface_(publicEndpoint.address);
// This retry is needed because the browser releases the UDP port
// asynchronously after we call close() on the RTCPeerConnection, so
// this call to bind() may initially fail, until the port is released.
portPromise = promises.retryWithExponentialBackoff(() => {
log.debug('%1: trying to bind public endpoint: %2',
this.name_, publicEndpoint);
// TODO: Once https://github.com/freedomjs/freedom/issues/283 is
// fixed, catch here, and only retry on an ALREADY_BOUND error.
return socket.bind(anyInterface, publicEndpoint.port);
}, MAX_REBIND_INTERVAL_MS, INITIAL_REBIND_INTERVAL_MS).then(() => {
log.debug('%1: successfully bound public endpoint: %2',
this.name_, publicEndpoint);
socket.on('onData', (recvFromInfo:freedom.UdpSocket.RecvFromInfo) => {
this.onIncomingData_(recvFromInfo, publicEndpoint.address, index);
});
});
this.publicPorts_[publicEndpoint.address][publicEndpoint.port] = portPromise;
return portPromise;
}
// Given a socket, and the endpoint to which it is bound, this function adds
// the endpoint to the set of sockets for that interface, performs any
// updates necessary to make the new socket functional, and returns an index
// that identifies the socket within its interface.
private addPublicSocket_ = (socket:Socket, endpoint:net.Endpoint)
:number => {
if (!(endpoint.address in this.publicSockets_)) {
this.publicSockets_[endpoint.address] = [];
}
this.publicSockets_[endpoint.address].push(socket);
if (this.publicSockets_[endpoint.address].length >
this.maxSocketsPerInterface_) {
this.increaseReplication_();
}
return this.publicSockets_[endpoint.address].length - 1;
}
// Some interface has broken the record for the number of bound local sockets.
// Add another mirror socket for every signaled remote candidate, to represent
// the routes through this newly bound local socket.
private increaseReplication_ = () => {
log.debug('%1: increasing replication (currently %2)',
this.name_, this.maxSocketsPerInterface_);
for (var remoteAddress in this.mirrorSockets_) {
for (var port in this.mirrorSockets_[remoteAddress]) {
var mirrorSet = this.mirrorSockets_[remoteAddress][port];
if (mirrorSet.signaled) {
var endpoint :net.Endpoint = {
address: remoteAddress,
port: parseInt(port, 10)
};
this.getMirrorSocketAndEmit_(endpoint, this.maxSocketsPerInterface_);
}
}
}
++this.maxSocketsPerInterface_;
}
// A new mirror port has been allocated for a signaled remote endpoint. Report
// it to the client.
private emitMirror_ = (remoteEndpoint:net.Endpoint, socket:Socket) => {
socket.getInfo().then(this.endpointFromInfo_).then((localEndpoint) => {
log.debug('%1: emitting mirror for %2: %3', this.name_, remoteEndpoint, localEndpoint);
this.dispatchEvent_('mappingAdded', {
local: localEndpoint,
remote: remoteEndpoint
});
});
}
// Informs this module about the existence of a browser endpoint.
public addBrowserEndpoint = (browserEndpoint:net.Endpoint) :Promise<void> => {
log.debug('%1: adding browser endpoint: %2', this.name_, browserEndpoint);
if (this.browserEndpoints_[browserEndpoint.address]) {
log.warn('%1: port %2 is already open on this interface',
this.name_, this.browserEndpoints_[browserEndpoint.address])
}
this.browserEndpoints_[browserEndpoint.address] = browserEndpoint.port;
this.browserPorts_[browserEndpoint.port] = true;
return Promise.resolve();
}
// Establishes an empty data structure to hold mirror sockets for this remote
// endpoint, if necessary. If |signaled| is true, the structure will be
// marked as signaled, whether or not it already existed.
private ensureRemoteEndpoint_ = (endpoint:net.Endpoint, signaled:boolean)
:MirrorSet => {
if (!(endpoint.address in this.mirrorSockets_)) {
this.mirrorSockets_[endpoint.address] = {};
}
if (!(endpoint.port in this.mirrorSockets_[endpoint.address])) {
this.mirrorSockets_[endpoint.address][endpoint.port] = {
signaled: false,
sockets: []
};
}
if (signaled) {
this.mirrorSockets_[endpoint.address][endpoint.port].signaled = true;
}
return this.mirrorSockets_[endpoint.address][endpoint.port];
}
/**
* Given an endpoint from which obfuscated datagrams may arrive, this method
* constructs a corresponding mirror socket, and returns its endpoint.
*/
public bindRemote = (remoteEndpoint:net.Endpoint) :Promise<void> => {
try {
var dummyAddress = this.getLocalInterface_(remoteEndpoint.address);
} catch (e) {
return Promise.reject('You must call bindLocal before bindRemote');
}
log.debug('%1: binding %2 mirror(s) for remote endpoint: %3',
this.name_, this.maxSocketsPerInterface_, remoteEndpoint);
this.ensureRemoteEndpoint_(remoteEndpoint, true);
var promises :Promise<void>[] = [];
for (var i = 0; i < this.maxSocketsPerInterface_; ++i) {
promises.push(this.getMirrorSocketAndEmit_(remoteEndpoint, i));
}
return Promise.all(promises).then((fulfills:void[]) :void => {});
}
// Returns the "any" interface with the same address family (IPv4 or IPv6) as
// |address|.
private static anyInterface_ = (address:string) => {
return ipaddr.IPv6.isValid(address) ? '::' : '0.0.0.0';
}
private getMirrorSocket_ = (remoteEndpoint:net.Endpoint, index:number)
:Promise<Socket> => {
var mirrorSet = this.ensureRemoteEndpoint_(remoteEndpoint, false);
var socketPromise :Promise<Socket> = mirrorSet.sockets[index];
if (socketPromise) {
return socketPromise;
}
var mirrorSocket :freedom.UdpSocket.Socket = freedom['core.udpsocket']();
mirrorSocket;
// Bind to INADDR_ANY owing to restrictions on localhost candidates
// in Firefox:
// https://github.com/uProxy/uproxy/issues/1597
// TODO: bind to an actual, non-localhost address (see the issue)
var anyInterface = Pipe.anyInterface_(remoteEndpoint.address);
socketPromise = mirrorSocket.bind(anyInterface, 0).then(() :Socket => {
mirrorSocket.on('onData', (recvFromInfo:freedom.UdpSocket.RecvFromInfo) => {
// Ignore packets that do not originate from the browser, for a
// theoretical security benefit.
if (!(recvFromInfo.address in this.browserEndpoints_)) {
log.warn('%1: mirror socket for %2 ignoring incoming packet from %3: ' +
'unknown source address',
this.name_,
remoteEndpoint, {
address: recvFromInfo.address,
port: recvFromInfo.port
});
} else if (!(recvFromInfo.port in this.browserPorts_)) {
log.warn('%1: mirror socket for %2 ignoring incoming packet from %3: ' +
'unknown source port',
this.name_,
remoteEndpoint, {
address: recvFromInfo.address,
port: recvFromInfo.port
});
} else {
var publicSocket = this.publicSockets_[recvFromInfo.address] &&
this.publicSockets_[recvFromInfo.address][index];
// Public socket may be null, especially if the index is too great.
// Drop the packet in that case.
if (publicSocket) {
this.sendTo_(publicSocket, recvFromInfo.data, remoteEndpoint);
} else {
log.warn('%1: Dropping packet due to null public socket', this.name_);
}
}
});
return mirrorSocket;
});
mirrorSet.sockets[index] = socketPromise;
return socketPromise;
}
private getMirrorSocketAndEmit_ = (remoteEndpoint:net.Endpoint, index:number)
:Promise<void> => {
return this.getMirrorSocket_(remoteEndpoint, index).then((socket) => {
this.emitMirror_(remoteEndpoint, socket)
}, (e) => {
log.error('%1: error while getting mirror socket: %2', this.name_, e);
});
}
private getLocalInterface_ = (anyAddress:string) : string => {
// This method will not work until bindLocal populates |lastInterface_|.
var isIPv6 = ipaddr.IPv6.isValid(anyAddress);
var address = isIPv6 ? this.lastInterface_.v6 : this.lastInterface_.v4;
if (!address) {
// This error would only occur if this method were called (from
// bindRemote) before bindLocal was called.
throw new Error('No known interface to match ' + anyAddress);
}
return address;
}
private endpointFromInfo_ = (socketInfo:freedom.UdpSocket.SocketInfo) => {
if (!socketInfo.localAddress) {
throw new Error('Cannot process incomplete info: ' +
JSON.stringify(socketInfo));
}
// freedom-for-firefox currently reports the bound address as 'localhost',
// which is unsupported in candidate lines by Firefox:
// https://github.com/freedomjs/freedom-for-firefox/issues/62
// This will result in |localAddress| being IPv4, so this
// issue is blocking IPv6 Churn support on Firefox.
var localAddress = this.getLocalInterface_(socketInfo.localAddress);
return {
address: localAddress,
port: socketInfo.localPort
};
}
/**
* Sends a message over the network to the specified destination.
* The message is obfuscated before it hits the wire.
*/
private sendTo_ = (publicSocket:Socket, buffer:ArrayBuffer, to:net.Endpoint)
:void => {
try {
let transformedBuffers = this.transformer_.transform(buffer);
for (var i = 0; i < transformedBuffers.length; i++) {
// 0 is the identifier for the outbound flow
this.queueManager_.send(0, [publicSocket, transformedBuffers[i], to]);
}
} catch (e) {
log.warn('%1: transform error: %2', this.name_, e.message);
}
}
/**
* Sends a message to the specified destination.
*/
private fastSend_ = (args:[Socket, ArrayBuffer, net.Endpoint]) : void => {
var [socket, buffer, to] = args;
socket.sendTo.reckless(
buffer,
to.address,
to.port);
}
/**
* Sends a message to the specified destination.
* This version also requests an Ack from the core, and returns a Promise
* that resolves when the core has sent the message.
*/
private tracedSend_ = (args:[Socket, ArrayBuffer, net.Endpoint])
: Promise<void> => {
var [socket, buffer, to] = args;
return socket.sendTo(
buffer,
to.address,
to.port).then((bytesWritten:number) => {
if (bytesWritten !== buffer.byteLength) {
throw new Error('Incomplete UDP send should be impossible');
}
});
}
/**
* Called when a message is received over the network from the remote side.
* The message is de-obfuscated before being passed to the browser endpoint
* via a corresponding mirror socket.
*/
private onIncomingData_ = (recvFromInfo:freedom.UdpSocket.RecvFromInfo,
iface:string, index:number) => {
var browserPort = this.browserEndpoints_[iface];
if (!browserPort) {
// There's no browser port for this interface, so drop the packet.
return;
}
var transformedBuffer = recvFromInfo.data;
try {
let buffers = this.transformer_.restore(transformedBuffer);
this.getMirrorSocket_(recvFromInfo, index).then((mirrorSocket:Socket) => {
var browserEndpoint:net.Endpoint = {
address: iface,
port: browserPort
};
for (var i = 0; i < buffers.length; i++) {
// 1 is the identifier for the inbound flow
this.queueManager_.send(1, [mirrorSocket, buffers[i], browserEndpoint]);
}
});
} catch (e) {
log.warn('%1: restore error: %2', this.name_, e.message);
}
}
public on = (name:string, listener:(event:any) => void) :void => {
throw new Error('Placeholder function to keep Typescript happy');
}
private static closeSocket_(socket:Socket) : Promise<void> {
return socket.destroy().catch((e) => {
log.warn('Error while closing socket: %1', e);
}).then(() => {
freedom['core.udpsocket'].close(socket);
});
}
public shutdown = () : Promise<void> => {
var shutdownPromises : Promise<void>[] = [];
var address:string;
var port:any; // Typescript doesn't allow number in for...in loops.
for (address in this.publicSockets_) {
this.publicSockets_[address].forEach((publicSocket) => {
shutdownPromises.push(Pipe.closeSocket_(publicSocket));
});
}
for (address in this.mirrorSockets_) {
for (port in this.mirrorSockets_[address]) {
var mirrorPromises = this.mirrorSockets_[address][port].sockets;
mirrorPromises.forEach((mirrorPromise) => {
shutdownPromises.push(mirrorPromise.then(Pipe.closeSocket_));
});
}
}
return Promise.all(shutdownPromises).then((voids:void[]) => {});
}
} | the_stack |
import {
compileTrio,
PenroseError,
PenroseState,
prepareState,
RenderInteractive,
RenderStatic,
resample,
stateConverged,
stateInitial,
stepState,
stepUntilConvergence
} from "@penrose/core";
import Inspector from "inspector/Inspector";
import { isEqual } from "lodash";
import * as React from "react";
import SplitPane from "react-split-pane";
import ButtonBar from "ui/ButtonBar";
import { FileSocket, FileSocketResult } from "ui/FileSocket";
/**
* (browser-only) Downloads any given exported SVG to the user's computer
* @param svg
* @param title the filename
*/
export const DownloadSVG = (
svg: SVGSVGElement,
title = "illustration"
): void => {
const blob = new Blob([svg.outerHTML], {
type: "image/svg+xml;charset=utf-8"
});
const url = URL.createObjectURL(blob);
const downloadLink = document.createElement("a");
downloadLink.href = url;
downloadLink.download = `${title}.svg`;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
};
const LOCALSTORAGE_SETTINGS = "browser-ui-settings-penrose";
export interface ISettings {
showInspector: boolean;
autostep: boolean;
autoStepSize: number;
}
interface ICanvasState {
data: PenroseState | undefined; // NOTE: if the backend is not connected, data will be undefined, TODO: rename this field
error: PenroseError | null;
processedInitial: boolean;
penroseVersion: string;
history: PenroseState[];
files: FileSocketResult | null;
connected: boolean;
settings: ISettings;
}
const socketAddress = "ws://localhost:9160";
class App extends React.Component<any, ICanvasState> {
public readonly state: ICanvasState = {
data: undefined,
error: null,
history: [],
processedInitial: false, // TODO: clarify the semantics of this flag
penroseVersion: "",
files: null,
connected: false,
settings: {
autostep: false,
showInspector: true,
autoStepSize: 10000
}
};
public readonly buttons = React.createRef<ButtonBar>();
public readonly canvasRef = React.createRef<HTMLDivElement>();
// same as onCanvasState but doesn't alter timeline or involve optimization
public modCanvas = async (canvasState: PenroseState) => {
await new Promise(r => setTimeout(r, 1));
this.setState({
data: canvasState,
processedInitial: true
});
this.renderCanvas(canvasState);
};
// TODO: reset history on resample/got stuff
public onCanvasState = async (canvasState: PenroseState) => {
// HACK: this will enable the "animation" that we normally expect
await new Promise(r => setTimeout(r, 1));
this.setState({
data: canvasState,
history: [...this.state.history, canvasState],
processedInitial: true,
error: null
});
this.renderCanvas(canvasState);
const { settings } = this.state;
if (settings.autostep && !stateConverged(canvasState)) {
await this.stepUntilConvergence();
}
};
public downloadSVG = (): void => {
DownloadSVG(RenderStatic(this.state.data));
};
public downloadPDF = (): void => {
console.error("PDF download not implemented");
};
public downloadState = (): void => {
const state = this.state.data;
if (state) {
const params = {
...state.params,
energyGraph: {},
xsVars: [],
constrWeightNode: undefined,
epWeightNode: undefined,
graphs: undefined
};
const content = JSON.stringify({ ...state, params });
const blob = new Blob([content], {
type: "text/json"
});
const url = URL.createObjectURL(blob);
const downloadLink = document.createElement("a");
downloadLink.href = url;
downloadLink.download = `state.json`;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
} else {
console.warn(
"Warning: cannot download the state because state is currently empty."
);
}
};
public setSettings = (settings: ISettings) => {
this.setState({ settings });
localStorage.setItem(LOCALSTORAGE_SETTINGS, JSON.stringify(settings));
};
public autoStepToggle = async () => {
const newSettings = {
...this.state.settings,
autostep: !this.state.settings.autostep
};
this.setState({
settings: newSettings
});
localStorage.setItem(LOCALSTORAGE_SETTINGS, JSON.stringify(newSettings));
if (newSettings.autostep) {
await this.stepUntilConvergence();
}
};
public step = (): void => {
if (this.state.data) {
try {
const stepped = stepState(this.state.data, 1);
void this.onCanvasState(stepped);
} catch (e) {
const error: PenroseError = {
errorType: "RuntimeError",
tag: "RuntimeError",
message: `Runtime error encountered: '${e}' Check console for more information.`
};
const errorWrapper = { error, data: undefined };
this.setState(errorWrapper);
throw e;
}
} else {
console.warn("No state loaded in the frontend.");
}
};
public stepUntilConvergence = (): void => {
if (this.state.data) {
const stepped = stepUntilConvergence(
this.state.data,
this.state.settings.autoStepSize
);
if (stepped.isErr()) {
this.setState({ error: stepped.error, data: undefined });
} else {
void this.onCanvasState(stepped.value);
}
} else {
console.warn("No state loaded in the frontend.");
}
};
public resample = async () => {
const NUM_SAMPLES = 1;
const oldState = this.state.data;
if (oldState) {
this.setState({ processedInitial: false });
const resampled = resample(oldState, NUM_SAMPLES);
void this.onCanvasState(resampled);
}
};
connectToSocket = () => {
FileSocket(
socketAddress,
async files => {
const { domain, substance, style } = files;
this.setState({ files, connected: true });
// TODO: does `processedInitial` need to be set?
this.setState({ processedInitial: false });
const compileRes = compileTrio(
domain.contents,
substance.contents,
style.contents
);
if (compileRes.isOk()) {
try {
const initState: PenroseState = await prepareState(
compileRes.value
);
void this.onCanvasState(initState);
} catch (e) {
const error: PenroseError = {
errorType: "RuntimeError",
tag: "RuntimeError",
message: `Runtime error encountered: '${e}' Check console for more information.`
};
const errorWrapper = { error, data: undefined };
this.setState(errorWrapper);
throw e;
}
} else {
this.setState({ error: compileRes.error, data: undefined });
}
},
() => {
this.setState({ connected: false });
}
);
};
public componentDidMount(): void {
const settings = localStorage.getItem(LOCALSTORAGE_SETTINGS);
// Overwrites if schema in-memory has different properties than in-storage
if (
!settings ||
!isEqual(
Object.keys(JSON.parse(settings)),
Object.keys(this.state.settings)
)
) {
localStorage.setItem(
LOCALSTORAGE_SETTINGS,
JSON.stringify(this.state.settings)
);
} else {
const parsed = JSON.parse(settings);
this.setState({ settings: parsed });
}
this.connectToSocket();
}
public updateData = async (data: PenroseState) => {
this.setState({ data: { ...data } });
if (this.state.settings.autostep) {
const stepped = stepState(data);
this.onCanvasState(stepped);
} else {
this.renderCanvas(data);
}
};
public setInspector = async (showInspector: boolean) => {
const newSettings = { ...this.state.settings, showInspector };
this.setSettings(newSettings);
};
public toggleInspector = async () => {
await this.setInspector(!this.state.settings.showInspector);
};
public hideInspector = async () => {
await this.setInspector(false);
};
public renderCanvas = (state: PenroseState) => {
if (this.canvasRef.current !== null) {
const current = this.canvasRef.current;
const rendered =
stateConverged(state) || stateInitial(state)
? RenderInteractive(state, this.updateData)
: RenderStatic(state);
if (current.firstChild !== null) {
current.replaceChild(rendered, current.firstChild);
} else {
current.appendChild(rendered);
}
}
};
private renderApp() {
const {
data,
settings,
penroseVersion,
history,
files,
error,
connected
} = this.state;
return (
<div
className="App"
style={{
height: "100%",
display: "flex",
flexFlow: "column",
overflow: "hidden"
}}
>
<div style={{ flexShrink: 0 }}>
<ButtonBar
downloadPDF={this.downloadPDF}
downloadSVG={this.downloadSVG}
downloadState={this.downloadState}
stepUntilConvergence={this.stepUntilConvergence}
autostep={settings.autostep}
step={this.step}
autoStepToggle={this.autoStepToggle}
resample={this.resample}
converged={data ? stateConverged(data) : false}
initial={data ? stateInitial(data) : false}
toggleInspector={this.toggleInspector}
showInspector={settings.showInspector}
files={files}
ref={this.buttons}
connected={connected}
reconnect={this.connectToSocket}
/>
</div>
<div style={{ flexGrow: 1, position: "relative", overflow: "hidden" }}>
<SplitPane
split="horizontal"
defaultSize={400}
style={{ position: "inherit" }}
className={this.state.settings.showInspector ? "" : "soloPane1"}
pane2Style={{ overflow: "hidden" }}
>
<div style={{ width: "100%", height: "100%" }}>
{data && (
<div
style={{ width: "100%", height: "100%" }}
ref={this.canvasRef}
/>
)}
{error && <pre>errors encountered, check inspector</pre>}
</div>
{settings.showInspector ? (
<Inspector
history={history}
error={error}
onClose={this.toggleInspector}
modCanvas={this.modCanvas}
settings={settings}
setSettings={this.setSettings}
/>
) : (
<div />
)}
</SplitPane>
</div>
</div>
);
}
public render() {
return this.renderApp();
}
}
export default App; | the_stack |
import * as React from 'react';
import styles from './SiteDesigns.module.scss';
import { ISiteDesignsProps } from './ISiteDesignsProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { ListView, IViewField, SelectionMode, GroupOrder, IGrouping } from "@pnp/spfx-controls-react/lib/ListView";
import { IListViewItems } from '../components/IListViewItems';
import spservice from '../../../services/spservices';
import { Icon, IconType } from 'office-ui-fabric-react/lib/Icon';
import { CommandBar } from 'office-ui-fabric-react/lib/CommandBar';
import { panelMode } from './IEnumPanel';
import {
MessageBar,
MessageBarType,
Spinner,
SpinnerSize,
Dialog,
DialogType,
DialogFooter,
ImageFit,
PrimaryButton,
Link
} from 'office-ui-fabric-react';
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import * as strings from 'SiteDesignsWebPartStrings';
import { ISiteDesignState } from './ISiteDesignState';
import { SiteDesignInfo, Item } from '@pnp/sp';
import { IAddSiteDesignTaskToCurrentWebResult } from '../../../services/IAddSiteDesignTaskToCurrentWebResult';
//import { SiteScripts } from './../../../controls/sitescripts/SiteScripts';
// ListView Columns
const viewFields: IViewField[] = [
{
name: 'Image',
render: ((item: IListViewItems) => {
let image;
item.PreviewImageUrl ?
image = <Icon iconType={IconType.image} imageProps={{ src: item.PreviewImageUrl, imageFit: ImageFit.cover }} /> :
image = <Icon iconName="FileImage" />;
return image;
}),
maxWidth: 70,
},
{
name: 'Id',
displayName: strings.ListViewColumnIdLabel,
sorting: true,
isResizable: true,
maxWidth: 200
},
{
name: 'Title',
displayName: strings.TitleFieldLabel,
sorting: true,
isResizable: true,
maxWidth: 250
},
{
name: 'Description',
displayName: strings.ListViewColumnDescriptionLabel,
sorting: true,
isResizable: true,
maxWidth: 250
},
{
name: 'WebTemplate',
displayName: strings.ListViewColumnWebTemplateLabel,
sorting: true,
isResizable: true,
maxWidth: 65
},
{
name: 'numberSiteScripts',
displayName: strings.ListViewColumnNumberSiteScriptsLabel,
sorting: true,
isResizable: true,
maxWidth: 60
}
];
export default class SiteDesigns extends React.Component<ISiteDesignsProps, ISiteDesignState> {
private spService: spservice;
private items: IListViewItems[];
private siteDesignsRunStatus: { addSiteDesignTaskResult: IAddSiteDesignTaskToCurrentWebResult, siteUrl: string }[] = [];
private SiteScriptsList = React.lazy(() => import('../../../controls/siteScripts/SiteScripts' /* webpackChunkName: "sitescriptslist" */));
private AddSiteDesign = React.lazy(() => import('./../../../controls/AddSiteDesign/AddSiteDesign' /* webpackChunkName: "addsitedesign" */));
private EditSiteDesign = React.lazy(() => import('./../../../controls/EditSiteDesign/EditSiteDesign' /* webpackChunkName: "editsitedesign" */));
private DeleteSiteDesign = React.lazy(() => import('./../../../controls/DeleteSiteDesign/DeleteSiteDesign' /* webpackChunkName: "deletesitedesign" */));
private SiteDesignRights = React.lazy(() => import('./../../../controls/SiteDesignRights/SiteDesignRights' /* webpackChunkName: "sitedesignrights" */));
private ApplySiteDesign = React.lazy(() => import('./../../../controls/ApplySiteDesign/ApplySiteDesign' /* webpackChunkName: "applysitedesign" */));
public constructor(props) {
super(props);
// Initialize state
this.state = ({
items: [],
isLoading: false,
disableCommandOption: true,
showPanel: false,
selectItem: null,
panelMode: panelMode.New,
hasError: false,
errorMessage: '',
siteDesignRunning: false,
siteDesignRunningMessage: []
});
// Init class services
this.spService = new spservice(this.props.context);
// Register event handlers
this._getSelection = this._getSelection.bind(this);
this.onNewItem = this.onNewItem.bind(this);
this.onEditItem = this.onEditItem.bind(this);
this.onDeleteItem = this.onDeleteItem.bind(this);
this.onApplyItem = this.onApplyItem.bind(this);
this.onRights = this.onRights.bind(this);
this.onSiteScripts = this.onSiteScripts.bind(this);
this.onDismissPanel = this.onDismissPanel.bind(this);
this.onRefresh = this.onRefresh.bind(this);
this.onDismissApplyPanel = this.onDismissApplyPanel.bind(this);
}
// Get Selection Item from List
private _getSelection(items: IListViewItems[]) {
if (items.length > 0) {
this.setState({
disableCommandOption: false,
selectItem: items[0]
});
} else {
this.setState({
disableCommandOption: true,
selectItem: null,
showPanel: false,
});
}
}
/**
*
*
* @param {IAddSiteDesignTaskToCurrentWebResult[]} siteDesignsRunning
* @param {boolean} [refresh]
* @returns
* @memberof SiteDesigns
*/
public async onDismissApplyPanel(siteDesignsRunning: { addSiteDesignTaskResult: IAddSiteDesignTaskToCurrentWebResult, siteUrl: string }[], refresh?: boolean) {
let isRunning: boolean = false;
let totalRunningSiteDesigns: number = 0;
let siteDesignRunningMessage: string[] = [`The Site Design ${siteDesignsRunning[0].addSiteDesignTaskResult.SiteDesignID} is beeing applyed ...`];
if (siteDesignsRunning && siteDesignsRunning.length > 0) {
totalRunningSiteDesigns = siteDesignsRunning.length;
this.siteDesignsRunStatus = siteDesignsRunning;
this.setState({
siteDesignRunning: true,
siteDesignRunningMessage: siteDesignRunningMessage
});
const runTimer = setInterval(async () => {
siteDesignRunningMessage = [];
siteDesignRunningMessage = [`The Site Design :${siteDesignsRunning[0].addSiteDesignTaskResult.SiteDesignID} was applyed.`];
for (const siteDesignApplyed of siteDesignsRunning) {
isRunning = true;
const result = await this.spService.getSiteDesignTask(siteDesignApplyed.siteUrl, siteDesignApplyed.addSiteDesignTaskResult.ID);
isRunning = !result['@odata.null'] ? true : false;
if (!isRunning) {
totalRunningSiteDesigns = totalRunningSiteDesigns - 1;
siteDesignRunningMessage.push(` site: ${siteDesignApplyed.siteUrl} : Applyed`);
} else {
siteDesignRunningMessage.push(`site: ${siteDesignApplyed.siteUrl} : Applying...`);
}
}
//
if (totalRunningSiteDesigns <= 0) {
clearInterval(runTimer);
this.setState({
siteDesignRunning: true,
siteDesignRunningMessage: siteDesignRunningMessage
});
}
}
, 5000);
}
this.setState({
showPanel: false
});
if (refresh) {
await this.loadSiteDesignsProperties();
}
return;
}
// Panel Dismiss CallBack
// @param refresh refresh list?
public async onDismissPanel(refresh?: boolean) {
this.setState({
showPanel: false
});
if (refresh) {
await this.loadSiteDesignsProperties();
}
return;
}
// On New Item
private onNewItem(e: React.MouseEvent<HTMLElement>) {
e.preventDefault();
this.setState({
panelMode: panelMode.New,
showPanel: true,
});
}
// On Delete
private onDeleteItem(e: React.MouseEvent<HTMLElement>) {
e.preventDefault();
this.setState({
panelMode: panelMode.Delete,
showPanel: true,
});
}
// On Edit item
private onEditItem(e: React.MouseEvent<HTMLElement>) {
e.preventDefault();
this.setState({
panelMode: panelMode.edit,
showPanel: true
});
}
/**
* On Appply item
* @private
* @param {React.MouseEvent<HTMLElement>} e
* @memberof SiteDesigns
*/
private onApplyItem(e: React.MouseEvent<HTMLElement>) {
e.preventDefault();
this.setState({
panelMode: panelMode.Apply,
showPanel: true
});
}
/**
* On Rights Event
*
* @private
* @param {React.MouseEvent<HTMLElement>} e
* @memberof SiteDesigns
*/
private onRights(e: React.MouseEvent<HTMLElement>) {
e.preventDefault();
this.setState({
panelMode: panelMode.Rights,
showPanel: true
});
}
/**
* On SiteScripts
*
* @private
* @param {React.MouseEvent<HTMLElement>} e
* @memberof SiteDesigns
*/
private onSiteScripts(e: React.MouseEvent<HTMLElement>) {
e.preventDefault();
this.setState({
panelMode: panelMode.SiteScripts,
showPanel: true
});
}
private checkSiteDesignRunTask(siteDesignApplyedInfo: IAddSiteDesignTaskToCurrentWebResult) {
try {
} catch (error) {
}
}
//
/**
*
*
* @private
* @memberof SiteDesigns
*/
private async loadSiteDesignsProperties() {
this.items = [];
this.setState({ isLoading: true });
try {
// check if user is Teanant Global Admin
const isGlobalAdmin = await this.spService.checkUserIsGlobalAdmin();
if (isGlobalAdmin) {
// Get Tenant Properties
const siteDesigns: SiteDesignInfo[] = await this.spService.getSiteDesigns();
for (const siteDesign of siteDesigns) {
this.items.push(
{
key: siteDesign.Id,
Description: siteDesign.Description,
Id: siteDesign.Id,
Title: siteDesign.Title,
WebTemplate: siteDesign.WebTemplate,
SiteScriptIds: siteDesign.SiteScriptIds.toString(),
numberSiteScripts: siteDesign.SiteScriptIds.length,
IsDefault: siteDesign.IsDefault,
PreviewImageAltText: siteDesign.PreviewImageAltText,
PreviewImageUrl: siteDesign.PreviewImageUrl,
Version: siteDesign.Version,
runStatus: false
}
);
}
this.setState({ items: this.items, isLoading: false, disableCommandOption: true });
} else {
this.setState({
items: this.items,
hasError: true,
errorMessage: strings.ErrorMessageUserNotAdmin,
isLoading: false
});
}
}
catch (error) {
this.setState({
items: this.items,
hasError: true,
errorMessage: error.message,
isLoading: false
});
}
}
// Refresh
public onRefresh(ev: React.MouseEvent<HTMLElement>) {
ev.preventDefault();
// LoadTenantProperties
this.loadSiteDesignsProperties();
}
// Component Did Mount
public async componentDidMount() {
// LoadTenantProperties
await this.loadSiteDesignsProperties();
}
// On Render
public render(): React.ReactElement<ISiteDesignsProps> {
return (
<div className={styles.siteDesigns}>
<WebPartTitle displayMode={this.props.displayMode}
title={this.props.title}
className={styles.webPartTitle}
updateProperty={this.props.updateProperty} />
{
this.state.isLoading ?
<Spinner size={SpinnerSize.large} label={strings.LoadingLabel} ariaLive="assertive" />
:
this.state.hasError ?
<MessageBar
messageBarType={MessageBarType.error}>
<span>{this.state.errorMessage}</span>
</MessageBar >
:
this.state.siteDesignRunning ?
<MessageBar
truncated={true}
isMultiline={false}
onDismiss={ (ev) => {this.setState({siteDesignRunning: false});}}
messageBarType={MessageBarType.info}
styles={{
root: {
background: 'rgba(113, 175, 229, 0.2)',
color: '#00188f'
},
icon: {
color: '#00188f'
}
}}
>
{
this.state.siteDesignRunningMessage.map((message) =>{
return (
<span>{message}<br/></span>
);
})
}
</MessageBar>
:
null
}
{
!this.state.hasError && !this.state.isLoading &&
< div className={styles.commandBar}>
<CommandBar
items={[
{
key: 'newItem',
name: strings.CommandbarNewLabel,
iconProps: {
iconName: 'Add'
},
onClick: this.onNewItem,
},
{
key: 'edit',
name: strings.CommandbarEditLabel,
iconProps: {
iconName: 'Edit'
},
onClick: this.onEditItem,
disabled: this.state.disableCommandOption,
},
{
key: 'delete',
name: strings.CommandbarDeleteLabel,
iconProps: {
iconName: 'Delete'
},
onClick: this.onDeleteItem,
disabled: this.state.disableCommandOption,
},
{
key: 'apply',
name: strings.CommandbarApplyLabel,
iconProps: {
iconName: 'Play'
},
onClick: this.onApplyItem,
disabled: this.state.disableCommandOption,
},
{
key: 'rights',
name: strings.CommandbarRightsLabel,
iconProps: {
iconName: 'Permissions'
},
onClick: this.onRights,
disabled: this.state.disableCommandOption,
},
{
key: 'sitescripts',
name: strings.CommandbarSiteScriptsLabel,
iconProps: {
iconName: 'FileCode'
},
onClick: this.onSiteScripts,
disabled: this.state.disableCommandOption,
}
]}
farItems={[
{
key: 'refresh',
name: strings.CommandbarRefreshLabel,
iconProps: {
iconName: 'Refresh'
},
onClick: this.onRefresh,
}
]}
/>
</div>
}
{
!this.state.hasError && !this.state.isLoading &&
<ListView
items={this.state.items}
viewFields={viewFields}
compact={false}
selectionMode={SelectionMode.single}
selection={this._getSelection}
showFilter={true}
filterPlaceHolder={strings.SearchPlaceholder}
/>
}
{
this.state.showPanel && this.state.panelMode == panelMode.SiteScripts &&
<React.Suspense fallback={<div>Loading...</div>}>
<this.SiteScriptsList
mode={this.state.panelMode}
SiteDesignSelectedItem={this.state.selectItem}
onDismiss={this.onDismissPanel}
showPanel={this.state.showPanel}
context={this.props.context}
/>
</React.Suspense>
}
{
this.state.showPanel && this.state.panelMode == panelMode.New &&
<React.Suspense fallback={<div>Loading...</div>}>
<this.AddSiteDesign
mode={this.state.panelMode}
onDismiss={this.onDismissPanel}
showPanel={this.state.showPanel}
context={this.props.context}
/>
</React.Suspense>
}
{
this.state.showPanel && this.state.panelMode == panelMode.edit &&
<React.Suspense fallback={<div>Loading...</div>}>
<this.EditSiteDesign
mode={this.state.panelMode}
onDismiss={this.onDismissPanel}
showPanel={this.state.showPanel}
context={this.props.context}
siteDesignInfo={this.state.selectItem}
/>
</React.Suspense>
}
{
this.state.showPanel && this.state.panelMode == panelMode.Delete &&
<React.Suspense fallback={<div>Loading...</div>}>
<this.DeleteSiteDesign
mode={this.state.panelMode}
onDismiss={this.onDismissPanel}
showPanel={this.state.showPanel}
context={this.props.context}
siteDesignInfo={this.state.selectItem}
/>
</React.Suspense>
}
{
this.state.showPanel && this.state.panelMode == panelMode.Rights &&
<React.Suspense fallback={<div>Loading...</div>}>
<this.SiteDesignRights
mode={this.state.panelMode}
onDismiss={this.onDismissPanel}
showPanel={this.state.showPanel}
context={this.props.context}
SiteDesignSelectedItem={this.state.selectItem}
/>
</React.Suspense>
}
{
this.state.showPanel && this.state.panelMode == panelMode.Apply &&
<React.Suspense fallback={<div>Loading...</div>}>
<this.ApplySiteDesign
onDismiss={this.onDismissApplyPanel}
showPanel={this.state.showPanel}
context={this.props.context}
siteDesignInfo={this.state.selectItem}
/>
</React.Suspense>
}
</div >
);
}
} | the_stack |
import { getComponentName, ComponentConstructor, getComponentClassId, ComponentLike } from './Component'
import { IEngine, IEntity, ComponentAdded, ComponentRemoved, ParentChanged } from './IEntity'
import { EventManager } from './EventManager'
import { newId, log } from './helpers'
import { Attachable } from './Attachable'
// tslint:disable:no-use-before-declare
/**
* @public
*/
export class Entity implements IEntity {
public children: Record<string, IEntity> = {}
public eventManager: EventManager | null = null
public alive: boolean = false
public readonly uuid: string = newId('E')
public readonly components: Record<string, any> = {}
// @internal
public engine: IEngine | null = null
// @internal
private _parent: IEntity | null = null
constructor(public name?: string) {
// stub
}
/**
* Adds or replaces a component in the entity.
* @param component - component instance.
*/
addComponentOrReplace<T extends object>(component: T): T {
if (typeof component === 'function') {
throw new Error('You passed a function or class as a component, an instance of component is expected')
}
if (typeof component !== 'object') {
throw new Error(`You passed a ${typeof component}, an instance of component is expected`)
}
const componentName = getComponentName(component)
if (this.components[componentName]) {
if (this.components[componentName] === component) {
return component
}
this.removeComponent(this.components[componentName], false)
}
return this.addComponent(component)
}
/**
* Returns a boolean indicating if a component is present in the entity.
* @param component - component class, instance or name
*/
hasComponent<T = any>(component: string): boolean
hasComponent<T>(component: ComponentConstructor<T>): boolean
hasComponent<T extends object>(component: T): boolean
hasComponent<T>(component: ComponentConstructor<T> | string): boolean {
const typeOfComponent = typeof component
if (typeOfComponent !== 'string' && typeOfComponent !== 'object' && typeOfComponent !== 'function') {
throw new Error('Entity#has(component): component is not a class, name or instance')
}
if ((component as any) == null) return false
const componentName = typeOfComponent === 'string' ? (component as string) : getComponentName(component as any)
const storedComponent = this.components[componentName]
if (!storedComponent) {
return false
}
if (typeOfComponent === 'object') {
return storedComponent === component
}
if (typeOfComponent === 'function') {
return storedComponent instanceof (component as ComponentConstructor<T>)
}
return true
}
/**
* Gets a component, if it doesn't exist, it throws an Error.
* @param component - component class or name
*/
getComponent<T = any>(component: string): T
getComponent<T>(component: ComponentConstructor<T>): T
getComponent<T>(component: ComponentConstructor<T> | string): T {
const typeOfComponent = typeof component
if (typeOfComponent !== 'string' && typeOfComponent !== 'function') {
throw new Error('Entity#get(component): component is not a class or name')
}
const componentName = typeOfComponent === 'string' ? (component as string) : getComponentName(component as any)
const storedComponent = this.components[componentName]
if (!storedComponent) {
throw new Error(`Can not get component "${componentName}" from entity "${this.identifier}"`)
}
if (typeOfComponent === 'function') {
if (storedComponent instanceof (component as ComponentConstructor<T>)) {
return storedComponent
} else {
throw new Error(`Can not get component "${componentName}" from entity "${this.identifier}" (by instance)`)
}
}
return storedComponent
}
/**
* Gets a component, if it doesn't exist, it returns null.
* @param component - component class or name
*/
getComponentOrNull<T = any>(component: string): T | null
getComponentOrNull<T>(component: ComponentConstructor<T>): T | null
getComponentOrNull<T>(component: ComponentConstructor<T> | string): T | null {
const typeOfComponent = typeof component
if (typeOfComponent !== 'string' && typeOfComponent !== 'function') {
throw new Error('Entity#getOrNull(component): component is not a class or name')
}
const componentName = typeOfComponent === 'string' ? (component as string) : getComponentName(component as any)
const storedComponent = this.components[componentName]
if (!storedComponent) {
return null
}
if (typeOfComponent === 'function') {
if (storedComponent instanceof (component as ComponentConstructor<T>)) {
return storedComponent
} else {
return null
}
}
return storedComponent
}
/**
* Gets a component, if it doesn't exist, it creates the component and returns it.
* @param component - component class
*/
getComponentOrCreate<T>(component: ComponentConstructor<T> & { new(): T }): T {
if (typeof (component as any) !== 'function') {
throw new Error('Entity#getOrCreate(component): component is not a class')
}
let ret = this.getComponentOrNull(component)
if (!ret) {
ret = new component()
// Safe-guard to only add registered components to entities
getComponentName(ret)
this.addComponentOrReplace(ret as any)
}
return ret
}
/**
* Adds a component. If the component already exist, it throws an Error.
* @param component - component instance.
*/
addComponent<T extends object>(component: T): T {
if (typeof component !== 'object') {
throw new Error(
'Entity#add(component): You passed a function or class as a component, an instance of component is expected'
)
}
const componentName = getComponentName(component)
const classId = getComponentClassId(component)
if (this.components[componentName]) {
throw new Error(`A component of type "${componentName}" is already present in entity "${this.identifier}"`)
}
this.components[componentName] = component
if (this.eventManager) {
this.eventManager.fireEvent(new ComponentAdded(this, componentName, classId))
}
const storedComponent = component as ComponentLike
if (typeof storedComponent.addedToEntity === 'function') {
storedComponent.addedToEntity(this)
}
return component
}
/**
* Removes a component instance from the entity.
* @param component - component instance to remove
* @param triggerRemovedEvent - should this action trigger an event?
*/
removeComponent(component: string, triggerRemovedEvent?: boolean): void
removeComponent<T extends object>(component: T, triggerRemovedEvent?: boolean): void
removeComponent(component: ComponentConstructor<any>, triggerRemovedEvent?: boolean): void
removeComponent(component: object | string | Function, triggerRemovedEvent = true): void {
const typeOfComponent = typeof component
if (typeOfComponent !== 'string' && typeOfComponent !== 'function' && typeOfComponent !== 'object') {
throw new Error('Entity#remove(component): component is not a class, class or name')
}
const componentName = typeOfComponent === 'string' ? (component as string) : getComponentName(component as any)
const storedComponent = this.components[componentName] as ComponentLike | void
if (!storedComponent) {
log(`Entity Warning: Trying to remove inexisting component "${componentName}" from entity "${this.identifier}"`)
return
}
if (typeOfComponent === 'function') {
if (storedComponent instanceof (component as ComponentConstructor<any>)) {
delete this.components[componentName]
if (storedComponent) {
if (triggerRemovedEvent && this.eventManager) {
this.eventManager.fireEvent(new ComponentRemoved(this, componentName, storedComponent))
}
if (typeof storedComponent.removedFromEntity === 'function') {
storedComponent.removedFromEntity(this)
}
}
return
} else {
log(
`Entity Warning: Trying to remove wrong (by constructor) component "${componentName}" from entity "${this.identifier}"`
)
return
}
}
delete this.components[componentName]
if (storedComponent) {
if (triggerRemovedEvent && this.eventManager) {
this.eventManager.fireEvent(new ComponentRemoved(this, componentName, storedComponent))
}
if (typeof storedComponent.removedFromEntity === 'function') {
storedComponent.removedFromEntity(this)
}
}
return
}
/**
* Returns true if the entity is already added to the engine.
* Returns false if no engine was defined.
*/
isAddedToEngine(): boolean {
if (this.engine && (this.uuid in this.engine.entities || this.engine.rootEntity === this)) {
return true
}
return false
}
/**
* Sets the parent entity
*/
setParent(_parent: IEntity | Attachable | null): IEntity {
let newParent: IEntity | null
// Check if parent is of type Attachable
if (_parent && 'getEntityRepresentation' in _parent) {
if (!this.engine) {
throw new Error(`In order to set an attachable as parent, you first need to add the entity to the engine.`)
}
newParent = _parent.getEntityRepresentation(this.engine)
} else {
// @ts-ignore
newParent = !_parent && this.engine ? this.engine.rootEntity : _parent
}
let currentParent = this.getParent()
if (newParent === this) {
throw new Error(
`Failed to set parent for entity "${this.identifier}": An entity can't set itself as a its own parent`
)
}
if (newParent === currentParent) {
return this
}
const circularAncestor = this.getCircularAncestor(newParent)
if (circularAncestor) {
throw new Error(
`Failed to set parent for entity "${this.identifier}": Circular parent references are not allowed (See entity "${circularAncestor}")`
)
}
if (currentParent) {
delete currentParent.children[this.uuid]
}
// Make sure that the parent and child are both on the engine, or off the engine, together
if (newParent !== null && newParent.uuid !== '0') {
if (!newParent.isAddedToEngine() && this.isAddedToEngine()) {
// tslint:disable-next-line:semicolon
this.engine!.removeEntity(this)
}
if (newParent.isAddedToEngine() && !this.isAddedToEngine()) {
// tslint:disable-next-line:semicolon
(newParent as Entity).engine!.addEntity(this)
}
}
this._parent = newParent || null
this.registerAsChild()
if (this.eventManager && this.engine) {
this.eventManager.fireEvent(new ParentChanged(this, newParent))
}
return this
}
/**
* Gets the parent entity
*/
getParent(): IEntity | null {
return this._parent
}
private get identifier() {
return this.name || this.uuid
}
private getCircularAncestor(ent: IEntity | null): string | null {
const root = this.engine ? this.engine.rootEntity : null
let e: IEntity | null = ent
while (e && e !== root) {
const parent: IEntity | null = e.getParent()
if (parent === this) {
return e.uuid
}
e = parent
}
return null
}
private registerAsChild() {
const parent = this.getParent()
if (this.uuid && parent) {
parent.children[this.uuid] = this
}
}
} | the_stack |
import { ElementRef } from '@angular/core';
import { createServiceFactory, SpectatorService } from '@ngneat/spectator';
import {
Chart,
ChartData,
ChartDataset as ChartJSDataset,
ChartType as ChartJSType,
} from 'chart.js';
import { AnnotationOptions, AnnotationTypeRegistry } from 'chartjs-plugin-annotation';
import { MockProvider } from 'ng-mocks';
import { deepCopy } from '../../../helpers/deep-copy';
import { ChartDataLabelOptions } from '../chart.types';
import { ChartDataset, ChartType, ChartTypesConfig } from '../chart.types';
import { ChartHighlightedElements } from '../chart.types';
import { ChartConfigService } from '../configs/chart-config.service';
import { CHART_GLOBAL_DEFAULTS } from '../configs/global-defaults.config';
import { ChartJSService } from './chart-js.service';
import { TEST_CHART_ANNOTATIONS_CONFIG, TEST_CHART_TYPES_CONFIG } from './test-utils';
describe('ChartJSService', () => {
let spectator: SpectatorService<ChartJSService>;
let chartJSService: ChartJSService;
let canvasElement: ElementRef<HTMLCanvasElement>;
const mockChartConfigService = MockProvider(ChartConfigService, {
getTypeConfig: (chartType: ChartType) => deepCopy(TEST_CHART_TYPES_CONFIG[chartType]),
getInteractionFunctionsExtensions: () => ({ onHover: () => console.log('testing') }),
getAnnotationDefaults: (type: string) => TEST_CHART_ANNOTATIONS_CONFIG[type],
chartTypeToChartJSType: (type: ChartType) => TEST_CHART_TYPES_CONFIG[type].type as ChartJSType,
});
const createService = createServiceFactory({
service: ChartJSService,
providers: [mockChartConfigService],
});
beforeEach(() => {
spectator = createService();
const nativeElement = document.createElement('canvas');
chartJSService = spectator.service;
canvasElement = new ElementRef<HTMLCanvasElement>(nativeElement);
});
describe('function: renderChart', () => {
it('should render chart with correct defaults for filler plugin', () => {
const data = [7, 7.37, 7.46];
chartJSService.renderChart({
targetElement: canvasElement,
type: 'line',
data: data,
dataLabels: ['one', 'two', 'three'],
});
const fillerOptions = chartJSService['chart'].options.plugins.filler;
expect(fillerOptions.propagate).toBeTrue();
expect(fillerOptions.drawTime).toBe('beforeDatasetDraw');
});
describe('when annotations are given', () => {
it('should render the chart with annotations applied', () => {
const annotations: AnnotationOptions[] = [
{ type: 'line', yMin: 10, yMax: 10 },
{ type: 'line', yMin: 20, yMax: 20 },
];
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
annotations,
});
expect(chartJSService['chart'].options.plugins.annotation.annotations.length).toEqual(2);
});
});
describe('when data is given as a number[]', () => {
it('should render a new chart', () => {
expect(chartJSService['chart']).toBeUndefined();
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
});
expect(chartJSService['chart']).toBeInstanceOf(Chart);
});
it('should use the supplied data in the chart', () => {
const data = [1, 2, 3];
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data,
dataLabels: ['one', 'two', 'three'],
});
const chart = chartJSService['chart'];
expect(chart.data.datasets[0].data).toEqual(data);
});
describe('when highlightedElements are given', () => {
it('should mark given elements as highlighted', () => {
const highlightedElements = [
[0, 0],
[0, 2],
];
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
highlightedElements,
});
const datasets = chartJSService['chart'].data.datasets as ChartDataset[];
expect(datasets.length).toEqual(1);
expect(datasets[0].kirbyOptions.highlightedElements).toEqual([0, 2]);
});
});
});
describe('when custom options are given', () => {
it('should overwrite options set by global defaults', () => {
// Check if a global default is actually being overwritten
expect(CHART_GLOBAL_DEFAULTS.elements.bar.backgroundColor).not.toBeUndefined();
const customElementBackgroundColor = '#ffffff';
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
customOptions: {
elements: {
bar: {
backgroundColor: customElementBackgroundColor,
},
},
},
});
const chart = chartJSService['chart'];
expect(chart.options.elements.bar.backgroundColor).toEqual(customElementBackgroundColor);
});
it('should overwrite type specific options', () => {
// Check if a type config is actually being overwritten
const type = 'bar';
const customIndexAxis = 'x';
expect(TEST_CHART_TYPES_CONFIG[type].options.indexAxis).toBe('y');
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
customOptions: {
indexAxis: customIndexAxis,
},
});
const chart = chartJSService['chart'];
expect(chart.options.indexAxis).toEqual(customIndexAxis);
});
});
describe('when no data labels are provided', () => {
it('should have a blank label for each data point', () => {
chartJSService.renderChart({
targetElement: canvasElement,
type: 'column',
data: [1, 2, 3],
});
const chartDataLabels = chartJSService['chart'].data.labels;
expect(chartDataLabels.length).toEqual(3);
chartDataLabels.forEach((dataLabel) => {
expect(dataLabel).toEqual('');
});
});
describe('function: createConfigurationObject', () => {
it('should not be filled with blank labels if type is stock', () => {
const stockChartConfig = {
targetElement: canvasElement,
type: 'stock' as ChartType,
data: [
{
data: [
{ x: 10, y: 5 },
{ x: 11, y: 6 },
{ x: 13, y: 6 },
],
},
],
};
chartJSService.renderChart(stockChartConfig);
console.log(chartJSService['chart'].options.locale);
expect(chartJSService['chart'].data.labels.length).toEqual(3);
chartJSService['chart'].data.labels.forEach((label) => {
expect(label).not.toBe('');
});
});
});
describe('when data is given as a chartJSDataset[]', () => {
it('should render a new chart', () => {
expect(chartJSService['chart']).toBeUndefined();
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [{ data: [1, 2, 3] }],
dataLabels: ['one', 'two', 'three'],
});
expect(chartJSService['chart']).toBeInstanceOf(Chart);
});
it('should use the supplied data in the chart', () => {
const data = [1, 2, 3];
const dataset = {
data: data,
};
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [dataset],
dataLabels: ['one', 'two', 'three'],
});
const chart = chartJSService['chart'];
expect(chart.data.datasets[0].data).toEqual(data);
});
describe('that contains more than one entry', () => {
it('should use every supplied dataset in the chart', () => {
const data1 = [1, 2, 3];
const data2 = [4, 5, 6];
const datasets = [
{
data: data1,
},
{ data: data2 },
];
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: datasets,
dataLabels: ['one', 'two', 'three'],
});
const chart = chartJSService['chart'];
expect(chart.data.datasets[0].data).toEqual(data1);
expect(chart.data.datasets[1].data).toEqual(data2);
});
});
describe('when highlightedElements are given', () => {
it('should mark given elements as highlighted', () => {
const highlightedElements = [
[0, 0],
[0, 2],
];
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [{ data: [1, 2, 3] }],
dataLabels: ['one', 'two', 'three'],
highlightedElements,
});
const datasets = chartJSService['chart'].data.datasets as ChartDataset[];
expect(datasets.length).toEqual(1);
expect(datasets[0].kirbyOptions.highlightedElements).toEqual([0, 2]);
});
});
});
});
});
describe('function: redrawChart', () => {
beforeEach(() => {
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
});
});
it('should update the chart', () => {
const updateSpy = spyOn(chartJSService['chart'], 'update');
chartJSService.redrawChart();
expect(updateSpy).toHaveBeenCalledTimes(1);
});
it('should keep the same chart', () => {
const initialId = chartJSService['chart'].id;
chartJSService.redrawChart();
expect(chartJSService['chart'].id).toEqual(initialId);
});
});
describe('function: updateData', () => {
let chart: Chart;
beforeEach(() => {
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
});
chart = chartJSService['chart'];
});
describe('when data is given as a number[]', () => {
it('should update the chart data', () => {
const newData = [4, 5, 6];
expect(chart.data.datasets[0].data).not.toEqual(newData);
chartJSService.updateData(newData);
expect(chart.data.datasets[0].data).toEqual(newData);
});
});
describe('when data is given as a chartJSDataset[]', () => {
it('should update the chart data', () => {
const newDataset = [
{
data: [7, 8, 9],
},
];
expect(chart.data.datasets[0].data).not.toEqual(newDataset[0].data);
chartJSService.updateData(newDataset);
expect(chart.data.datasets[0].data).toEqual(newDataset[0].data);
});
describe('that contains more than one entry', () => {
it('should update to have multiple datasets', () => {
const newDatasets = [
{
data: [7, 8, 9],
},
{ data: [10, 11, 12] },
];
expect(chart.data.datasets.length).toBe(1);
chartJSService.updateData(newDatasets);
expect(chart.data.datasets[0].data).toEqual(newDatasets[0].data);
expect(chart.data.datasets[1].data).toEqual(newDatasets[1].data);
});
});
});
});
describe('function: updateDataLabels', () => {
let chart: Chart;
beforeEach(() => {
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
});
chart = chartJSService['chart'];
});
it('should update the data labels of the chart', () => {
const newDatalabels = ['Tre', 'Fire', 'Fem'];
expect(chart.data.labels).not.toEqual(newDatalabels);
chartJSService.updateDataLabels(newDatalabels);
expect(chart.data.labels).toEqual(newDatalabels);
});
});
describe('function: updateType', () => {
beforeEach(() => {
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
});
});
let chartTypesThatDestructivelyUpdate: ChartType[] = ['bar', 'column'];
let chartTypesThatUpdateNormally: ChartType[] = ['line'];
chartTypesThatDestructivelyUpdate.forEach((chartType) => {
describe(`if the new type is ChartType.${chartType}`, () => {
it('should destructively update type', () => {
const destructivelyUpdateTypeSpy = spyOn<any>(chartJSService, 'destructivelyUpdateType');
chartJSService.updateType(chartType, {});
expect(destructivelyUpdateTypeSpy).toHaveBeenCalledTimes(1);
});
});
});
chartTypesThatUpdateNormally.forEach((chartType) => {
describe(`if the new type is ChartType.${chartType}`, () => {
it('should non-destructively update type', () => {
const nonDestructivelyUpdateTypeSpy = spyOn<any>(
chartJSService,
'nonDestructivelyUpdateType'
);
chartJSService.updateType(chartType, {});
expect(nonDestructivelyUpdateTypeSpy).toHaveBeenCalledTimes(1);
});
});
});
});
describe('private function: createOptionsObject', () => {
it('should apply interaction functions extensions', () => {
const applyInteractionFunctionsExtensionsSpy = spyOn<any>(
chartJSService,
'applyInteractionFunctionsExtensions'
);
chartJSService['createOptionsObject']({});
expect(applyInteractionFunctionsExtensionsSpy).toHaveBeenCalledTimes(1);
});
});
describe('private function: nonDestructivelyUpdateType', () => {
let chart: Chart;
beforeEach(() => {
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
annotations: [{ type: 'line', yMin: 10, yMax: 10 }],
});
chart = chartJSService['chart'];
});
it('should set a new type', () => {
const oldType = chart.config.type;
const newType = 'line';
expect(oldType).not.toBe(newType);
chartJSService['nonDestructivelyUpdateType']('line');
expect(chart.config.type).not.toBe(oldType);
expect(newType).toBe('line');
});
it('should apply config from new type', () => {
const newType = 'line';
const newBorderColor = TEST_CHART_TYPES_CONFIG[newType].options.elements.line.borderColor;
expect(chart.options.elements.line.borderColor).not.toEqual(newBorderColor);
chartJSService['nonDestructivelyUpdateType'](newType);
chart.update(); // An update is needed for changes to be reflected
expect(chart.options.elements.line.borderColor).toEqual(newBorderColor);
});
it('should apply custom options', () => {
const oldBackgroundColor = chart.options.bar?.datasets?.backgroundColor;
const newBackgroundColor = 'rgba(125,124,123,1)';
chartJSService['nonDestructivelyUpdateType']('line', {
elements: { bar: { backgroundColor: newBackgroundColor } },
});
expect(oldBackgroundColor).toBeUndefined();
expect(chart.config.options.elements.bar.backgroundColor).toBe(newBackgroundColor);
});
it('should preserve the chart', () => {
const oldChartId = chart.id;
chartJSService['nonDestructivelyUpdateType']('bar');
expect(chartJSService['chart'].id).toEqual(oldChartId);
});
it('should preserve the original dataLabels', () => {
const oldDatalabels = chart.data.labels;
chartJSService['nonDestructivelyUpdateType']('line');
expect(chartJSService['chart'].data.labels).toEqual(oldDatalabels);
});
it('should preserve the original annotations', () => {
const oldAnnotations = chart.options.plugins.annotation.annotations;
chartJSService['nonDestructivelyUpdateType']('line');
chart.update(); // Annotation changes are not visible before update
const newAnnotations = chartJSService['chart'].options.plugins.annotation.annotations;
expect(newAnnotations).toEqual(oldAnnotations);
});
});
describe('private function: destructivelyUpdateType', () => {
let chart: Chart;
beforeEach(() => {
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
annotations: [{ type: 'line', yMin: 10, yMax: 10 }],
});
chart = chartJSService['chart'];
});
it('should replace the old chart element', () => {
const oldChartId = chart.id;
chartJSService['destructivelyUpdateType']('bar');
expect(chartJSService['chart'].id).not.toEqual(oldChartId);
});
it('should preserve the original data', () => {
const oldDatasets = chart.data.datasets;
chartJSService['destructivelyUpdateType']('bar');
expect(chartJSService['chart'].data.datasets).toEqual(oldDatasets);
});
it('should preserve the original dataLabels', () => {
const oldDatalabels = chart.data.labels;
chartJSService['destructivelyUpdateType']('bar');
expect(chartJSService['chart'].data.labels).toEqual(oldDatalabels);
});
it('should preserve the original annotations', () => {
const oldAnnotations = chart.options.plugins.annotation.annotations;
chartJSService['destructivelyUpdateType']('bar');
expect(chartJSService['chart'].options.plugins.annotation.annotations).toEqual(
oldAnnotations
);
});
});
describe('function: updateOptions', () => {
const chartType = 'bar';
let annotations: AnnotationOptions[];
beforeEach(() => {
annotations = [{ type: 'line', yMin: 20, yMax: 20 }];
chartJSService.renderChart({
targetElement: canvasElement,
type: chartType,
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
customOptions: {
borderColor: 'pink',
},
annotations,
});
});
it('should overwrite existing custom options', () => {
expect(chartJSService['chart'].options.borderColor).toEqual('pink');
chartJSService.updateOptions(
{
borderColor: 'red',
},
chartType
);
// Options are resolved as part of update
chartJSService['chart'].update();
expect(chartJSService['chart'].options.borderColor).toEqual('red');
});
it('should overwrite options set by global defaults', () => {
// Check if a global default is actually being overwritten
expect(CHART_GLOBAL_DEFAULTS.elements.bar.backgroundColor).not.toBeUndefined();
const customElementBackgroundColor = '#ffffff';
chartJSService.updateOptions(
{
elements: {
bar: {
backgroundColor: customElementBackgroundColor,
},
},
},
chartType
);
// Options are resolved as part of update
chartJSService['chart'].update();
expect(chartJSService['chart'].options.elements.bar.backgroundColor).toEqual(
customElementBackgroundColor
);
});
it('should overwrite type specific options', () => {
// Check if a type config is actually being overwritten
const customIndexAxis = 'x';
expect(TEST_CHART_TYPES_CONFIG[chartType].options.indexAxis).not.toBeUndefined();
expect(TEST_CHART_TYPES_CONFIG[chartType].options.indexAxis).not.toEqual(customIndexAxis);
chartJSService.updateOptions(
{
indexAxis: customIndexAxis,
},
chartType
);
// Options are resolved as part of update
chartJSService['chart'].update();
const chart = chartJSService['chart'];
expect(chart.options.indexAxis).toEqual(customIndexAxis);
});
it('should preserve the original annotations', () => {
const oldAnnotations = chartJSService['chart'].options.plugins.annotation.annotations;
chartJSService.updateOptions(
{
indexAxis: 'x',
},
chartType
);
chartJSService['chart'].update();
const newAnnotations = chartJSService['chart'].options.plugins.annotation.annotations;
expect(newAnnotations.length).not.toBe(0);
expect(newAnnotations).toEqual(oldAnnotations);
});
});
describe('function: updateHighlightedElements', () => {
let data: ChartDataset[] | number[];
let chart: Chart;
beforeEach(() => {
data = [{ data: [1, 2, 3] }, { data: [4, 5, 6] }, { data: [7, 8, 9] }];
chartJSService.renderChart({
targetElement: canvasElement,
type: 'bar',
data,
dataLabels: ['one', 'two', 'three'],
});
chart = chartJSService['chart'];
});
it('should mark the given elements as highlighted for respective datasets', () => {
/* I have not found a way to directly test which color each datapoint is rendered with.
That would however have been the better approach, as it can be seen directly how it is
rendered. But this will suffice for now - the assumption is, that if it is marked
as highlighted in the dataset, it is rendered with the correct color */
const highlightedElements: ChartHighlightedElements = [
[0, 1],
[0, 2],
[2, 1],
[2, 2],
];
chartJSService.updateHighlightedElements(highlightedElements);
chart.update();
highlightedElements.forEach(([datasetIndex, dataIndex]) => {
const dataset = chart.data.datasets[datasetIndex] as ChartDataset;
expect(dataset.kirbyOptions.highlightedElements.includes(dataIndex)).toBeTrue();
});
});
it('should preserve the original data', () => {
const originalData = chart.data.datasets.map((dataset) => dataset.data);
chartJSService.updateHighlightedElements([
[0, 1],
[0, 2],
[2, 1],
[2, 2],
]);
chart.update();
const newData = chart.data.datasets.map((dataset) => dataset.data);
expect(originalData).toEqual(newData);
});
describe('when there already are highlighted elements', () => {
let highlightedElements: ChartHighlightedElements;
beforeEach(() => {
highlightedElements = [
[0, 1],
[0, 2],
];
chartJSService.updateHighlightedElements(highlightedElements);
chart.update();
});
it('should clear the highlight from existing elements', () => {
chartJSService.updateHighlightedElements([
[1, 1],
[1, 2],
]);
chart.update();
highlightedElements.forEach(([datasetIndex, dataIndex]) => {
const dataset = chart.data.datasets[datasetIndex] as ChartDataset;
expect(dataset?.kirbyOptions?.highlightedElements?.includes(dataIndex)).toBeFalsy();
});
});
it('should be possible to remove all highlights by passing an empty array', () => {
chartJSService.updateHighlightedElements([]);
chart.update();
const datasets = chart.data.datasets as ChartDataset[];
datasets.forEach((dataset) => {
expect(dataset?.kirbyOptions?.highlightedElements).toBeFalsy();
});
});
it('should be possible to remove all highlights by passing nothing', () => {
chartJSService.updateHighlightedElements();
chart.update();
const datasets = chart.data.datasets as ChartDataset[];
datasets.forEach((dataset) => {
expect(dataset?.kirbyOptions?.highlightedElements).toBeFalsy();
});
});
});
});
describe('function: updateAnnotations', () => {
const chartType = 'bar';
let chart: Chart;
beforeEach(() => {
chartJSService.renderChart({
targetElement: canvasElement,
type: chartType,
data: [1, 2, 3],
dataLabels: ['one', 'two', 'three'],
});
chart = chartJSService['chart'];
});
describe('if the chart already has annotations applied', () => {
beforeEach(() => {
chart.options.plugins.annotation.annotations = [
{ type: 'line', yMin: -10, yMax: -10 },
{ type: 'line', yMin: 0, yMax: 0 },
];
chartJSService.redrawChart();
expect(chart.options.plugins.annotation.annotations.length).toEqual(2);
});
it('should replace the annotations with new ones', () => {
const newAnnotations: AnnotationOptions[] = [
{ type: 'line', yMin: 10, yMax: 10 },
{ type: 'line', yMin: 20, yMax: 20 },
];
chartJSService.updateAnnotations(newAnnotations);
chartJSService.redrawChart();
const chartAnnotations = chartJSService['chart'].options.plugins.annotation.annotations;
newAnnotations.forEach((newAnnotation, index) => {
const chartAnnotation = chartAnnotations[index];
expect(newAnnotation['yMin']).toEqual(chartAnnotation['yMin']);
expect(newAnnotation['yMax']).toEqual(chartAnnotation['yMax']);
});
expect(chartAnnotations.length).toBe(2);
});
it('should be possible to remove the annotations by passing an empty array', () => {
chartJSService.updateAnnotations([]);
chartJSService.redrawChart();
expect(chart.options.plugins.annotation.annotations.length).toEqual(0);
});
});
describe('if the chart has no annotations applied', () => {
beforeEach(() => {
expect(chart.options.plugins.annotation.annotations).toEqual({});
});
it('should add annotations to the chart', () => {
const annotations: AnnotationOptions[] = [
{ type: 'line', yMin: 10, yMax: 10 },
{ type: 'line', yMin: 20, yMax: 20 },
];
expect(chart.options.plugins.annotation.annotations).toEqual(Object.create(null));
chartJSService.updateAnnotations(annotations);
chartJSService.redrawChart();
expect(chart.options.plugins.annotation.annotations.length).toEqual(2);
});
});
it('should preserve annotation defaults if they are not overwritten', () => {
const annotations: AnnotationOptions[] = [
{ type: 'line', yMin: 10, yMax: 10 },
{ type: 'line', yMin: 20, yMax: 20 },
];
chartJSService.updateAnnotations(annotations);
chartJSService.redrawChart();
const chartAnnotations = chart.options.plugins.annotation.annotations as AnnotationOptions[];
chartAnnotations.forEach((chartAnnotation) => {
const annotationDefaults = TEST_CHART_ANNOTATIONS_CONFIG[chartAnnotation.type];
Object.entries(annotationDefaults).forEach(([key, _]) => {
expect(chartAnnotation[key]).toEqual(annotationDefaults[key]);
});
});
});
it('should be possible to overwrite annotation defaults', () => {
expect(TEST_CHART_ANNOTATIONS_CONFIG['line']['borderDash']).toEqual([6, 3]);
const annotations: AnnotationOptions[] = [
{ type: 'line', yMin: 10, yMax: 10, borderDash: [10, 10] },
{ type: 'line', yMin: 20, yMax: 20, borderDash: [10, 10] },
];
chartJSService.updateAnnotations(annotations);
chartJSService.redrawChart();
const chartAnnotations = chart.options.plugins.annotation.annotations as AnnotationOptions[];
chartAnnotations.forEach((chartAnnotation) => {
expect(chartAnnotation.borderDash).toEqual([10, 10]);
});
});
});
describe('function: addDataLabelsData', () => {
const data: ChartDataset[] = [
{
data: [
{ x: 10, y: 3 },
{ x: 2, y: 7 },
{ x: 19, y: -10 },
],
},
];
const flatDataset: number[] = [1, 2, 3, 4, 5];
describe('when dataset is a flat array', () => {
it('should throw an error if dataset is a flat array', () => {
chartJSService.setDataLabelOptions({});
expect(function() {
chartJSService.addDataLabelsData(flatDataset);
}).toThrowError();
});
});
const dataLabelOptionsProperties = ['showMax', 'showMin', 'showCurrent'];
dataLabelOptionsProperties.forEach((property) => {
describe(`when ChartDataLabelsOptions.${property} is true`, () => {
it(`should have an datalabel propery in dataset`, () => {
chartJSService.setDataLabelOptions({ [property]: true });
const result = chartJSService.addDataLabelsData(deepCopy(data));
expect(
(result[0] as ChartJSDataset).data.find((item: any) => item.datalabel)
).toBeTruthy();
});
});
});
describe('when niether ChartDataLabelsOptions.showMin, showMax, showCurrent is true', () => {
it('should NOT have an datalabel propery in dataset', () => {
chartJSService.setDataLabelOptions({});
const result = chartJSService.addDataLabelsData(deepCopy(data));
expect((result[0] as ChartJSDataset).data.find((item: any) => item.datalabel)).toBeFalsy();
});
});
});
}); | the_stack |
import gensync from "gensync";
import type { Handler } from "gensync";
import { loadPlugin, loadPreset } from "./files";
import { getItemDescriptor } from "./item";
import {
makeWeakCacheSync,
makeStrongCacheSync,
makeStrongCache,
} from "./caching";
import type { CacheConfigurator } from "./caching";
import type {
ValidatedOptions,
PluginList,
PluginItem,
} from "./validation/options";
import { resolveBrowserslistConfigFile } from "./resolve-targets";
// Represents a config object and functions to lazily load the descriptors
// for the plugins and presets so we don't load the plugins/presets unless
// the options object actually ends up being applicable.
export type OptionsAndDescriptors = {
options: ValidatedOptions;
plugins: () => Handler<Array<UnloadedDescriptor>>;
presets: () => Handler<Array<UnloadedDescriptor>>;
};
// Represents a plugin or presets at a given location in a config object.
// At this point these have been resolved to a specific object or function,
// but have not yet been executed to call functions with options.
export type UnloadedDescriptor = {
name: string | undefined;
value: any | Function;
options: {} | undefined | false;
dirname: string;
alias: string;
ownPass?: boolean;
file?: {
request: string;
resolved: string;
};
};
function isEqualDescriptor(
a: UnloadedDescriptor,
b: UnloadedDescriptor,
): boolean {
return (
a.name === b.name &&
a.value === b.value &&
a.options === b.options &&
a.dirname === b.dirname &&
a.alias === b.alias &&
a.ownPass === b.ownPass &&
(a.file && a.file.request) === (b.file && b.file.request) &&
(a.file && a.file.resolved) === (b.file && b.file.resolved)
);
}
export type ValidatedFile = {
filepath: string;
dirname: string;
options: ValidatedOptions;
};
// eslint-disable-next-line require-yield
function* handlerOf<T>(value: T): Handler<T> {
return value;
}
function optionsWithResolvedBrowserslistConfigFile(
options: ValidatedOptions,
dirname: string,
): ValidatedOptions {
if (typeof options.browserslistConfigFile === "string") {
options.browserslistConfigFile = resolveBrowserslistConfigFile(
options.browserslistConfigFile,
dirname,
);
}
return options;
}
/**
* Create a set of descriptors from a given options object, preserving
* descriptor identity based on the identity of the plugin/preset arrays
* themselves, and potentially on the identity of the plugins/presets + options.
*/
export function createCachedDescriptors(
dirname: string,
options: ValidatedOptions,
alias: string,
): OptionsAndDescriptors {
const { plugins, presets, passPerPreset } = options;
return {
options: optionsWithResolvedBrowserslistConfigFile(options, dirname),
plugins: plugins
? () =>
// @ts-expect-error todo(flow->ts) ts complains about incorrect arguments
createCachedPluginDescriptors(plugins, dirname)(alias)
: () => handlerOf([]),
presets: presets
? () =>
// @ts-expect-error todo(flow->ts) ts complains about incorrect arguments
createCachedPresetDescriptors(presets, dirname)(alias)(
!!passPerPreset,
)
: () => handlerOf([]),
};
}
/**
* Create a set of descriptors from a given options object, with consistent
* identity for the descriptors, but not caching based on any specific identity.
*/
export function createUncachedDescriptors(
dirname: string,
options: ValidatedOptions,
alias: string,
): OptionsAndDescriptors {
// The returned result here is cached to represent a config object in
// memory, so we build and memoize the descriptors to ensure the same
// values are returned consistently.
let plugins;
let presets;
return {
options: optionsWithResolvedBrowserslistConfigFile(options, dirname),
*plugins() {
if (!plugins) {
plugins = yield* createPluginDescriptors(
options.plugins || [],
dirname,
alias,
);
}
return plugins;
},
*presets() {
if (!presets) {
presets = yield* createPresetDescriptors(
options.presets || [],
dirname,
alias,
!!options.passPerPreset,
);
}
return presets;
},
};
}
const PRESET_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPresetDescriptors = makeWeakCacheSync(
(items: PluginList, cache: CacheConfigurator<string>) => {
const dirname = cache.using(dir => dir);
return makeStrongCacheSync((alias: string) =>
makeStrongCache(function* (
passPerPreset: boolean,
): Handler<Array<UnloadedDescriptor>> {
const descriptors = yield* createPresetDescriptors(
items,
dirname,
alias,
passPerPreset,
);
return descriptors.map(
// Items are cached using the overall preset array identity when
// possibly, but individual descriptors are also cached if a match
// can be found in the previously-used descriptor lists.
desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc),
);
}),
);
},
);
const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPluginDescriptors = makeWeakCacheSync(
(items: PluginList, cache: CacheConfigurator<string>) => {
const dirname = cache.using(dir => dir);
return makeStrongCache(function* (
alias: string,
): Handler<Array<UnloadedDescriptor>> {
const descriptors = yield* createPluginDescriptors(items, dirname, alias);
return descriptors.map(
// Items are cached using the overall plugin array identity when
// possibly, but individual descriptors are also cached if a match
// can be found in the previously-used descriptor lists.
desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc),
);
});
},
);
/**
* When no options object is given in a descriptor, this object is used
* as a WeakMap key in order to have consistent identity.
*/
const DEFAULT_OPTIONS = {};
/**
* Given the cache and a descriptor, returns a matching descriptor from the
* cache, or else returns the input descriptor and adds it to the cache for
* next time.
*/
function loadCachedDescriptor(
cache: WeakMap<{} | Function, WeakMap<{}, Array<UnloadedDescriptor>>>,
desc: UnloadedDescriptor,
) {
const { value, options = DEFAULT_OPTIONS } = desc;
if (options === false) return desc;
let cacheByOptions = cache.get(value);
if (!cacheByOptions) {
cacheByOptions = new WeakMap();
cache.set(value, cacheByOptions);
}
let possibilities = cacheByOptions.get(options);
if (!possibilities) {
possibilities = [];
cacheByOptions.set(options, possibilities);
}
if (possibilities.indexOf(desc) === -1) {
const matches = possibilities.filter(possibility =>
isEqualDescriptor(possibility, desc),
);
if (matches.length > 0) {
return matches[0];
}
possibilities.push(desc);
}
return desc;
}
function* createPresetDescriptors(
items: PluginList,
dirname: string,
alias: string,
passPerPreset: boolean,
): Handler<Array<UnloadedDescriptor>> {
return yield* createDescriptors(
"preset",
items,
dirname,
alias,
passPerPreset,
);
}
function* createPluginDescriptors(
items: PluginList,
dirname: string,
alias: string,
): Handler<Array<UnloadedDescriptor>> {
return yield* createDescriptors("plugin", items, dirname, alias);
}
function* createDescriptors(
type: "plugin" | "preset",
items: PluginList,
dirname: string,
alias: string,
ownPass?: boolean,
): Handler<Array<UnloadedDescriptor>> {
const descriptors = yield* gensync.all(
items.map((item, index) =>
createDescriptor(item, dirname, {
type,
alias: `${alias}$${index}`,
ownPass: !!ownPass,
}),
),
);
assertNoDuplicates(descriptors);
return descriptors;
}
/**
* Given a plugin/preset item, resolve it into a standard format.
*/
export function* createDescriptor(
pair: PluginItem,
dirname: string,
{
type,
alias,
ownPass,
}: {
type?: "plugin" | "preset";
alias: string;
ownPass?: boolean;
},
): Handler<UnloadedDescriptor> {
const desc = getItemDescriptor(pair);
if (desc) {
return desc;
}
let name;
let options;
// todo(flow->ts) better type annotation
let value: any = pair;
if (Array.isArray(value)) {
if (value.length === 3) {
[value, options, name] = value;
} else {
[value, options] = value;
}
}
let file = undefined;
let filepath = null;
if (typeof value === "string") {
if (typeof type !== "string") {
throw new Error(
"To resolve a string-based item, the type of item must be given",
);
}
const resolver = type === "plugin" ? loadPlugin : loadPreset;
const request = value;
({ filepath, value } = yield* resolver(value, dirname));
file = {
request,
resolved: filepath,
};
}
if (!value) {
throw new Error(`Unexpected falsy value: ${String(value)}`);
}
if (typeof value === "object" && value.__esModule) {
if (value.default) {
value = value.default;
} else {
throw new Error("Must export a default export when using ES6 modules.");
}
}
if (typeof value !== "object" && typeof value !== "function") {
throw new Error(
`Unsupported format: ${typeof value}. Expected an object or a function.`,
);
}
if (filepath !== null && typeof value === "object" && value) {
// We allow object values for plugins/presets nested directly within a
// config object, because it can be useful to define them in nested
// configuration contexts.
throw new Error(
`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`,
);
}
return {
name,
alias: filepath || alias,
value,
options,
dirname,
ownPass,
file,
};
}
function assertNoDuplicates(items: Array<UnloadedDescriptor>): void {
const map = new Map();
for (const item of items) {
if (typeof item.value !== "function") continue;
let nameMap = map.get(item.value);
if (!nameMap) {
nameMap = new Set();
map.set(item.value, nameMap);
}
if (nameMap.has(item.name)) {
const conflicts = items.filter(i => i.value === item.value);
throw new Error(
[
`Duplicate plugin/preset detected.`,
`If you'd like to use two separate instances of a plugin,`,
`they need separate names, e.g.`,
``,
` plugins: [`,
` ['some-plugin', {}],`,
` ['some-plugin', {}, 'some unique name'],`,
` ]`,
``,
`Duplicates detected are:`,
`${JSON.stringify(conflicts, null, 2)}`,
].join("\n"),
);
}
nameMap.add(item.name);
}
} | the_stack |
import { arrObjOrBoth } from "util-array-object-or-both";
import { checkTypesMini } from "check-types-mini";
import { compare } from "ast-compare";
import { traverse } from "ast-monkey-traverse";
import { version as v } from "../package.json";
const version: string = v;
/* eslint no-use-before-define: 0 */
// From "type-fest" by Sindre Sorhus, with added undefined
type JsonValue =
| string
| number
| boolean
| null
| undefined // non-JSON but added too
| JsonObject
| JsonArray;
type JsonObject = { [Key in string]?: JsonValue };
type JsonArray = Array<JsonValue>;
// -----------------------------------------------------------------------------
interface InternalOpts {
key?: null | string;
val?: any;
only?: string | null | undefined;
index?: number;
mode: "find" | "get" | "set" | "drop" | "del" | "arrayFirstOnly";
}
interface Finding {
index: number;
key: string;
val: any;
path: number[];
}
function existy(x: any): boolean {
return x != null;
}
// function isStr(x) { return typeof x === 'string' }
function compareIsEqual(a: any, b: any): boolean {
if (typeof a !== typeof b) {
return false;
}
return !!compare(a, b, { matchStrictly: true, useWildcards: true });
}
function isObj(something: any): boolean {
return (
something && typeof something === "object" && !Array.isArray(something)
);
}
// -----------------------------------------------------------------------------
function monkey(originalInput: JsonValue, originalOpts: InternalOpts) {
console.log(`055 monkey() called`);
const opts: InternalOpts = {
...originalOpts,
};
console.log(
`060 ${`\u001b[${32}m${`FINAL`}\u001b[${39}m`} ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
opts,
null,
4
)}`
);
// ---------------------------------------------------------------------------
// action
interface Data {
count: number;
gatherPath: number[];
finding: any;
}
const data: Data = { count: 0, gatherPath: [], finding: null };
const findings: Finding[] = [];
let ko = false; // key only
let vo = false; // value only
if (existy(opts.key) && opts.val === undefined) {
ko = true;
}
if (!existy(opts.key) && opts.val !== undefined) {
vo = true;
}
console.log(
`088 ${`\u001b[${33}m${`keyOnly, ko`}\u001b[${39}m`} = ${JSON.stringify(
ko,
null,
4
)}; ${`\u001b[${33}m${`valueOnly, vo`}\u001b[${39}m`} = ${JSON.stringify(
vo,
null,
4
)}`
);
let input = originalInput;
if (
opts.mode === "arrayFirstOnly" &&
Array.isArray(input) &&
input.length > 0
) {
input = [input[0]];
}
//
//
//
console.log(`112 ${`\u001b[${32}m${`CALL`}\u001b[${39}m`} traverse()`);
input = traverse(input, (key, val, innerObj) => {
console.log(`114 ${`\u001b[${35}m${`---------------`}\u001b[${39}m`}`);
console.log(
`116 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`key`}\u001b[${39}m`} = ${JSON.stringify(
key,
null,
4
)}; ${`\u001b[${33}m${`val`}\u001b[${39}m`} = ${JSON.stringify(
val,
null,
4
)}; ${`\u001b[${33}m${`innerObj`}\u001b[${39}m`} = ${JSON.stringify(
innerObj,
null,
4
)}`
);
let temp: Finding;
data.count += 1;
data.gatherPath.length = innerObj.depth;
data.gatherPath.push(data.count);
if (opts.mode === "get") {
if (data.count === opts.index) {
if (innerObj.parentType === "object") {
data.finding = {};
data.finding[key] = val;
} else {
data.finding = key;
}
}
} else if (opts.mode === "find" || opts.mode === "del") {
if (
// opts.only satisfied
(opts.only === "any" ||
(opts.only === "array" && innerObj.parentType === "array") ||
(opts.only === "object" && innerObj.parentType !== "array")) && // match
((ko && compareIsEqual(key, opts.key)) ||
(vo && compareIsEqual(val, opts.val)) ||
(!ko &&
!vo &&
compareIsEqual(key, opts.key) &&
compareIsEqual(val, opts.val)))
) {
if (opts.mode === "find") {
temp = {
index: data.count,
key,
val,
path: [...data.gatherPath],
};
findings.push(temp);
} else {
// del() then!
return NaN;
}
} else {
return innerObj.parentType === "object" ? val : key;
}
}
if (opts.mode === "set" && data.count === opts.index) {
return opts.val;
}
if (opts.mode === "drop" && data.count === opts.index) {
return NaN;
}
if (opts.mode === "arrayFirstOnly") {
if (innerObj.parentType === "object" && Array.isArray(val)) {
return [val[0]];
}
if (existy(key) && Array.isArray(key)) {
return [key[0]];
}
return innerObj.parentType === "object" ? val : key;
}
return innerObj.parentType === "object" ? val : key;
});
console.log(`190 ${`\u001b[${35}m${`--------------- fin.`}\u001b[${39}m`}`);
// returns
if (opts.mode === "get") {
return data.finding;
}
if (opts.mode === "find") {
return findings;
}
return input;
}
// -----------------------------------------------------------------------------
// Validate and prep all the options right here
interface FindOpts {
key: null | string;
val: any;
only?: undefined | null | "any" | "array" | "object";
}
function find(input: JsonValue, originalOpts: FindOpts): Finding[] {
if (!existy(input)) {
throw new Error(
"ast-monkey/main.js/find(): [THROW_ID_02] Please provide the input"
);
}
if (
!isObj(originalOpts) ||
(originalOpts.key === undefined && originalOpts.val === undefined)
) {
throw new Error(
"ast-monkey/main.js/find(): [THROW_ID_03] Please provide opts.key or opts.val"
);
}
const opts = { ...originalOpts };
checkTypesMini(opts, null, {
schema: {
key: ["null", "string"],
val: "any",
only: ["undefined", "null", "string"],
},
msg: "ast-monkey/get(): [THROW_ID_04*]",
});
if (typeof opts.only === "string" && opts.only.length > 0) {
opts.only = arrObjOrBoth(opts.only, {
optsVarName: "opts.only",
msg: "ast-monkey/find(): [THROW_ID_05*]",
});
} else {
opts.only = "any";
}
return monkey(input, { ...opts, mode: "find" });
}
interface GetOpts {
index: number; // obligatory for get()
only?: undefined | null | "any" | "array" | "object";
}
function get(input: JsonValue, originalOpts: GetOpts): GetOpts {
if (!existy(input)) {
throw new Error(
"ast-monkey/main.js/get(): [THROW_ID_06] Please provide the input"
);
}
if (!isObj(originalOpts)) {
throw new Error(
"ast-monkey/main.js/get(): [THROW_ID_07] Please provide the opts"
);
}
if (!existy(originalOpts.index)) {
throw new Error(
"ast-monkey/main.js/get(): [THROW_ID_08] Please provide opts.index"
);
}
const opts = { ...originalOpts };
if (typeof opts.index === "string" && /^\d*$/.test(opts.index)) {
opts.index = +opts.index;
} else if (!Number.isInteger(opts.index)) {
throw new Error(
`ast-monkey/main.js/get(): [THROW_ID_11] opts.index must be a natural number. It was given as: ${
opts.index
} (type ${typeof opts.index})`
);
}
return monkey(input, { ...opts, mode: "get" });
}
interface SetOpts {
key: null | string;
val: any;
index: number; // obligatory for get()
only?: undefined | null | "any" | "array" | "object";
}
function set(input: JsonValue, originalOpts: SetOpts): JsonValue {
if (!existy(input)) {
throw new Error(
"ast-monkey/main.js/set(): [THROW_ID_12] Please provide the input"
);
}
if (!isObj(originalOpts)) {
throw new Error(
"ast-monkey/main.js/set(): [THROW_ID_13] Please provide the input"
);
}
if (!existy(originalOpts.key) && originalOpts.val === undefined) {
throw new Error(
"ast-monkey/main.js/set(): [THROW_ID_14] Please provide opts.val"
);
}
if (!existy(originalOpts.index)) {
throw new Error(
"ast-monkey/main.js/set(): [THROW_ID_15] Please provide opts.index"
);
}
const opts = { ...originalOpts };
if (typeof opts.index === "string" && /^\d*$/.test(opts.index)) {
opts.index = +opts.index;
} else if (!Number.isInteger(opts.index)) {
throw new Error(
`ast-monkey/main.js/set(): [THROW_ID_17] opts.index must be a natural number. It was given as: ${opts.index}`
);
}
if (existy(opts.key) && opts.val === undefined) {
opts.val = opts.key;
}
checkTypesMini(opts, null, {
schema: {
key: [null, "string"],
val: "any",
index: "number",
},
msg: "ast-monkey/set(): [THROW_ID_18*]",
});
return monkey(input, { ...opts, mode: "set" });
}
interface DropOpts {
index: number; // obligatory for get()
only?: undefined | null | "any" | "array" | "object";
}
function drop(input: JsonValue, originalOpts: DropOpts): JsonValue {
if (!existy(input)) {
throw new Error(
"ast-monkey/main.js/drop(): [THROW_ID_19] Please provide the input"
);
}
if (!isObj(originalOpts)) {
throw new Error(
"ast-monkey/main.js/drop(): [THROW_ID_20] Please provide the input"
);
}
if (!existy(originalOpts.index)) {
throw new Error(
"ast-monkey/main.js/drop(): [THROW_ID_21] Please provide opts.index"
);
}
const opts = { ...originalOpts };
if (typeof opts.index === "string" && /^\d*$/.test(opts.index)) {
opts.index = +opts.index;
} else if (!Number.isInteger(opts.index)) {
throw new Error(
`ast-monkey/main.js/drop(): [THROW_ID_23] opts.index must be a natural number. It was given as: ${opts.index}`
);
}
return monkey(input, { ...opts, mode: "drop" });
}
interface DelOpts {
key: null | string;
val: any;
only?: undefined | null | "any" | "array" | "object";
}
function del(input: JsonValue, originalOpts: DelOpts): JsonValue {
if (!existy(input)) {
throw new Error(
"ast-monkey/main.js/del(): [THROW_ID_26] Please provide the input"
);
}
if (!isObj(originalOpts)) {
throw new Error(
"ast-monkey/main.js/del(): [THROW_ID_27] Please provide the opts object"
);
}
if (!existy(originalOpts.key) && originalOpts.val === undefined) {
throw new Error(
"ast-monkey/main.js/del(): [THROW_ID_28] Please provide opts.key or opts.val"
);
}
const opts = { ...originalOpts };
checkTypesMini(opts, null, {
schema: {
key: [null, "string"],
val: "any",
only: ["undefined", "null", "string"],
},
msg: "ast-monkey/drop(): [THROW_ID_29*]",
});
if (typeof opts.only === "string" && opts.only.length > 0) {
opts.only = arrObjOrBoth(opts.only, {
msg: "ast-monkey/del(): [THROW_ID_30*]",
optsVarName: "opts.only",
});
} else {
opts.only = "any";
}
return monkey(input, { ...opts, mode: "del" });
}
function arrayFirstOnly(input: JsonValue): JsonValue {
if (!existy(input)) {
throw new Error(
"ast-monkey/main.js/arrayFirstOnly(): [THROW_ID_31] Please provide the input"
);
}
return monkey(input, { mode: "arrayFirstOnly" });
}
// -----------------------------------------------------------------------------
export { find, get, set, drop, del, arrayFirstOnly, traverse, version }; | the_stack |
import { EventEmitter } from 'events'
import type TypedEventEmitter from 'typed-emitter'
import {
CHAT_EVENT_DICT,
} from 'wechaty-puppet'
import type {
Puppet,
ScanStatus,
} from 'wechaty-puppet'
import type {
Friendship,
ContactSelf,
Room,
RoomInvitation,
Contact,
Message,
} from '../user/mod.js'
const WECHATY_EVENT_DICT = {
...CHAT_EVENT_DICT,
dong : 'Should be emitted after we call `Wechaty.ding()`',
error : "Will be emitted when there's an Error occurred.",
heartbeat : 'Will be emitted periodically after the Wechaty started. If not, means that the Wechaty had died.',
puppet : 'Will be emitted when the puppet has been set.',
ready : 'All underlined data source are ready for use.',
start : 'Will be emitted after the Wechaty had been started.',
stop : 'Will be emitted after the Wechaty had been stopped.',
}
type WechatyEventName = keyof typeof WECHATY_EVENT_DICT
/**
* Wechaty Event Listener Interfaces
*/
type WechatyDongEventListener = (data?: string) => void | Promise<void>
type WechatyErrorEventListener = (error: Error) => void | Promise<void>
type WechatyFriendshipEventListener = (friendship: Friendship) => void | Promise<void>
type WechatyHeartbeatEventListener = (data: any) => void | Promise<void>
type WechatyLoginEventListener = (user: ContactSelf) => void | Promise<void>
type WechatyLogoutEventListener = (user: ContactSelf, reason?: string) => void | Promise<void>
type WechatyMessageEventListener = (message: Message) => void | Promise<void>
type WechatyPuppetEventListener = (puppet: Puppet) => void | Promise<void>
type WechatyReadyEventListener = () => void | Promise<void>
type WechatyRoomInviteEventListener = (roomInvitation: RoomInvitation) => void | Promise<void>
type WechatyRoomJoinEventListener = (room: Room, inviteeList: Contact[], inviter: Contact, date?: Date) => void | Promise<void>
type WechatyRoomLeaveEventListener = (room: Room, leaverList: Contact[], remover?: Contact, date?: Date) => void | Promise<void>
type WechatyRoomTopicEventListener = (room: Room, newTopic: string, oldTopic: string, changer: Contact, date?: Date) => void | Promise<void>
type WechatyScanEventListener = (qrcode: string, status: ScanStatus, data?: string) => void | Promise<void>
type WechatyStartStopEventListener = () => void | Promise<void>
/**
* @desc Wechaty Class Event Type
* @typedef WechatyEventName
* @property {string} error - When the bot get error, there will be a Wechaty error event fired.
* @property {string} login - After the bot login full successful, the event login will be emitted, with a Contact of current logged in user.
* @property {string} logout - Logout will be emitted when bot detected log out, with a Contact of the current login user.
* @property {string} heartbeat - Get heartbeat of the bot.
* @property {string} friendship - When someone sends you a friend request, there will be a Wechaty friendship event fired.
* @property {string} message - Emit when there's a new message.
* @property {string} ready - Emit when all data has load completed, in wechaty-puppet-padchat, it means it has sync Contact and Room completed
* @property {string} room-join - Emit when anyone join any room.
* @property {string} room-topic - Get topic event, emitted when someone change room topic.
* @property {string} room-leave - Emit when anyone leave the room.<br>
* - If someone leaves the room by themselves, WeChat will not notice other people in the room, so the bot will never get the "leave" event.
* @property {string} room-invite - Emit when there is a room invitation, see more in {@link RoomInvitation}
* @property {string} scan - A scan event will be emitted when the bot needs to show you a QR Code for scanning. </br>
* It is recommend to install qrcode-terminal(run `npm install qrcode-terminal`) in order to show qrcode in the terminal.
*/
/**
* @desc Wechaty Class Event Function
* @typedef WechatyEventFunction
* @property {Function} error -(this: Wechaty, error: Error) => void | Promise<void> callback function
* @property {Function} login -(this: Wechaty, user: ContactSelf)=> void
* @property {Function} logout -(this: Wechaty, user: ContactSelf) => void | Promise<void>
* @property {Function} scan -(this: Wechaty, url: string, code: number) => void | Promise<void> <br>
* <ol>
* <li>URL: {String} the QR code image URL</li>
* <li>code: {Number} the scan status code. some known status of the code list here is:</li>
* </ol>
* <ul>
* <li>0 initial_</li>
* <li>200 login confirmed</li>
* <li>201 scanned, wait for confirm</li>
* <li>408 waits for scan</li>
* </ul>
* @property {Function} heartbeat -(this: Wechaty, data: any) => void | Promise<void>
* @property {Function} friendship -(this: Wechaty, friendship: Friendship) => void | Promise<void>
* @property {Function} message -(this: Wechaty, message: Message) => void | Promise<void>
* @property {Function} ready -(this: Wechaty) => void | Promise<void>
* @property {Function} room-join -(this: Wechaty, room: Room, inviteeList: Contact[], inviter: Contact) => void | Promise<void>
* @property {Function} room-topic -(this: Wechaty, room: Room, newTopic: string, oldTopic: string, changer: Contact) => void | Promise<void>
* @property {Function} room-leave -(this: Wechaty, room: Room, leaverList: Contact[]) => void | Promise<void>
* @property {Function} room-invite -(this: Wechaty, room: Room, roomInvitation: RoomInvitation) => void | Promise<void> <br>
* see more in {@link RoomInvitation}
*/
/**
* @listens Wechaty
* @param {WechatyEventName} event - Emit WechatyEvent
* @param {WechatyEventFunction} listener - Depends on the WechatyEvent
*
* @return {Wechaty} - this for chaining,
* see advanced {@link https://github.com/wechaty/wechaty-getting-started/wiki/FAQ-EN#36-why-wechatyonevent-listener-return-wechaty|chaining usage}
*
* @desc
* When the bot get message, it will emit the following Event.
*
* You can do anything you want when in these events functions.
* The main Event name as follows:
* - **scan**: Emit when the bot needs to show you a QR Code for scanning. After scan the qrcode, you can login
* - **login**: Emit when bot login full successful.
* - **logout**: Emit when bot detected log out.
* - **message**: Emit when there's a new message.
*
* see more in {@link WechatyEventName}
*
* @example <caption>Event:scan</caption>
* // Scan Event will emit when the bot needs to show you a QR Code for scanning
*
* bot.on('scan', (url, status) => {
* console.log(`[${status}] Scan ${url} to login.` )
* })
*
* @example <caption>Event:login </caption>
* // Login Event will emit when bot login full successful.
*
* bot.on('login', (user) => {
* console.log(`user ${user} login`)
* })
*
* @example <caption>Event:logout </caption>
* // Logout Event will emit when bot detected log out.
*
* bot.on('logout', (user) => {
* console.log(`user ${user} logout`)
* })
*
* @example <caption>Event:message </caption>
* // Message Event will emit when there's a new message.
*
* wechaty.on('message', (message) => {
* console.log(`message ${message} received`)
* })
*
* @example <caption>Event:friendship </caption>
* // Friendship Event will emit when got a new friend request, or friendship is confirmed.
*
* bot.on('friendship', (friendship) => {
* if(friendship.type() === Friendship.Type.Receive){ // 1. receive new friendship request from new contact
* const contact = friendship.contact()
* let result = await friendship.accept()
* if(result){
* console.log(`Request from ${contact.name()} is accept successfully!`)
* } else{
* console.log(`Request from ${contact.name()} failed to accept!`)
* }
* } else if (friendship.type() === Friendship.Type.Confirm) { // 2. confirm friendship
* console.log(`new friendship confirmed with ${contact.name()}`)
* }
* })
*
* @example <caption>Event:room-join </caption>
* // room-join Event will emit when someone join the room.
*
* bot.on('room-join', (room, inviteeList, inviter) => {
* const nameList = inviteeList.map(c => c.name()).join(',')
* console.log(`Room ${room.topic()} got new member ${nameList}, invited by ${inviter}`)
* })
*
* @example <caption>Event:room-leave </caption>
* // room-leave Event will emit when someone leave the room.
*
* bot.on('room-leave', (room, leaverList) => {
* const nameList = leaverList.map(c => c.name()).join(',')
* console.log(`Room ${room.topic()} lost member ${nameList}`)
* })
*
* @example <caption>Event:room-topic </caption>
* // room-topic Event will emit when someone change the room's topic.
*
* bot.on('room-topic', (room, topic, oldTopic, changer) => {
* console.log(`Room ${room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
* })
*
* @example <caption>Event:room-invite, RoomInvitation has been encapsulated as a RoomInvitation Class. </caption>
* // room-invite Event will emit when there's an room invitation.
*
* bot.on('room-invite', async roomInvitation => {
* try {
* console.log(`received room-invite event.`)
* await roomInvitation.accept()
* } catch (e) {
* console.error(e)
* }
* }
*
* @example <caption>Event:error </caption>
* // error Event will emit when there's an error occurred.
*
* bot.on('error', (error) => {
* console.error(error)
* })
*/
interface WechatyEvents {
'room-invite' : WechatyRoomInviteEventListener
'room-join' : WechatyRoomJoinEventListener
'room-leave' : WechatyRoomLeaveEventListener
'room-topic' : WechatyRoomTopicEventListener
dong : WechatyDongEventListener
error : WechatyErrorEventListener
friendship : WechatyFriendshipEventListener
heartbeat : WechatyHeartbeatEventListener
login : WechatyLoginEventListener
logout : WechatyLogoutEventListener
message : WechatyMessageEventListener
puppet : WechatyPuppetEventListener
ready : WechatyReadyEventListener
scan : WechatyScanEventListener
start : WechatyStartStopEventListener
stop : WechatyStartStopEventListener
}
const WechatyEventEmitter = EventEmitter as new () => TypedEventEmitter<
WechatyEvents
>
export type {
WechatyEventName,
WechatyDongEventListener,
WechatyErrorEventListener,
WechatyFriendshipEventListener,
WechatyHeartbeatEventListener,
WechatyLoginEventListener,
WechatyLogoutEventListener,
WechatyMessageEventListener,
WechatyPuppetEventListener,
WechatyReadyEventListener,
WechatyRoomInviteEventListener,
WechatyRoomJoinEventListener,
WechatyRoomLeaveEventListener,
WechatyRoomTopicEventListener,
WechatyScanEventListener,
WechatyStartStopEventListener,
}
export {
WechatyEventEmitter,
} | the_stack |
import * as acorn from 'acorn';
import * as estree from 'estree';
import * as path from 'path';
import * as semver from 'semver';
import * as vm from 'vm';
import {StatusMessage} from '../../client/stackdriver/status-message';
import consoleLogLevel = require('console-log-level');
import * as stackdriver from '../../types/stackdriver';
import * as v8 from '../../types/v8';
import {ResolvedDebugAgentConfig} from '../config';
import {FileStats, ScanStats} from '../io/scanner';
import {MapInfoOutput, SourceMapper} from '../io/sourcemapper';
import * as state from '../state/legacy-state';
import * as utils from '../util/utils';
import * as debugapi from './debugapi';
export class V8BreakpointData {
constructor(
public apiBreakpoint: stackdriver.Breakpoint,
public v8Breakpoint: v8.BreakPoint,
public parsedCondition: estree.Node,
// TODO: The code in this method assumes that `compile` exists. Verify
// that is correct.
// TODO: Update this so that `null|` is not needed for `compile`.
public compile: null | ((src: string) => string)
) {}
}
interface LegacyVm {
runInDebugContext: (context: string) => v8.Debug;
}
export class V8DebugApi implements debugapi.DebugApi {
breakpoints: {[id: string]: V8BreakpointData} = {};
sourcemapper: SourceMapper;
v8: v8.Debug;
config: ResolvedDebugAgentConfig;
fileStats: ScanStats;
listeners: {[id: string]: utils.LegacyListener} = {};
v8Version: RegExpExecArray | null;
usePermanentListener: boolean;
logger: consoleLogLevel.Logger;
handleDebugEvents: (
evt: v8.DebugEvent,
execState: v8.ExecutionState,
eventData: v8.BreakEvent
) => void;
numBreakpoints = 0;
constructor(
logger: consoleLogLevel.Logger,
config: ResolvedDebugAgentConfig,
jsFiles: ScanStats,
sourcemapper: SourceMapper
) {
this.sourcemapper = sourcemapper;
// This constructor is only used in situations where the legacy vm
// interface is used that has the `runInDebugContext` method.
this.v8 = (vm as {} as LegacyVm).runInDebugContext('Debug');
this.config = config;
this.fileStats = jsFiles;
this.v8Version = /(\d+\.\d+\.\d+)\.\d+/.exec(process.versions.v8);
this.logger = logger;
this.usePermanentListener = semver.satisfies(this.v8Version![1], '>=4.5');
this.handleDebugEvents = (
evt: v8.DebugEvent,
execState: v8.ExecutionState,
eventData: v8.BreakEvent
): void => {
try {
switch (evt) {
// TODO: Address the case where `v8` is `null`.
case this.v8.DebugEvent.Break:
eventData.breakPointsHit().forEach(hit => {
const num = hit.script_break_point().number();
if (this.listeners[num].enabled) {
this.logger.info('>>>V8 breakpoint hit<<< number: ' + num);
this.listeners[num].listener(execState, eventData);
}
});
break;
default:
}
} catch (e) {
this.logger.warn('Internal V8 error on breakpoint event: ' + e);
}
};
if (this.usePermanentListener) {
this.logger.info('activating v8 breakpoint listener (permanent)');
this.v8.setListener(this.handleDebugEvents);
}
}
set(
breakpoint: stackdriver.Breakpoint,
cb: (err: Error | null) => void
): void {
if (
!this.v8 ||
!breakpoint ||
typeof breakpoint.id === 'undefined' || // 0 is a valid id
!breakpoint.location ||
!breakpoint.location.path ||
!breakpoint.location.line
) {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.UNSPECIFIED,
utils.messages.INVALID_BREAKPOINT
);
}
const baseScriptPath = path.normalize(breakpoint.location.path);
const mapInfoInput = this.sourcemapper.getMapInfoInput(baseScriptPath);
if (mapInfoInput === null) {
const extension = path.extname(baseScriptPath);
if (!this.config.javascriptFileExtensions.includes(extension)) {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_SOURCE_LOCATION,
utils.messages.COULD_NOT_FIND_OUTPUT_FILE
);
}
this.setInternal(breakpoint, null /* mapInfo */, null /* compile */, cb);
} else {
const line = breakpoint.location.line;
const column = 0;
const mapInfo = this.sourcemapper.getMapInfoOutput(
line,
column,
mapInfoInput
);
const compile = utils.getBreakpointCompiler(breakpoint);
if (breakpoint.condition && compile) {
try {
breakpoint.condition = compile(breakpoint.condition);
} catch (e) {
this.logger.info(
'Unable to compile condition >> ' + breakpoint.condition + ' <<'
);
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_CONDITION,
utils.messages.ERROR_COMPILING_CONDITION
);
}
}
this.setInternal(breakpoint, mapInfo, compile, cb);
}
}
clear(
breakpoint: stackdriver.Breakpoint,
cb: (err: Error | null) => void
): void {
if (typeof breakpoint.id === 'undefined') {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_CONDITION,
utils.messages.V8_BREAKPOINT_CLEAR_ERROR
);
}
const breakpointData = this.breakpoints[breakpoint.id];
if (!breakpointData) {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_CONDITION,
utils.messages.V8_BREAKPOINT_CLEAR_ERROR
);
}
const v8bp = breakpointData.v8Breakpoint;
this.v8.clearBreakPoint(v8bp.number());
delete this.breakpoints[breakpoint.id];
delete this.listeners[v8bp.number()];
this.numBreakpoints--;
if (this.numBreakpoints === 0 && !this.usePermanentListener) {
// removed last breakpoint
this.logger.info('deactivating v8 breakpoint listener');
this.v8.setListener(null);
}
setImmediate(() => {
cb(null);
});
}
wait(
breakpoint: stackdriver.Breakpoint,
callback: (err?: Error) => void
): void {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
const num = that.breakpoints[breakpoint.id].v8Breakpoint.number();
const listener = this.onBreakpointHit.bind(
this,
breakpoint,
(err: Error | null) => {
that.listeners[num].enabled = false;
// This method is called from the debug event listener, which
// swallows all exception. We defer the callback to make sure the
// user errors aren't silenced.
setImmediate(() => {
callback(err || undefined);
});
}
);
that.listeners[num] = {enabled: true, listener};
}
log(
breakpoint: stackdriver.Breakpoint,
print: (format: string, exps: string[]) => void,
shouldStop: () => boolean
): void {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const that = this;
const num = that.breakpoints[breakpoint.id].v8Breakpoint.number();
let logsThisSecond = 0;
let timesliceEnd = Date.now() + 1000;
// TODO: Determine why the Error argument is not used.
const listener = this.onBreakpointHit.bind(this, breakpoint, () => {
const currTime = Date.now();
if (currTime > timesliceEnd) {
logsThisSecond = 0;
timesliceEnd = currTime + 1000;
}
print(
// TODO: Address the case where `breakpoint.logMessageFormat` is
// null
breakpoint.logMessageFormat!,
breakpoint.evaluatedExpressions.map(obj => JSON.stringify(obj))
);
logsThisSecond++;
if (shouldStop()) {
that.listeners[num].enabled = false;
} else {
if (logsThisSecond >= that.config.log.maxLogsPerSecond) {
that.listeners[num].enabled = false;
setTimeout(() => {
// listeners[num] may have been deleted by `clear` during the
// async hop. Make sure it is valid before setting a property
// on it.
if (!shouldStop() && that.listeners[num]) {
that.listeners[num].enabled = true;
}
}, that.config.log.logDelaySeconds * 1000);
}
}
});
that.listeners[num] = {enabled: true, listener};
}
disconnect(): void {
return;
}
numBreakpoints_(): number {
return Object.keys(this.breakpoints).length;
}
numListeners_(): number {
return Object.keys(this.listeners).length;
}
private setInternal(
breakpoint: stackdriver.Breakpoint,
mapInfo: MapInfoOutput | null,
compile: ((src: string) => string) | null,
cb: (err: Error | null) => void
): void {
// Parse and validate conditions and watch expressions for correctness and
// immutability
let ast = null;
if (breakpoint.condition) {
try {
// We parse as ES6; even though the underlying V8 version may only
// support a subset. This should be fine as the objective of the parse
// is to heuristically find side-effects. V8 will raise errors later
// if the syntax is invalid. It would have been nice if V8 had made the
// parser API available us :(.
ast = acorn.parse(breakpoint.condition, {
sourceType: 'script',
ecmaVersion: 6,
});
// eslint-disable-next-line @typescript-eslint/no-var-requires
const validator = require('../util/validator.js');
if (!validator.isValid(ast)) {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_CONDITION,
utils.messages.DISALLOWED_EXPRESSION
);
}
} catch (err) {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_CONDITION,
utils.messages.SYNTAX_ERROR_IN_CONDITION + (err as Error).message
);
}
}
// Presently it is not possible to precisely disambiguate the script
// path from the path provided by the debug server. The issue is that we
// don't know the repository root relative to the root filesystem or
// relative to the working-directory of the process. We want to make sure
// that we are setting the breakpoint that the user intended instead of a
// breakpoint in a file that happens to have the same name but is in a
// different directory. Until this is addressed between the server and the
// debuglet, we are going to assume that repository root === the starting
// working directory.
let matchingScript;
const scriptPath = mapInfo
? mapInfo.file
: path.normalize(
(breakpoint.location as stackdriver.SourceLocation).path
);
const scripts = utils.findScripts(
scriptPath,
this.config,
this.fileStats,
this.logger
);
if (scripts.length === 0) {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_SOURCE_LOCATION,
utils.messages.SOURCE_FILE_NOT_FOUND
);
} else if (scripts.length === 1) {
// Found the script
matchingScript = scripts[0];
} else {
this.logger.warn(
`Unable to unambiguously find ${scriptPath}. Potential matches: ${scripts}`
);
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_SOURCE_LOCATION,
utils.messages.SOURCE_FILE_AMBIGUOUS
);
}
// The breakpoint protobuf message presently doesn't have a column property
// but it may have one in the future.
// TODO: Address the case where `breakpoint.location` is `null`.
let column =
mapInfo && mapInfo.column
? mapInfo.column
: (breakpoint.location as stackdriver.SourceLocation).column || 1;
const line = mapInfo
? mapInfo.line
: (breakpoint.location as stackdriver.SourceLocation).line;
// We need to special case breakpoints on the first line. Since Node.js
// wraps modules with a function expression, we adjust
// to deal with that.
if (line === 1) {
column += debugapi.MODULE_WRAP_PREFIX_LENGTH - 1;
}
// TODO: Address the case where `fileStats[matchingScript]` is `null`.
if (line >= (this.fileStats[matchingScript] as FileStats).lines) {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_SOURCE_LOCATION,
utils.messages.INVALID_LINE_NUMBER +
matchingScript +
':' +
line +
'. Loaded script contained ' +
(this.fileStats[matchingScript] as FileStats).lines +
' lines. Please ensure' +
' that the snapshot was set in the same code version as the' +
' deployed source.'
);
}
const v8bp = this.setByRegExp(matchingScript, line, column);
if (!v8bp) {
return utils.setErrorStatusAndCallback(
cb,
breakpoint,
StatusMessage.BREAKPOINT_SOURCE_LOCATION,
utils.messages.V8_BREAKPOINT_ERROR
);
}
if (this.numBreakpoints === 0 && !this.usePermanentListener) {
// added first breakpoint
this.logger.info('activating v8 breakpoint listener');
this.v8.setListener(this.handleDebugEvents);
}
this.breakpoints[breakpoint.id] =
// TODO: Address the case where `ast` is `null`.
new V8BreakpointData(breakpoint, v8bp, ast as estree.Node, compile);
this.numBreakpoints++;
setImmediate(() => {
cb(null);
}); // success.
}
private setByRegExp(
scriptPath: string,
line: number,
column: number
): v8.BreakPoint {
const regexp = utils.pathToRegExp(scriptPath);
const num = this.v8.setScriptBreakPointByRegExp(
regexp,
line - 1,
column - 1
);
const v8bp = this.v8.findBreakPoint(num);
return v8bp;
}
private onBreakpointHit(
breakpoint: stackdriver.Breakpoint,
callback: (err: Error | null) => void,
execState: v8.ExecutionState
): void {
// TODO: Address the situation where `breakpoint.id` is `null`.
const v8bp = this.breakpoints[breakpoint.id].v8Breakpoint;
if (!v8bp.active()) {
// Breakpoint exists, but not active. We never disable breakpoints, so
// this is theoretically not possible. Perhaps this is possible if there
// is a second debugger present? Regardless, report the error.
return utils.setErrorStatusAndCallback(
callback,
breakpoint,
StatusMessage.BREAKPOINT_SOURCE_LOCATION,
utils.messages.V8_BREAKPOINT_DISABLED
);
}
const result = this.checkCondition(breakpoint, execState);
if (result.error) {
return utils.setErrorStatusAndCallback(
callback,
breakpoint,
StatusMessage.BREAKPOINT_CONDITION,
utils.messages.ERROR_EVALUATING_CONDITION + result.error
);
} else if (!result.value) {
// Check again next time
this.logger.info("\tthe breakpoint condition wasn't met");
return;
}
// Breakpoint Hit
const start = process.hrtime();
try {
this.captureBreakpointData(breakpoint, execState);
} catch (err) {
return utils.setErrorStatusAndCallback(
callback,
breakpoint,
StatusMessage.BREAKPOINT_SOURCE_LOCATION,
utils.messages.CAPTURE_BREAKPOINT_DATA + err
);
}
const end = process.hrtime(start);
this.logger.info(utils.formatInterval('capture time: ', end));
callback(null);
}
/**
* Evaluates the breakpoint condition, if present.
* @return object with either a boolean value or an error property
*/
private checkCondition(
breakpoint: stackdriver.Breakpoint,
execState: v8.ExecutionState
): {value?: boolean; error?: string} {
if (!breakpoint.condition) {
return {value: true};
}
const result = state.evaluate(breakpoint.condition, execState.frame(0));
if (result.error) {
return {error: result.error};
}
// TODO: Address the case where `result.mirror` is `null`.
return {
value: !!(result.mirror as v8.ValueMirror).value(),
}; // intentional !!
}
private captureBreakpointData(
breakpoint: stackdriver.Breakpoint,
execState: v8.ExecutionState
): void {
const expressionErrors: Array<stackdriver.Variable | null> = [];
if (breakpoint.expressions && this.breakpoints[breakpoint.id].compile) {
for (let i = 0; i < breakpoint.expressions.length; i++) {
try {
breakpoint.expressions[i] =
// TODO: Address the case where `compile` is `null`.
(
this.breakpoints[breakpoint.id].compile as (
text: string
) => string
)(breakpoint.expressions[i]);
} catch (e) {
this.logger.info(
'Unable to compile watch expression >> ' +
breakpoint.expressions[i] +
' <<'
);
expressionErrors.push({
name: breakpoint.expressions[i],
status: new StatusMessage(
StatusMessage.VARIABLE_VALUE,
'Error Compiling Expression',
true
),
});
breakpoint.expressions.splice(i, 1);
i--;
}
}
}
if (breakpoint.action === 'LOG') {
// TODO: This doesn't work with compiled languages if there is an error
// compiling one of the expressions in the loop above.
if (!breakpoint.expressions) {
breakpoint.evaluatedExpressions = [];
} else {
const frame = execState.frame(0);
const evaluatedExpressions = breakpoint.expressions.map(exp => {
const result = state.evaluate(exp, frame);
// TODO: Address the case where `result.mirror` is `undefined`.
return result.error
? result.error
: (result.mirror as v8.ValueMirror).value();
});
breakpoint.evaluatedExpressions = evaluatedExpressions;
}
} else {
// TODO: Address the case where `breakpoint.expression` is `undefined`.
const captured = state.capture(
execState,
breakpoint.expressions as string[],
this.config,
this.v8
);
if (
breakpoint.location &&
utils.isJavaScriptFile(breakpoint.location.path) &&
captured.location &&
captured.location.line
) {
breakpoint.location.line = captured.location.line;
}
breakpoint.stackFrames = captured.stackFrames;
// TODO: This suggests the Status type and Variable type are the same.
// Determine if that is the case.
breakpoint.variableTable =
captured.variableTable as stackdriver.Variable[];
breakpoint.evaluatedExpressions = expressionErrors.concat(
captured.evaluatedExpressions
);
}
}
} | the_stack |
import { match, not, Pattern, select, when, __ } from '../src';
import { Equal, Expect } from '../src/types/helpers';
import { Option, some, none, BigUnion, State, Event } from './utils';
describe('exhaustive()', () => {
describe('should exclude matched patterns from subsequent `.with()` clauses', () => {
it('string literals', () => {
type Input = 'a' | 'b' | 'c';
const input = 'b' as Input;
match(input)
.with('b', (x) => {
const check: 'b' = x;
return 1;
})
// @ts-expect-error
.exhaustive();
match(input)
.with('a', (x) => 1)
.with('b', (x) => 1)
// @ts-expect-error
.exhaustive();
match(input)
.with('a', (x) => {
const check: 'a' = x;
return 1;
})
.with('b', (x) => {
const check: 'b' = x;
return 2;
})
// @ts-expect-error
.exhaustive();
match(input)
.with('a', (x) => {
const check: 'a' = x;
return 1;
})
.with('b', (x) => {
const check: 'b' = x;
return 2;
})
.with('c', (x) => {
const check: 'c' = x;
return 2;
})
.exhaustive();
});
it('number literals', () => {
type Input = 1 | 2 | 3;
const input = 2 as Input;
match(input)
.with(2, (x) => {
const check: 2 = x;
return 2;
})
// @ts-expect-error
.exhaustive();
match(input)
.with(1, (x) => 1)
.with(2, () => 3)
// @ts-expect-error
.exhaustive();
match(input)
.with(1, (x) => {
const check: 1 = x;
return 1;
})
.with(2, (x) => {
const check: 2 = x;
return 2;
})
// @ts-expect-error
.exhaustive();
match(input)
.with(1, (x) => {
const check: 1 = x;
return 1;
})
.with(2, (x) => {
const check: 2 = x;
return 2;
})
.with(3, (x) => {
const check: 3 = x;
return 2;
})
.exhaustive();
});
it('boolean literals', () => {
type Input =
| [true, true]
| [false, true]
| [false, false]
| [true, false];
const input = [true, true] as Input;
match(input)
.with([true, true], () => true)
.with([false, true], () => false)
.with([true, false], () => false)
// @ts-expect-error
.exhaustive();
match(input)
.with([true, true], () => true)
.with([false, true], () => false)
.with([true, false], () => false)
.with([false, false], () => false)
.exhaustive();
});
it('boolean literals', () => {
type Input = [boolean, boolean];
const input = [true, true] as Input;
match(input)
.with([true, true], () => true)
.with([false, true], () => false)
.with([true, false], () => false)
// @ts-expect-error
.exhaustive();
match(input)
.with([true, true], () => true)
.with([false, true], () => false)
.with([true, false], () => false)
.with([false, false], () => false)
.exhaustive();
});
it('union of objects', () => {
type letter =
| 'a'
| 'b'
| 'c'
| 'd'
| 'e'
| 'f'
| 'g'
| 'h'
| 'i'
| 'j'
| 'k'
| 'l'
| 'm'
| 'n'
| 'o'
| 'p'
| 'q'
| 'r'
| 's'
| 't'
| 'u'
| 'v'
| 'w'
| 'x'
| 'y'
| 'z';
type Input =
| { type: 1; data: number }
| { type: 'two'; data: string }
| { type: 3; data: boolean }
| { type: 4 }
| (letter extends any ? { type: letter } : never);
const input = { type: 1, data: 2 } as Input;
match(input)
.with({ type: 1 }, (x) => 1)
// @ts-expect-error
.exhaustive();
match(input)
.with({ type: 1 }, (x) => 1)
.with({ type: 'two' }, (x) => 2)
// @ts-expect-error
.exhaustive();
match(input)
.with({ type: 1, data: select() }, (data) => {
type t = Expect<Equal<typeof data, number>>;
return 1;
})
.with({ type: 'two', data: select() }, (data) => data.length)
.with({ type: 3, data: true }, ({ data }) => {
type t = Expect<Equal<typeof data, true>>;
return 3;
})
.with({ type: 3, data: __ }, ({ data }) => {
type t = Expect<Equal<typeof data, boolean>>;
return 3;
})
.with({ type: 4 }, () => 3)
.with({ type: 'a' }, () => 0)
.with({ type: 'b' }, () => 0)
.with({ type: 'c' }, () => 0)
.with({ type: 'd' }, () => 0)
.with({ type: 'e' }, () => 0)
.with({ type: 'f' }, () => 0)
.with({ type: 'g' }, () => 0)
.with({ type: 'h' }, () => 0)
.with({ type: 'i' }, () => 0)
.with({ type: 'j' }, () => 0)
.with({ type: 'k' }, () => 0)
.with({ type: 'l' }, () => 0)
.with({ type: 'm' }, () => 0)
.with({ type: 'n' }, () => 0)
.with({ type: 'o' }, () => 0)
.with({ type: 'p' }, () => 0)
.with({ type: 'q' }, () => 0)
.with({ type: 'r' }, () => 0)
.with({ type: 's' }, () => 0)
.with({ type: 't' }, () => 0)
.with({ type: 'u' }, () => 0)
.with({ type: 'v' }, () => 0)
.with({ type: 'w' }, () => 0)
.with({ type: 'x' }, () => 0)
.with({ type: 'y' }, () => 0)
.with({ type: 'z' }, () => 0)
.exhaustive();
match<Option<number>>({ kind: 'some', value: 3 })
.with({ kind: 'some' }, ({ value }) => value)
.with({ kind: 'none' }, () => 0)
.exhaustive();
match<Option<number>>({ kind: 'some', value: 3 })
.with({ kind: 'some', value: 3 }, ({ value }): number => value)
.with({ kind: 'none' }, () => 0)
// @ts-expect-error: missing {kind: 'some', value: number}
.exhaustive();
match<Option<number>>({ kind: 'some', value: 3 })
.with({ kind: 'some', value: 3 }, ({ value }): number => value)
.with({ kind: 'some', value: __.number }, ({ value }): number => value)
.with({ kind: 'none' }, () => 0)
.exhaustive();
});
it('union of tuples', () => {
type Input = [1, number] | ['two', string] | [3, boolean];
const input = [1, 3] as Input;
match(input)
.with([1, __], (x) => 1)
// @ts-expect-error
.exhaustive();
match(input)
.with([1, __], (x) => 1)
.with(['two', __], (x) => 2)
// @ts-expect-error
.exhaustive();
match(input)
.with([1, __], (x) => 1)
.with(['two', __], ([_, data]) => data.length)
.with([3, __], () => 3)
.exhaustive();
match(input)
.with([1, __], (x) => 1)
.with(['two', 'Hey'], ([_, data]) => data.length)
.with(['two', __], ([_, data]) => data.length)
.with([3, __], () => 3)
.exhaustive();
});
it('deeply nested 1', () => {
type Input =
| [1, Option<number>]
| ['two', Option<string>]
| [3, Option<boolean>];
const input = [1, { kind: 'some', value: 3 }] as Input;
match(input)
.with([1, { kind: 'some' }], (x) => 1)
// @ts-expect-error
.exhaustive();
match(input)
.with([1, __], (x) => 1)
.with(['two', __], (x) => 2)
// @ts-expect-error
.exhaustive();
match(input)
.with([1, __], (x) => 1)
.with(['two', { kind: 'some' }], ([_, { value }]) => value.length)
.with([3, __], () => 3)
// @ts-expect-error
.exhaustive();
match(input)
.with(['two', { kind: 'some' }], ([_, { value }]) => value.length)
.with(['two', { kind: 'none' }], () => 4)
.with([1, __], () => 3)
.with([3, __], () => 3)
.exhaustive();
});
it('deeply nested 2', () => {
type Input = ['two', Option<string>];
const input = ['two', { kind: 'some', value: 'hello' }] as Input;
match(input)
.with(['two', { kind: 'some' }], ([_, { value }]) => value.length)
.with(['two', { kind: 'none' }], () => 4)
.exhaustive();
});
it('should work with non-unions', () => {
match<number>(2)
.with(2, () => 'two')
.with(3, () => 'three')
// @ts-expect-error
.exhaustive();
match<number>(2)
.with(2, () => 'two')
.with(3, () => 'three')
.with(__.number, () => 'something else')
.exhaustive();
match<string>('Hello')
.with('Hello', () => 'english')
.with('Bonjour', () => 'french')
// @ts-expect-error
.exhaustive();
match<string>('Hello')
.with('Hello', () => 'english')
.with('Bonjour', () => 'french')
.with(__, (c) => 'something else')
.exhaustive();
});
it('should work with object properties union', () => {
type Input = { value: 'a' | 'b' };
const input = { value: 'a' } as Input;
match(input)
.with({ value: 'a' }, (x) => 1)
// @ts-expect-error
.exhaustive();
match(input)
.with({ value: __ }, (x) => 1)
.exhaustive();
match(input)
.with({ value: 'a' }, (x) => 1)
.with({ value: 'b' }, (x) => 1)
.exhaustive();
});
it('should work with lists', () => {
type Input =
| {
type: 'a';
items: ({ some: string; data: number } | string)[];
}
| {
type: 'b';
items: { other: boolean; data: string }[];
};
const input = {
type: 'a',
items: [{ some: 'hello', data: 42 }],
} as Input;
match(input)
.with({ type: 'a' }, (x) => x.items)
// @ts-expect-error
.exhaustive();
match(input)
.with({ type: 'a' }, (x) => x.items)
.with({ type: 'b', items: [{ data: __.string }] }, (x) => [])
.exhaustive();
match(input)
.with({ type: 'a', items: [__] }, (x) => x.items)
.with({ type: 'b', items: [{ data: __.string }] }, (x) => [])
.exhaustive();
match<Input>(input)
.with({ type: 'a', items: [{ some: __ }] }, (x) => x.items)
.with({ type: 'b', items: [{ data: __.string }] }, (x) => [])
// @ts-expect-error
.exhaustive();
});
it('should support __ in a readonly tuple', () => {
const f = (n: number, state: State) => {
const x = match([n, state] as const)
.with(
[1, { status: 'success', data: select() }],
([_, { data }]) => data.startsWith('coucou'),
(data) => data.replace('coucou', 'bonjour')
)
.with([2, __], () => "It's a twoooo")
.with([__, { status: 'error' }], () => 'Oups')
.with([__, { status: 'idle' }], () => '')
.with([__, { status: 'loading' }], () => '')
.with([__, { status: 'success' }], () => '')
.exhaustive();
};
});
it('should work with Sets', () => {
type Input = Set<string> | Set<number>;
const input = new Set(['']) as Input;
match(input)
.with(new Set([__.string]), (x) => x)
// @ts-expect-error
.exhaustive();
match(input)
.with(new Set([__.string]), (x) => x)
.with(new Set([__.number]), (x) => new Set([]))
.exhaustive();
});
it('should work with Sets', () => {
type Input = Set<string> | Set<number>;
const input = new Set(['']) as Input;
expect(
match(input)
.with(new Set([__.string]), (x) => x)
// @ts-expect-error
.exhaustive()
).toEqual(input);
expect(
match(input)
.with(new Set([__.string]), (x) => 1)
.with(new Set([__.number]), (x) => 2)
.exhaustive()
).toEqual(1);
});
it('should work with Maps', () => {
type Input = Map<string, 1 | 2 | 3>;
const input = new Map([['hello', 1]]) as Input;
expect(
match(input)
.with(new Map([['hello' as const, __.number]]), (x) => x)
// @ts-expect-error
.exhaustive()
).toEqual(input);
expect(
match(input)
.with(new Map([['hello' as const, 1 as const]]), (x) => x)
// @ts-expect-error
.exhaustive()
).toEqual(input);
expect(
match(input)
.with(new Map([['hello', 1 as const]]), (x) => x)
// @ts-expect-error
.exhaustive()
).toEqual(input);
match(input)
.with(__, (x) => x)
.exhaustive();
});
it('should work with structures with a lot of unions', () => {
type X = 1 | 2 | 3 | 4 | 5 | 6 | 7;
// This structures has 7 ** 9 = 40353607 possibilities
match<{
a: X;
b: X;
c: X;
d: X;
e: X;
f: X;
g: X;
h: X;
i: X;
}>({ a: 1, b: 1, c: 1, d: 1, e: 1, f: 1, g: 1, h: 1, i: 1 })
.with({ b: 1 }, () => 'otherwise')
.with({ b: 2 }, () => 'b = 2')
.with({ b: 3 }, () => 'otherwise')
.with({ b: 4 }, () => 'otherwise')
.with({ b: 5 }, () => 'otherwise')
.with({ b: 6 }, () => 'otherwise')
.with({ b: 7 }, () => 'otherwise')
.exhaustive();
match<{
a: X;
b: X;
c: X;
}>({ a: 1, b: 1, c: 1 })
.with({ a: not(1) }, () => 'a != 1')
.with({ a: 1 }, () => 'a != 1')
.exhaustive();
match<{
a: BigUnion;
b: BigUnion;
}>({ a: 'a', b: 'b' })
.with({ a: 'a' }, () => 0)
.with({ a: 'b' }, () => 0)
.with({ a: 'c' }, (x) => 0)
.with({ a: 'd' }, () => 0)
.with({ a: 'e' }, (x) => 0)
.with({ a: 'f', b: __ }, (x) => 0)
.with({ a: __ }, (x) => 0)
.exhaustive();
});
it('should work with generics', () => {
const last = <a>(xs: a[]) =>
match<a[], Option<a>>(xs)
.with([], () => none)
.with(__, (x, y) => some(xs[xs.length - 1]))
.exhaustive();
expect(last([1, 2, 3])).toEqual(some(3));
});
it('should work with generics in type guards', () => {
const map = <A, B>(
option: Option<A>,
mapper: (value: A) => B
): Option<B> =>
match<Option<A>, Option<B>>(option)
.when(
(option): option is { kind: 'some'; value: A } =>
option.kind === 'some',
(option) => ({
kind: 'some',
value: mapper(option.value),
})
)
.when(
(option): option is { kind: 'none' } => option.kind === 'none',
(option) => option
)
.otherwise(() => ({ kind: 'none' }));
const res = map(
{ kind: 'some' as const, value: 20 },
(x) => `number is ${x}`
);
type t = Expect<Equal<typeof res, Option<string>>>;
expect(res).toEqual({ kind: 'some' as const, value: `number is 20` });
});
it('should work with inputs of varying shapes', () => {
type Input = { type: 'test' } | ['hello', Option<string>] | 'hello'[];
const input = { type: 'test' } as Input;
expect(
match(input)
.with(['hello', { kind: 'some' }], ([, { value }]) => {
return value;
})
.with(['hello'], ([str]) => {
return str;
})
.with({ type: __ }, (x) => x.type)
.with([__], (x) => `("hello" | Option<string>)[] | "hello"[]`)
.exhaustive()
).toEqual('test');
});
it('should infer literals as literal types', () => {
type Input = { type: 'video'; duration: number };
match<Input>({ type: 'video', duration: 10 })
.with({ type: 'video', duration: 10 }, (x) => '')
// @ts-expect-error
.exhaustive();
let n: number = 10;
match<number>(n)
.with(10, (x) => '')
// @ts-expect-error
.exhaustive();
});
it('should correctly exclude cases if when pattern contains a type guard', () => {
match<{ x: 1 | 2 | 3 }>({ x: 2 })
.with({ x: when((x): x is 1 => x === 1) }, (x) => {
type t = Expect<Equal<typeof x, { x: 1 }>>;
return '';
})
.with({ x: when((x): x is 2 => x === 2) }, (x) => {
type t = Expect<Equal<typeof x, { x: 2 }>>;
return '';
})
.with({ x: when((x): x is 3 => x === 3) }, (x) => {
type t = Expect<Equal<typeof x, { x: 3 }>>;
return '';
})
.exhaustive();
});
it('should correctly exclude cases if .when is a type guard', () => {
match<Option<string>, Option<number>>({ kind: 'none' })
.when(
(option): option is { kind: 'some'; value: string } =>
option.kind === 'some',
(option) => ({
kind: 'some',
value: option.value.length,
})
)
.when(
(option): option is { kind: 'none' } => option.kind === 'none',
(option) => option
)
.exhaustive();
});
it('should correctly exclude cases if the pattern is a literal type', () => {
const input = { kind: 'none' } as Option<string>;
match(input)
.with({ kind: 'some', value: 'hello' }, (option) => '')
.with({ kind: 'none' }, (option) => '')
// @ts-expect-error: handled { kind: 'some', value: string }
.exhaustive();
match(input)
.with({ kind: 'some', value: 'hello' }, (option) => '')
.with({ kind: 'none' }, (option) => '')
.with({ kind: 'some' }, (option) => '')
.exhaustive();
});
it('should not exclude cases if the pattern is a literal type and the value is not', () => {
match({ x: 2 })
.with({ x: 2 }, ({ x }) => {
type t = Expect<Equal<typeof x, number>>;
return '';
})
// @ts-expect-error
.exhaustive();
match<1 | 2 | 3>(2)
.with(2, (x) => {
type t = Expect<Equal<typeof x, 2>>;
return '';
})
// @ts-expect-error
.exhaustive();
match<1 | 2 | 3>(2)
.with(1, (x) => {
type t = Expect<Equal<typeof x, 1>>;
return '';
})
.with(2, (x) => {
type t = Expect<Equal<typeof x, 2>>;
return '';
})
.with(3, (x) => {
type t = Expect<Equal<typeof x, 3>>;
return '';
})
.exhaustive();
});
});
it('real world example', () => {
type Input =
| { type: 'text'; text: string; author: { name: string } }
| { type: 'video'; duration: number; src: string }
| {
type: 'movie';
duration: number;
author: { name: string };
src: string;
title: string;
}
| { type: 'picture'; src: string };
const isNumber = (x: unknown): x is number => typeof x === 'number';
match<Input>({ type: 'text', text: 'Hello', author: { name: 'Gabriel' } })
.with(
{
type: 'text',
text: select('text'),
author: { name: select('authorName') },
},
({ text, authorName }) => `${text} from ${authorName}`
)
.with({ type: 'video', duration: when((x) => x > 10) }, () => '')
.with(
{
type: 'video',
duration: when(isNumber),
},
() => ''
)
.with({ type: 'movie', duration: 10 }, () => '')
.with(
{
type: 'movie',
duration: 10,
author: select('author'),
title: select('title'),
},
({ author, title }) => ''
)
.with({ type: 'picture' }, () => '')
.with({ type: 'movie', duration: when(isNumber) }, () => '')
.exhaustive();
});
it('reducer example', () => {
const initState: State = {
status: 'idle',
};
const reducer = (state: State, event: Event): State =>
match<[State, Event], State>([state, event])
.with(
[{ status: 'loading' }, { type: 'success', data: select() }],
(data) => ({ status: 'success', data })
)
.with(
[{ status: 'loading' }, { type: 'error', error: select() }],
(error) => ({ status: 'error', error })
)
.with([{ status: 'loading' }, { type: 'cancel' }], () => initState)
.with([{ status: not('loading') }, { type: 'fetch' }], (value) => ({
status: 'loading',
}))
.with(__, () => state)
.exhaustive();
});
it('select should always match', () => {
type Input = { type: 3; data: number };
const input = { type: 3, data: 2 } as Input;
match<Input>(input)
.with({ type: 3, data: select() }, (data) => {
type t = Expect<Equal<typeof data, number>>;
return 3;
})
.exhaustive();
type Input2 = { type: 3; data: true } | 2;
match<Input2>(2)
.with({ type: 3, data: select() }, (data) => {
type t = Expect<Equal<typeof data, true>>;
return 3;
})
.with(2, () => 2)
.exhaustive();
});
describe('Exhaustive match and `not` patterns', () => {
it('should work with a single not pattern', () => {
const reducer1 = (state: State, event: Event): State =>
match<[State, Event], State>([state, event])
.with([{ status: not('loading') }, __], (x) => state)
.with([{ status: 'loading' }, { type: 'fetch' }], () => state)
// @ts-expect-error
.exhaustive();
const reducer3 = (state: State, event: Event): State =>
match<[State, Event], State>([state, event])
.with([{ status: not('loading') }, __], (x) => state)
.with([{ status: 'loading' }, __], () => state)
.exhaustive();
});
it('should work with several not patterns', () => {
const reducer = (state: State, event: Event): State =>
match<[State, Event], State>([state, event])
.with(
[{ status: not('loading') }, { type: not('fetch') }],
(x) => state
)
.with([{ status: 'loading' }, { type: __ }], () => state)
.with([{ status: __ }, { type: 'fetch' }], () => state)
.exhaustive();
const f = (input: readonly [1 | 2 | 3, 1 | 2 | 3, 1 | 2 | 3]) =>
match(input)
.with([not(1), not(1), not(1)], (x) => 'ok')
.with([1, __, __], () => 'ok')
.with([__, 1, __], () => 'ok')
.with([__, __, 1], () => 'ok')
.exhaustive();
const range = [1, 2, 3] as const;
const flatMap = <A, B>(
xs: readonly A[],
f: (x: A) => readonly B[]
): B[] => xs.reduce<B[]>((acc, x) => acc.concat(f(x)), []);
const allPossibleCases = flatMap(range, (x) =>
flatMap(range, (y) => flatMap(range, (z) => [[x, y, z]] as const))
);
allPossibleCases.forEach((x) => expect(f(x)).toBe('ok'));
const f2 = (input: [1 | 2 | 3, 1 | 2 | 3, 1 | 2 | 3]) =>
match(input)
.with([not(1), not(1), not(1)], (x) => 'ok')
.with([1, __, __], () => 'ok')
.with([__, 1, __], () => 'ok')
// @ts-expect-error : NonExhaustiveError<[3, 3, 1] | [3, 2, 1] | [2, 3, 1] | [2, 2, 1]>
.exhaustive();
});
it('should work with not patterns and lists', () => {
const f = (input: (1 | 2 | 3)[]) =>
match(input)
.with([not(1)], (x) => 'ok')
.with([1], (x) => 'ok')
// @ts-expect-error: NonExhaustiveError<(1 | 2 | 3)[]>, because lists can be heterogenous
.exhaustive();
});
});
describe('exhaustive and any', () => {
const f = (input: { t: 'a'; x: any } | { t: 'b' }) =>
match(input)
.with({ t: 'a' }, (x) => {
type t = Expect<Equal<typeof x, { t: 'a'; x: any }>>;
return 'ok';
})
.with({ t: 'b' }, (x) => 'ok')
.exhaustive();
const f2 = (input: { t: 'a'; x: any } | { t: 'b' }) =>
match(input)
.with({ t: 'a', x: 'hello' }, (x) => 'ok')
.with({ t: 'b' }, (x) => 'ok')
// @ts-expect-error
.exhaustive();
const f3 = (input: { t: 'a'; x: any } | { t: 'b' }) =>
match(input)
.with({ t: 'a', x: __ }, (x) => 'ok')
.with({ t: 'b' }, (x) => 'ok')
.exhaustive();
});
describe('issue #44', () => {
it("shouldn't exclude cases if the pattern contains unknown keys", () => {
type Person = {
sex: 'Male' | 'Female';
age: 'Adult' | 'Child';
};
function withTypo(person: Person): string {
return (
match(person)
// this pattern contains an addition unknown key
.with({ sex: 'Female', oopsThisIsATypo: 'Adult' }, (x) => 'Woman')
// those are correct
.with({ sex: 'Female', age: 'Child' }, () => 'Girl')
.with({ sex: 'Male', age: 'Adult' }, () => 'Man')
.with({ sex: 'Male', age: 'Child' }, () => 'Boy')
// this pattern shouldn't be considered exhaustive
// @ts-expect-error
.exhaustive()
);
}
function withoutTypo(person: Person): string {
return (
match(person)
.with({ sex: 'Female', age: 'Adult' }, (x) => 'Woman')
.with({ sex: 'Female', age: 'Child' }, () => 'Girl')
.with({ sex: 'Male', age: 'Adult' }, () => 'Man')
.with({ sex: 'Male', age: 'Child' }, () => 'Boy')
// this should be ok
.exhaustive()
);
}
expect(() => withTypo({ sex: 'Female', age: 'Adult' })).toThrow();
expect(withoutTypo({ sex: 'Female', age: 'Adult' })).toBe('Woman');
});
});
}); | the_stack |
import { AnimateDisplayObject } from './DisplayObject';
import { Graphics } from '@pixi/graphics';
import { Sprite } from '@pixi/sprite';
export type EaseMethod = (input: number) => number;
// NOTE ABOUT KEYS OF TweenProps: Use "(myProps[key] as any) = myVal;"
// Typescript is unhelpful in this case: https://github.com/microsoft/TypeScript/issues/31663
export interface TweenProps {
x?: number;
y?: number;
sx?: number;
sy?: number;
kx?: number;
ky?: number;
r?: number;
a?: number;
t?: number;
v?: boolean;
c?: number[];
m?: Graphics|Sprite;
g?: any;
/** Eases for any of the tweenable properties, if published as a per-property ease */
e?: {[P in TweenablePropNames]?: EaseMethod|{n: string; s: number}};
}
export type TweenablePropNames = keyof Omit<TweenProps, 'm'|'g'|'e'|'v'>;
export interface TweenData
{
d: number;
p: TweenProps;
e?: EaseMethod|{n: string; s: number};
}
export interface KeyframeData extends TweenProps
{
/** Not tweenable, but information about a tween that starts on this frame */
tw?: TweenData;
}
// standard tweening
function lerpValue(start: number, end: number, t: number): number
{
return start + ((end - start) * t);
}
const PI = Math.PI;
const TWO_PI = PI * 2;
// handle 355 -> 5 degrees only going through a 10 degree change instead of
// the long way around
// Math from http://stackoverflow.com/a/2708740
function lerpRotation(start: number, end: number, t: number): number
{
const difference = Math.abs(end - start);
if (difference > PI)
{
// We need to add on to one of the values.
if (end > start)
{
// We'll add it on to start...
start += TWO_PI;
}
else
{
// Add it on to end.
end += PI + TWO_PI;
}
}
// Interpolate it.
const value = (start + ((end - start) * t));
// wrap to 0-2PI
/* if (value >= 0 && value <= TWO_PI)
return value;
return value % TWO_PI;*/
// just return, as it's faster
return value;
}
// split r, g, b into separate values for tweening
function lerpTint(start: number, end: number, t: number): number
{
// split start color into components
const sR = (start >> 16) & 0xFF;
const sG = (start >> 8) & 0xFF;
const sB = start & 0xFF;
// split end color into components
const eR = (end >> 16) & 0xFF;
const eG = (end >> 8) & 0xFF;
const eB = end & 0xFF;
// lerp red
let r = sR + ((eR - sR) * t);
// clamp red to valid values
if (r < 0) r = 0;
else if (r > 255) r = 255;
// lerp green
let g = sG + ((eG - sG) * t);
// clamp green to valid values
if (g < 0) g = 0;
else if (g > 255) g = 255;
// lerp blue
let b = sB + ((eB - sB) * t);
// clamp blue to valid values
if (b < 0) b = 0;
else if (b > 255) b = 255;
const combined = (r << 16) | (g << 8) | b;
return combined;
}
const COLOR_HELPER: number[] = [];
function lerpColor(start: number[], end: number[], t: number): number[]
{
COLOR_HELPER[0] = start[0] + ((end[0] - start[0]) * t);
COLOR_HELPER[1] = start[1] + ((end[1] - start[1]) * t);
COLOR_HELPER[2] = start[2] + ((end[2] - start[2]) * t);
COLOR_HELPER[3] = start[3] + ((end[3] - start[3]) * t);
COLOR_HELPER[4] = start[4] + ((end[4] - start[4]) * t);
COLOR_HELPER[5] = start[5] + ((end[5] - start[5]) * t);
return COLOR_HELPER;
}
const PROP_LERPS: {[P in keyof TweenProps]: (start: number, end: number, t: number) => number} = {
// position
x: lerpValue,
y: lerpValue,
// scale
sx: lerpValue,
sy: lerpValue,
// skew
kx: lerpValue,
ky: lerpValue,
// rotation
r: lerpRotation,
// alpha
a: lerpValue,
// tinting
t: lerpTint,
// values to be set
v: null, // visible
c: lerpColor as any, // colorTransform
m: null, // mask
g: null, // not sure if we'll actually handle graphics this way?
};
function setPropFromShorthand(target: AnimateDisplayObject, prop: keyof TweenProps, value: any): void
{
switch (prop)
{
case 'x':
target.transform.position.x = value;
break;
case 'y':
target.transform.position.y = value;
break;
case 'sx':
target.transform.scale.x = value;
break;
case 'sy':
target.transform.scale.y = value;
break;
case 'kx':
target.transform.skew.x = value;
break;
case 'ky':
target.transform.skew.y = value;
break;
case 'r':
target.transform.rotation = value;
break;
case 'a':
target.alpha = value;
break;
case 't':
target.i(value); // i = setTint
break;
case 'c':
target.setColorTransform(...value as [number, number, number, number, number, number]); // c = setColorTransform
break;
case 'v':
target.visible = value;
break;
case 'm':
target.ma(value); // ma = setMask
break;
}
}
// builds an ease in function for a specific exponential power, i.e. quadratic easing is power 2 and cubic is 3
function buildPowIn(power: number): EaseMethod
{
return (t): number => Math.pow(t, power);
}
// builds an ease out function for a specific exponential power, i.e. quadratic easing is power 2 and cubic is 3
function buildPowOut(power: number): EaseMethod
{
return (t): number => 1 - Math.pow(1 - t, power);
}
// builds an ease in & out function for a specific exponential power, i.e. quadratic easing is power 2 and cubic is 3
function buildPowInOut(power: number): EaseMethod
{
return (t): number =>
{
if ((t *= 2) < 1) return 0.5 * Math.pow(t, power);
return 1 - (0.5 * Math.abs(Math.pow(2 - t, power)));
};
}
const ELASTIC_AMPLITUDE = 1;
const ELASTIC_PERIOD = 0.3;
const ELASTIC_INOUT_PERIOD = 0.3 * 1.5;
const EASE_DICT: { [name: string]: EaseMethod } = {
quadIn: buildPowIn(2),
quadOut: buildPowOut(2),
quadInOut: buildPowInOut(2),
cubicIn: buildPowIn(3),
cubicOut: buildPowOut(3),
cubicInOut: buildPowInOut(3),
quartIn: buildPowIn(4),
quartOut: buildPowOut(4),
quartInOut: buildPowInOut(4),
quintIn: buildPowIn(5),
quintOut: buildPowOut(5),
quintInOut: buildPowInOut(5),
sineIn: (t) => 1 - Math.cos(t * PI / 2),
sineOut: (t) => Math.sin(t * PI / 2),
sineInOut: (t) => -0.5 * (Math.cos(PI * t) - 1),
backIn: (t) => t * t * (((1.7 + 1) * t) - 1.7),
backOut: (t) => (--t * t * (((1.7 + 1) * t) + 1.7)) + 1,
backInOut: (t) =>
{
const constVal = 1.7 * 1.525;
if ((t *= 2) < 1) return 0.5 * (t * t * (((constVal + 1) * t) - constVal));
return 0.5 * (((t -= 2) * t * (((constVal + 1) * t) + constVal)) + 2);
},
circIn: (t) => -(Math.sqrt(1 - (t * t)) - 1),
circOut: (t) => Math.sqrt(1 - ((--t) * t)),
circInOut: (t) =>
{
if ((t *= 2) < 1) return -0.5 * (Math.sqrt(1 - (t * t)) - 1);
return 0.5 * (Math.sqrt(1 - ((t -= 2) * t)) + 1);
},
bounceIn: (t) => 1 - EASE_DICT.bounceOut(1 - t),
bounceOut: (t) =>
{
if (t < 1 / 2.75)
{
return 7.5625 * t * t;
}
else if (t < 2 / 2.75)
{
return (7.5625 * (t -= 1.5 / 2.75) * t) + 0.75;
}
else if (t < 2.5 / 2.75)
{
return (7.5625 * (t -= 2.25 / 2.75) * t) + 0.9375;
}
return (7.5625 * (t -= 2.625 / 2.75) * t) + 0.984375;
},
// eslint-disable-next-line no-confusing-arrow
bounceInOut: (t) => t < 0.5 ? EASE_DICT.bounceIn(t * 2) * 0.5 : (EASE_DICT.bounceOut((t * 2) - 1) * 0.5) + 0.5,
elasticIn: (t) =>
{
if (t === 0 || t === 1) return t;
const s = ELASTIC_PERIOD / TWO_PI * Math.asin(1 / ELASTIC_AMPLITUDE);
return -(ELASTIC_AMPLITUDE * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TWO_PI / ELASTIC_PERIOD));
},
elasticOut: (t) =>
{
if (t === 0 || t === 1) return t;
const s = ELASTIC_PERIOD / TWO_PI * Math.asin(1 / ELASTIC_AMPLITUDE);
return (ELASTIC_AMPLITUDE * Math.pow(2, -10 * t) * Math.sin((t - s) * TWO_PI / ELASTIC_PERIOD)) + 1;
},
elasticInOut: (t) =>
{
const s = ELASTIC_INOUT_PERIOD / TWO_PI * Math.asin(1 / ELASTIC_AMPLITUDE);
if ((t *= 2) < 1)
{
return -0.5 * (ELASTIC_AMPLITUDE * Math.pow(2, 10 * (t -= 1))
* Math.sin((t - s) * TWO_PI / ELASTIC_INOUT_PERIOD));
}
return (ELASTIC_AMPLITUDE * Math.pow(2, -10 * (t -= 1))
* Math.sin((t - s) * TWO_PI / ELASTIC_INOUT_PERIOD) * 0.5) + 1;
},
};
export function getEaseFromConfig(config: EaseMethod | { n: string; s: number }): EaseMethod | null
{
if (!config) return null;
if (typeof config === 'function') return config;
// TODO: use config (name, strength) to determine an ease method
// In order to figure that out, we need to test out Animate's actual output values so we know what to use.
if (config.n === 'classic')
{
const s = config.s / 100;
// (s + 1)t + (-s)(t^2)
return (t: number): number => ((s + 1) * t) + ((-s) * t * t);
}
return EASE_DICT[config.n];
}
/**
* Provides timeline playback of movieclip
*/
export class Tween
{
/**
* Target display object.
*/
public target: AnimateDisplayObject;
/**
* Properties at the start of the tween
*/
public startProps: TweenProps;
/**
* Properties at the end of the tween, as well as any properties that are set
* instead of tweened
*/
public endProps: TweenProps;
/**
* duration of tween in frames. For a keyframe with no tweening, the duration will be 0.
*/
public duration: number;
/**
* The frame that the tween starts on
*/
public startFrame: number;
/**
* the frame that the tween ends on
*/
public endFrame: number;
/**
* easing function to use, if any
*/
public ease: {[P in TweenablePropNames]?: EaseMethod};
/**
* If we don't tween.
*/
public isTweenlessFrame: boolean;
/**
* @param target The target to play
* @param startProps The starting properties
* @param endProps The ending properties
* @param startFrame frame number on which to begin tweening
* @param duration Number of frames to tween
* @param ease Ease function to use
*/
constructor(target: AnimateDisplayObject,
startProps: TweenProps,
endProps: TweenProps|null,
startFrame: number,
duration: number,
ease?: EaseMethod)
{
this.target = target;
this.startProps = startProps;
this.endProps = {};
this.duration = duration;
this.startFrame = startFrame;
this.endFrame = startFrame + duration;
this.ease = {};
this.isTweenlessFrame = !endProps;
if (endProps)
{
// make a copy to safely include any unchanged values from the start of the tween
for (const prop in endProps)
{
if (prop === 'e') continue;
// read the end value
(this.endProps[prop as TweenablePropNames] as any) = endProps[prop as TweenablePropNames];
// if there is an ease for that property, use that
if (endProps.e?.[prop as TweenablePropNames])
{
this.ease[prop as TweenablePropNames] = getEaseFromConfig(endProps.e[prop as TweenablePropNames]);
}
// otherwise use the global ease for this tween (if any)
else
{
this.ease[prop as TweenablePropNames] = ease;
}
}
}
// copy in any starting properties don't change
for (const prop in startProps)
{
// eslint-disable-next-line no-prototype-builtins
if (!this.endProps.hasOwnProperty(prop))
{
(this.endProps[prop as keyof TweenProps] as any) = startProps[prop as keyof TweenProps];
}
}
}
/**
* Set the current frame.
*/
public setPosition(currentFrame: number): void
{
// if this is a single frame with no tweening, or at the end of the tween, then
// just speed up the process by setting values
if (currentFrame >= this.endFrame)
{
this.setToEnd();
return;
}
if (this.isTweenlessFrame)
{
this.setToEnd();
return;
}
const time = (currentFrame - this.startFrame) / this.duration;
const target = this.target;
const startProps = this.startProps;
const endProps = this.endProps;
for (const prop in endProps)
{
const p = prop as keyof TweenProps;
const lerp = PROP_LERPS[p];
let lerpedTime = time;
if (this.ease[prop as TweenablePropNames])
{
lerpedTime = this.ease[prop as TweenablePropNames](time);
}
if (lerp)
{
setPropFromShorthand(target, p, lerp(startProps[p], endProps[p], lerpedTime));
}
else
{
setPropFromShorthand(target, p, startProps[p]);
}
}
}
/**
* Set to the end position
*/
setToEnd(): void
{
const endProps = this.endProps;
const target = this.target;
for (const prop in endProps)
{
setPropFromShorthand(target, prop as keyof TweenProps, endProps[prop as keyof TweenProps]);
}
}
} | the_stack |
import { PivotFieldList } from '../../src/pivotfieldlist/base/field-list';
import { createElement, remove, EmitType } from '@syncfusion/ej2-base';
import { pivot_dataset } from '../base/datasource.spec';
import { IDataSet } from '../../src/base/engine';
import { MaskedTextBox } from '@syncfusion/ej2-inputs';
import { profile, inMB, getMemoryProfile } from '../common.spec';
import { MemberEditorOpenEventArgs, MemberFilteringEventArgs } from '../../src/common/base/interface';
describe('- Members limit in editor - field list', () => {
let fieldListObj: PivotFieldList;
let elem: HTMLElement = createElement('div', { id: 'PivotFieldList', styles: 'height:400px;width:60%' });
afterAll(() => {
if (fieldListObj) {
fieldListObj.destroy();
}
remove(elem);
});
beforeAll((done: Function) => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
if (document.getElementById(elem.id)) {
remove(document.getElementById(elem.id));
}
document.body.appendChild(elem);
let dataBound: EmitType<Object> = () => { done(); };
fieldListObj = new PivotFieldList(
{
dataSourceSettings: {
dataSource: pivot_dataset as IDataSet[],
rows: [{ name: 'product' }, { name: 'state' }],
columns: [{ name: 'gender' }],
values: [{ name: 'balance' }, { name: 'quantity' }], filters: [{ name: 'index' }]
},
maxNodeLimitInMemberEditor: 5,
renderMode: 'Fixed',
dataBound: dataBound,
memberEditorOpen: (args: MemberEditorOpenEventArgs) => {
expect(args.fieldMembers).toBeTruthy;
expect(args.cancel).toBe(false);
console.log('MemberFilterOpenNAme: ' + args.fieldName);
},
memberFiltering: (args: MemberFilteringEventArgs) => {
expect(args.filterSettings).toBeTruthy;
expect(args.cancel).toBe(false);
console.log('MemberFilterOpenNAme: ' + args.filterSettings.name);
}
});
fieldListObj.appendTo('#PivotFieldList');
});
it('field list render testing', () => {
// if (document.querySelectorAll('.e-pivot-calc-dialog-div .e-icon-btn')) {
// (document.querySelectorAll('.e-pivot-calc-dialog-div .e-icon-btn')[0] as HTMLElement).click()
// }
expect(document.querySelectorAll('.e-pivot-button').length).toBe(6);
});
it('check filtering field', (done: Function) => {
let pivotButtons: HTMLElement[] =
[].slice.call(document.querySelector('.e-filters').querySelectorAll('.e-pivot-button'));
((pivotButtons[0]).querySelector('.e-btn-filter') as HTMLElement).click();
setTimeout(() => {
expect(document.querySelectorAll('.e-member-editor-container li').length).toBe(5);
done();
}, 1000);
});
it('check all nodes on filter popup', () => {
let allNode: HTMLElement = document.querySelector('.e-member-editor-container .e-checkbox-wrapper');
let args: MouseEvent = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
allNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
allNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("click", { view: window, bubbles: true, cancelable: true });
allNode.querySelector('.e-frame').dispatchEvent(args);
let checkedEle: Element[] = <Element[] & NodeListOf<Element>>document.querySelectorAll('.e-member-editor-container .e-check');
expect(checkedEle.length).toEqual(0);
expect(document.querySelector('.e-ok-btn').getAttribute('disabled')).toBe('disabled');
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[1] as HTMLElement;
args = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("click", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
checkedEle = <Element[] & NodeListOf<Element>>document.querySelectorAll('.e-member-editor-container .e-check');
expect(checkedEle.length).toEqual(1);
expect(document.querySelector('.e-ok-btn').getAttribute('disabled')).toBe(null);
(document.querySelector('.e-ok-btn') as HTMLElement).click();
});
it('check filter state after update', () => {
expect(document.querySelectorAll('.e-pv-filtered').length).toBe(1);
});
it('check filtering field', (done: Function) => {
let pivotButtons: HTMLElement[] =
[].slice.call(document.querySelector('.e-filters').querySelectorAll('.e-pivot-button'));
((pivotButtons[0]).querySelector('.e-btn-filter') as HTMLElement).click();
setTimeout(() => {
expect(document.querySelectorAll('.e-member-editor-container li').length).toBe(5);
expect(document.querySelectorAll('.e-select-all li .e-check').length).toBe(0);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(1);
done();
}, 1000);
});
it('search 0', () => {
let searchOption: MaskedTextBox = fieldListObj.pivotCommon.filterDialog.editorSearch;
searchOption.setProperties({ value: '0' });
searchOption.change({ value: searchOption.value });
expect(document.querySelectorAll('.e-member-editor-container li').length).toBe(5);
expect(document.querySelectorAll('.e-select-all li .e-check').length).toBe(0);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(1);
expect((document.querySelectorAll('.e-member-editor-container li .e-list-text')[1] as HTMLElement).innerText).toBe("10");
});
it('search 11', () => {
let searchOption: MaskedTextBox = fieldListObj.pivotCommon.filterDialog.editorSearch;
searchOption.setProperties({ value: '11' });
searchOption.change({ value: searchOption.value });
expect(document.querySelectorAll('.e-member-editor-container li').length).toBe(5);
expect(document.querySelectorAll('.e-select-all li .e-stop').length).toBe(0);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(0);
expect((document.querySelectorAll('.e-member-editor-container li .e-list-text')[4] as HTMLElement).innerText).toBe("811");
});
it('check 11', (done: Function) => {
let args: MouseEvent = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[1] as HTMLElement;
args = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("click", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
let searchOption: MaskedTextBox = fieldListObj.pivotCommon.filterDialog.editorSearch;
searchOption.setProperties({ value: '0' });
searchOption.change({ value: searchOption.value });
setTimeout(() => {
expect(document.querySelectorAll('.e-member-editor-container li').length).toBe(5);
expect(document.querySelectorAll('.e-select-all li .e-stop').length).toBe(1);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(1);
expect((document.querySelectorAll('.e-member-editor-container li .e-list-text')[4] as HTMLElement).innerText).toBe("40");
done();
}, 1000);
});
it('search 11', () => {
let searchOption: MaskedTextBox = fieldListObj.pivotCommon.filterDialog.editorSearch;
searchOption.setProperties({ value: '11' });
searchOption.change({ value: searchOption.value });
expect(document.querySelectorAll('.e-member-editor-container li').length).toBe(5);
expect(document.querySelectorAll('.e-select-all li .e-stop').length).toBe(1);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(1);
expect((document.querySelectorAll('.e-member-editor-container li .e-list-text')[4] as HTMLElement).innerText).toBe("811");
});
it('check all search 0', (done: Function) => {
let args: MouseEvent = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[0] as HTMLElement;
args = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("click", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
expect(document.querySelectorAll('.e-select-all li .e-check').length).toBe(1);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(5);
let searchOption: MaskedTextBox = fieldListObj.pivotCommon.filterDialog.editorSearch;
searchOption.setProperties({ value: '0' });
searchOption.change({ value: searchOption.value });
setTimeout(() => {
expect(document.querySelectorAll('.e-member-editor-container li').length).toBe(5);
expect(document.querySelectorAll('.e-select-all li .e-stop').length).toBe(1);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(1);
expect((document.querySelectorAll('.e-member-editor-container li .e-list-text')[4] as HTMLElement).innerText).toBe("40");
done();
}, 1000);
});
it('check all btn click', () => {
let args: MouseEvent = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
let firstNode: HTMLElement = document.querySelectorAll('.e-member-editor-container .e-checkbox-wrapper')[0] as HTMLElement;
args = new MouseEvent("mousedown", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("mouseup", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
args = new MouseEvent("click", { view: window, bubbles: true, cancelable: true });
firstNode.querySelector('.e-frame').dispatchEvent(args);
expect(document.querySelectorAll('.e-select-all li .e-check').length).toBe(1);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(5);
(document.querySelector('.e-ok-btn') as HTMLElement).click();
});
it('change mem limit to 10', (done: Function) => {
fieldListObj.maxNodeLimitInMemberEditor = 10;
let pivotButtons: HTMLElement[] =
[].slice.call(document.querySelector('.e-filters').querySelectorAll('.e-pivot-button'));
((pivotButtons[0]).querySelector('.e-btn-filter') as HTMLElement).click();
setTimeout(() => {
expect(document.querySelectorAll('.e-member-editor-container li').length).toBe(10);
expect(document.querySelectorAll('.e-select-all li .e-stop').length).toBe(1);
expect(document.querySelectorAll('.e-member-editor-container li .e-check').length).toBe(1);
done();
}, 1000);
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange);
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile());
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import { filter, List } from "../../../Data/List"
import { bindF, Just, mapMaybe, Maybe, Nothing } from "../../../Data/Maybe"
import { elems, find, lookupF, OrderedMap } from "../../../Data/OrderedMap"
import { Record } from "../../../Data/Record"
import { BlessedTradition, MagicalTradition } from "../../Constants/Groups"
import { SpecialAbilityId } from "../../Constants/Ids"
import { ActivatableDependent } from "../../Models/ActiveEntries/ActivatableDependent"
import { SpecialAbility } from "../../Models/Wiki/SpecialAbility"
import { pipe } from "../pipe"
import { isActive } from "./isActive"
const ADA = ActivatableDependent.A
/**
* Checks if an ID is a magical tradition's id.
*/
export const isMagicalTradId =
(tradition_id: string): boolean => {
switch (tradition_id) {
case SpecialAbilityId.TraditionGuildMages:
case SpecialAbilityId.TraditionWitches:
case SpecialAbilityId.TraditionElves:
case SpecialAbilityId.TraditionDruids:
case SpecialAbilityId.TraditionIllusionist:
case SpecialAbilityId.TraditionArcaneBard:
case SpecialAbilityId.TraditionArcaneDancer:
case SpecialAbilityId.TraditionIntuitiveMage:
case SpecialAbilityId.TraditionSavant:
case SpecialAbilityId.TraditionQabalyaMage:
case SpecialAbilityId.TraditionZauberalchimisten:
case SpecialAbilityId.TraditionKristallomanten:
case SpecialAbilityId.TraditionGeoden:
case SpecialAbilityId.TraditionSchelme:
case SpecialAbilityId.TraditionAnimisten:
case SpecialAbilityId.TraditionZibilijas:
case SpecialAbilityId.TraditionBrobimGeoden:
return true
default:
return false
}
}
/**
* Checks if an ID is a blessed tradition's id.
*/
export const isBlessedTradId =
(tradition_id: string): boolean => {
switch (tradition_id) {
case SpecialAbilityId.TraditionChurchOfPraios:
case SpecialAbilityId.TraditionChurchOfRondra:
case SpecialAbilityId.TraditionChurchOfBoron:
case SpecialAbilityId.TraditionChurchOfHesinde:
case SpecialAbilityId.TraditionChurchOfPhex:
case SpecialAbilityId.TraditionChurchOfPeraine:
case SpecialAbilityId.TraditionChurchOfEfferd:
case SpecialAbilityId.TraditionChurchOfTravia:
case SpecialAbilityId.TraditionChurchOfFirun:
case SpecialAbilityId.TraditionChurchOfTsa:
case SpecialAbilityId.TraditionChurchOfIngerimm:
case SpecialAbilityId.TraditionChurchOfRahja:
case SpecialAbilityId.TraditionCultOfTheNamelessOne:
case SpecialAbilityId.TraditionChurchOfAves:
case SpecialAbilityId.TraditionChurchOfIfirn:
case SpecialAbilityId.TraditionChurchOfKor:
case SpecialAbilityId.TraditionChurchOfNandus:
case SpecialAbilityId.TraditionChurchOfSwafnir:
case SpecialAbilityId.TraditionCultOfNuminoru:
return true
default:
return false
}
}
const isActiveMagicalTradition =
(e: Record<ActivatableDependent>) => isMagicalTradId (ADA.id (e)) && isActive (e)
const isActiveBlessedTradition =
(e: Record<ActivatableDependent>) => isBlessedTradId (ADA.id (e)) && isActive (e)
/**
* Get magical traditions' dependent entries.
* @param list
*/
export const getMagicalTraditionsHeroEntries =
pipe (
elems as
(list: OrderedMap<any, Record<ActivatableDependent>>) => List<Record<ActivatableDependent>>,
filter (isActiveMagicalTradition)
)
/**
* Get magical traditions' wiki entries.
* @param wiki
* @param list
*/
export const getMagicalTraditionsFromWiki =
(wiki: OrderedMap<string, Record<SpecialAbility>>) =>
pipe (getMagicalTraditionsHeroEntries, mapMaybe (pipe (ADA.id, lookupF (wiki))))
/**
* Get blessed traditions' dependent entry.
* @param list
*/
export const getBlessedTradition = find (isActiveBlessedTradition)
/**
* Get blessed tradition's' wiki entry.
* @param wiki
* @param list
*/
export const getBlessedTraditionFromWiki =
(wiki: OrderedMap<string, Record<SpecialAbility>>) =>
pipe (getBlessedTradition, bindF (pipe (ADA.id, lookupF (wiki))))
/**
* Map a magical tradition's ID to a numeric magical tradition ID used by
* spells.
*
* *Note: Zauberalchimisten do not get spells and thus do not have a numeric
* magical tradition ID.*
*/
export const mapMagicalTradIdToNumId =
(tradition_id: string): Maybe<MagicalTradition> => {
switch (tradition_id) {
case SpecialAbilityId.TraditionGuildMages:
return Just (MagicalTradition.GuildMages)
case SpecialAbilityId.TraditionWitches:
return Just (MagicalTradition.Witches)
case SpecialAbilityId.TraditionElves:
return Just (MagicalTradition.Elves)
case SpecialAbilityId.TraditionDruids:
return Just (MagicalTradition.Druids)
case SpecialAbilityId.TraditionIllusionist:
return Just (MagicalTradition.Scharlatane)
case SpecialAbilityId.TraditionArcaneBard:
return Just (MagicalTradition.ArcaneBards)
case SpecialAbilityId.TraditionArcaneDancer:
return Just (MagicalTradition.ArcaneDancers)
case SpecialAbilityId.TraditionIntuitiveMage:
return Just (MagicalTradition.IntuitiveZauberer)
case SpecialAbilityId.TraditionSavant:
return Just (MagicalTradition.Meistertalentierte)
case SpecialAbilityId.TraditionQabalyaMage:
return Just (MagicalTradition.Qabalyamagier)
case SpecialAbilityId.TraditionKristallomanten:
return Just (MagicalTradition.Kristallomanten)
case SpecialAbilityId.TraditionGeoden:
return Just (MagicalTradition.Geodes)
case SpecialAbilityId.TraditionSchelme:
return Just (MagicalTradition.Rogues)
case SpecialAbilityId.TraditionAnimisten:
return Just (MagicalTradition.Animists)
case SpecialAbilityId.TraditionZibilijas:
return Just (MagicalTradition.Zibilija)
case SpecialAbilityId.TraditionBrobimGeoden:
return Just (MagicalTradition.BrobimGeoden)
default:
return Nothing
}
}
/**
* Map a numeric magical tradition ID used by spells to a magical tradition's
* ID.
*/
export const mapMagicalNumIdToTradId =
(tradition_id: MagicalTradition): Maybe<SpecialAbilityId> => {
switch (tradition_id) {
case MagicalTradition.GuildMages:
return Just (SpecialAbilityId.TraditionGuildMages)
case MagicalTradition.Witches:
return Just (SpecialAbilityId.TraditionWitches)
case MagicalTradition.Elves:
return Just (SpecialAbilityId.TraditionElves)
case MagicalTradition.Druids:
return Just (SpecialAbilityId.TraditionDruids)
case MagicalTradition.Scharlatane:
return Just (SpecialAbilityId.TraditionIllusionist)
case MagicalTradition.ArcaneBards:
return Just (SpecialAbilityId.TraditionArcaneBard)
case MagicalTradition.ArcaneDancers:
return Just (SpecialAbilityId.TraditionArcaneDancer)
case MagicalTradition.IntuitiveZauberer:
return Just (SpecialAbilityId.TraditionIntuitiveMage)
case MagicalTradition.Meistertalentierte:
return Just (SpecialAbilityId.TraditionSavant)
case MagicalTradition.Qabalyamagier:
return Just (SpecialAbilityId.TraditionQabalyaMage)
case MagicalTradition.Kristallomanten:
return Just (SpecialAbilityId.TraditionKristallomanten)
case MagicalTradition.Geodes:
return Just (SpecialAbilityId.TraditionGeoden)
case MagicalTradition.Rogues:
return Just (SpecialAbilityId.TraditionSchelme)
case MagicalTradition.Animists:
return Just (SpecialAbilityId.TraditionAnimisten)
case MagicalTradition.Zibilija:
return Just (SpecialAbilityId.TraditionZibilijas)
case MagicalTradition.BrobimGeoden:
return Just (SpecialAbilityId.TraditionBrobimGeoden)
default:
return Nothing
}
}
/**
* Map a blessed tradition's ID to a numeric blessed tradition ID used by
* chants.
*/
export const mapBlessedTradIdToNumId =
(tradition_id: string): Maybe<BlessedTradition> => {
switch (tradition_id) {
case SpecialAbilityId.TraditionChurchOfPraios:
return Just (BlessedTradition.ChurchOfPraios)
case SpecialAbilityId.TraditionChurchOfRondra:
return Just (BlessedTradition.ChurchOfRondra)
case SpecialAbilityId.TraditionChurchOfBoron:
return Just (BlessedTradition.ChurchOfBoron)
case SpecialAbilityId.TraditionChurchOfHesinde:
return Just (BlessedTradition.ChurchOfHesinde)
case SpecialAbilityId.TraditionChurchOfPhex:
return Just (BlessedTradition.ChurchOfPhex)
case SpecialAbilityId.TraditionChurchOfPeraine:
return Just (BlessedTradition.ChurchOfPeraine)
case SpecialAbilityId.TraditionChurchOfEfferd:
return Just (BlessedTradition.ChurchOfEfferd)
case SpecialAbilityId.TraditionChurchOfTravia:
return Just (BlessedTradition.ChurchOfTravia)
case SpecialAbilityId.TraditionChurchOfFirun:
return Just (BlessedTradition.ChurchOfFirun)
case SpecialAbilityId.TraditionChurchOfTsa:
return Just (BlessedTradition.ChurchOfTsa)
case SpecialAbilityId.TraditionChurchOfIngerimm:
return Just (BlessedTradition.ChurchOfIngerimm)
case SpecialAbilityId.TraditionChurchOfRahja:
return Just (BlessedTradition.ChurchOfRahja)
case SpecialAbilityId.TraditionCultOfTheNamelessOne:
return Just (BlessedTradition.CultOfTheNamelessOne)
case SpecialAbilityId.TraditionChurchOfAves:
return Just (BlessedTradition.ChurchOfAves)
case SpecialAbilityId.TraditionChurchOfIfirn:
return Just (BlessedTradition.ChurchOfIfirn)
case SpecialAbilityId.TraditionChurchOfKor:
return Just (BlessedTradition.ChurchOfKor)
case SpecialAbilityId.TraditionChurchOfNandus:
return Just (BlessedTradition.ChurchOfNandus)
case SpecialAbilityId.TraditionChurchOfSwafnir:
return Just (BlessedTradition.ChurchOfSwafnir)
case SpecialAbilityId.TraditionCultOfNuminoru:
return Just (BlessedTradition.CultOfNuminoru)
default:
return Nothing
}
}
/**
* Map a blessed tradition's ID to a numeric blessed tradition ID used by
* chants.
*/
export const mapBlessedNumIdToTradId =
(tradition_id: BlessedTradition): Maybe<SpecialAbilityId> => {
switch (tradition_id) {
case BlessedTradition.ChurchOfPraios:
return Just (SpecialAbilityId.TraditionChurchOfPraios)
case BlessedTradition.ChurchOfRondra:
return Just (SpecialAbilityId.TraditionChurchOfRondra)
case BlessedTradition.ChurchOfBoron:
return Just (SpecialAbilityId.TraditionChurchOfBoron)
case BlessedTradition.ChurchOfHesinde:
return Just (SpecialAbilityId.TraditionChurchOfHesinde)
case BlessedTradition.ChurchOfPhex:
return Just (SpecialAbilityId.TraditionChurchOfPhex)
case BlessedTradition.ChurchOfPeraine:
return Just (SpecialAbilityId.TraditionChurchOfPeraine)
case BlessedTradition.ChurchOfEfferd:
return Just (SpecialAbilityId.TraditionChurchOfEfferd)
case BlessedTradition.ChurchOfTravia:
return Just (SpecialAbilityId.TraditionChurchOfTravia)
case BlessedTradition.ChurchOfFirun:
return Just (SpecialAbilityId.TraditionChurchOfFirun)
case BlessedTradition.ChurchOfTsa:
return Just (SpecialAbilityId.TraditionChurchOfTsa)
case BlessedTradition.ChurchOfIngerimm:
return Just (SpecialAbilityId.TraditionChurchOfIngerimm)
case BlessedTradition.ChurchOfRahja:
return Just (SpecialAbilityId.TraditionChurchOfRahja)
case BlessedTradition.CultOfTheNamelessOne:
return Just (SpecialAbilityId.TraditionCultOfTheNamelessOne)
case BlessedTradition.ChurchOfAves:
return Just (SpecialAbilityId.TraditionChurchOfAves)
case BlessedTradition.ChurchOfIfirn:
return Just (SpecialAbilityId.TraditionChurchOfIfirn)
case BlessedTradition.ChurchOfKor:
return Just (SpecialAbilityId.TraditionChurchOfKor)
case BlessedTradition.ChurchOfNandus:
return Just (SpecialAbilityId.TraditionChurchOfNandus)
case BlessedTradition.ChurchOfSwafnir:
return Just (SpecialAbilityId.TraditionChurchOfSwafnir)
case BlessedTradition.CultOfNuminoru:
return Just (SpecialAbilityId.TraditionCultOfNuminoru)
default:
return Nothing
}
} | the_stack |
export default {
'activityBar.activeBorder': '#54bef2',
'activityBar.background': '#111720',
'activityBar.border': '#111720',
'activityBar.foreground': '#cacde2',
'activityBarBadge.background': '#54bef2',
'activityBarBadge.foreground': '#00111a',
'badge.background': '#54bef2',
'badge.foreground': '#00111a',
'breadcrumb.activeSelectionForeground': '#54bef2',
'breadcrumb.background': '#111720',
'breadcrumb.focusForeground': '#cacde2',
'breadcrumb.foreground': '#7e8995',
'breadcrumbPicker.background': '#111720',
'button.background': '#54bef2',
'button.border': '#111720',
'button.foreground': '#00111a',
'button.hoverBackground': '#67e8f9',
'button.secondaryBackground': '#00111a50',
'button.secondaryForeground': '#d2d8e7',
'button.secondaryHoverBackground': '#00111a',
'charts.blue': '#54bef2',
'charts.foreground': '#cacde2',
'charts.green': '#82f1b1',
'charts.orange': '#ff9c66',
'charts.purple': '#c792ea',
'charts.red': '#fb7185',
'charts.yellow': '#ffcb6b',
'debugConsole.errorForeground': '#fb7185',
'debugConsole.infoForeground': '#cacde2',
'debugConsole.sourceForeground': '#54bef2',
'debugConsole.warningForeground': '#ffcb6b',
'debugConsoleInputIcon.foreground': '#54bef2',
'debugToolBar.background': '#111720',
descriptionForeground: '#cacde2cc',
'diffEditor.insertedTextBackground': '#82f1b120',
'diffEditor.removedTextBackground': '#fb718560',
'dropdown.background': '#111720',
'dropdown.border': '#cacde210',
'editor.background': '#111720',
'editor.findMatchBackground': '#cacde240',
'editor.findMatchBorder': '#54bef2',
'editor.findMatchHighlightBackground': '#54bef260',
'editor.findMatchHighlightBorder': '#cacde210',
'editor.foreground': '#cacde2',
'editor.lineHighlightBackground': '#00111a50',
'editor.selectionBackground': '#54bef240',
'editor.selectionHighlightBackground': '#ffcb6b30',
'editorBracketMatch.background': '#00111a50',
'editorBracketMatch.border': '#54bef240',
'editorCodeLens.foreground': '#7e8995',
'editorCursor.foreground': '#ffcb6b',
'editorError.foreground': '#fb718540',
'editorGroup.border': '#111720',
'editorGroupHeader.tabsBackground': '#111720',
'editorGutter.addedBackground': '#82f1b140',
'editorGutter.deletedBackground': '#fb718540',
'editorGutter.modifiedBackground': '#54bef240',
'editorHoverWidget.background': '#111720',
'editorHoverWidget.border': '#cacde210',
'editorIndentGuide.activeBackground': '#5c6270',
'editorIndentGuide.background': '#7e899540',
'editorInfo.foreground': '#54bef240',
'editorInlayHint.background': '#2c313c',
'editorInlayHint.foreground': '#abb2bf',
'editorLineNumber.activeForeground': '#7e8995',
'editorLineNumber.foreground': '#5c6270',
'editorLink.activeForeground': '#d2d8e7',
'editorMarkerNavigation.background': '#54bef210',
'editorOverviewRuler.addedForeground': '#82f1b1',
'editorOverviewRuler.background': '#111720',
'editorOverviewRuler.border': '#111720',
'editorOverviewRuler.currentContentForeground': '#ffcb6b60',
'editorOverviewRuler.deletedForeground': '#fb7185',
'editorOverviewRuler.errorForeground': '#fb7185',
'editorOverviewRuler.findMatchForeground': '#67e8f9',
'editorOverviewRuler.incomingContentForeground': '#ffcb6b60',
'editorOverviewRuler.infoForeground': '#54bef2',
'editorOverviewRuler.modifiedForeground': '#ffcb6b',
'editorOverviewRuler.rangeHighlightForeground': '#67e8f930',
'editorOverviewRuler.selectionHighlightForeground': '#67e8f930',
'editorOverviewRuler.warningForeground': '#ffcb6b',
'editorOverviewRuler.wordHighlightForeground': '#ffcb6b30',
'editorOverviewRuler.wordHighlightStrongForeground': '#ffcb6b60',
'editorRuler.foreground': '#7e8995',
'editorSuggestWidget.background': '#111720',
'editorSuggestWidget.border': '#cacde210',
'editorSuggestWidget.focusHighlightForeground': '#54bef2',
'editorSuggestWidget.foreground': '#d2d8e7',
'editorSuggestWidget.highlightForeground': '#54bef2',
'editorSuggestWidget.selectedBackground': '#111720',
'editorSuggestWidget.selectedForeground': '#cacde2',
'editorWarning.foreground': '#ffcb6b40',
'editorWhitespace.foreground': '#cacde240',
'editorWidget.background': '#111720',
'editorWidget.border': '#54bef2',
'editorWidget.resizeBorder': '#54bef2',
'extensionButton.prominentBackground': '#54bef2cc',
'extensionButton.prominentHoverBackground': '#54bef2',
focusBorder: '#11172000',
foreground: '#cacde2',
'gitDecoration.conflictingResourceForeground': '#ffcb6bcc',
'gitDecoration.deletedResourceForeground': '#fb7185cc',
'gitDecoration.ignoredResourceForeground': '#5c6270',
'gitDecoration.modifiedResourceForeground': '#ffcb6bcc',
'gitDecoration.submoduleResourceForeground': '#c792eacc',
'gitDecoration.untrackedResourceForeground': '#82f1b1cc',
'gitlens.closedPullRequestIconColor': '#fb7185',
'gitlens.decorations.branchAheadForegroundColor': '#82f1b1',
'gitlens.decorations.branchBehindForegroundColor': '#ffcb6b',
'gitlens.decorations.branchDivergedForegroundColor': '#ff9c66',
'gitlens.decorations.branchMissingUpstreamForegroundColor': '#fb7185',
'gitlens.decorations.branchUnpublishedForegroundColor': '#82f1b1',
'gitlens.gutterBackgroundColor': '#00111a60',
'gitlens.gutterForegroundColor': '#cacde2',
'gitlens.gutterUncommittedForegroundColor': '#5c6270',
'gitlens.lineHighlightBackgroundColor': '#00111a60',
'gitlens.lineHighlightOverviewRulerColor': '#cacde2',
'gitlens.mergedPullRequestIconColor': '#c792ea',
'gitlens.openPullRequestIconColor': '#82f1b1',
'gitlens.trailingLineBackgroundColor': '#00111a50',
'gitlens.trailingLineForegroundColor': '#cacde240',
'gitlens.unpublishedCommitIconColor': '#82f1b1',
'gitlens.unpulledChangesIconColor': '#ffcb6b',
'gitlens.unpushlishedChangesIconColor': '#82f1b1',
'icon.foreground': '#cacde2',
'input.background': '#00111a50',
'input.border': '#111720',
'input.foreground': '#d2d8e7',
'input.placeholderForeground': '#cacde240',
'inputOption.activeBackground': '#00111a60',
'inputOption.activeBorder': '#cacde210',
'inputValidation.errorBorder': '#fb718540',
'inputValidation.infoBorder': '#54bef240',
'inputValidation.warningBorder': '#ffcb6b40',
'keybindingLabel.background': '#00111a50',
'keybindingLabel.border': '#5c6270cc',
'keybindingLabel.bottomBorder': '#7e8995cc',
'keybindingLabel.foreground': '#d2d8e7',
'list.activeSelectionBackground': '#7e899560',
'list.activeSelectionForeground': '#ffffff',
'list.activeSelectionIconForeground': '#ffffff',
'list.dropBackground': '#00111a50',
'list.focusBackground': '#54bef220',
'list.focusForeground': '#ffffff',
'list.focusHighlightForeground': '#ffffff',
'list.highlightForeground': '#d2d8e7',
'list.hoverBackground': '#00111a50',
'list.hoverForeground': '#d2d8e7',
'list.inactiveSelectionBackground': '#111720',
'list.inactiveSelectionForeground': '#54bef2',
'listFilterWidget.background': '#111720',
'listFilterWidget.noMatchesOutline': '#cacde210',
'listFilterWidget.outline': '#cacde210',
'menu.background': '#111720',
'menu.foreground': '#d2d8e7',
'menu.selectionBackground': '#111720',
'menu.selectionForeground': '#54bef2',
'menu.separatorBackground': '#d2d8e7',
'menubar.selectionBackground': '#111720',
'menubar.selectionForeground': '#54bef2',
'notificationCenterHeader.background': '#111720',
'notificationCenterHeader.foreground': '#d2d8e7',
'notificationLink.foreground': '#c792ea',
'notifications.background': '#111720',
'notifications.foreground': '#d2d8e7',
'notificationsErrorIcon.foreground': '#fb7185',
'notificationsInfoIcon.foreground': '#00111a50',
'notificationsWarningIcon.foreground': '#ffcb6b',
'panel.background': '#111720',
'panel.border': '#111720',
'panel.dropBorder': '#c792ea',
'panelTitle.activeBorder': '#54bef2',
'panelTitle.activeForeground': '#ffffff',
'panelTitle.inactiveForeground': '#7e8995',
'peekView.border': '#cacde210',
'peekViewEditor.background': '#c792ea10',
'peekViewEditor.matchHighlightBackground': '#54bef240',
'peekViewEditorGutter.background': '#c792ea10',
'peekViewResult.background': '#c792ea10',
'peekViewResult.matchHighlightBackground': '#54bef240',
'peekViewResult.selectionBackground': '#7e899540',
'peekViewTitle.background': '#c792ea10',
'peekViewTitleDescription.foreground': '#cacde240',
'pickerGroup.foreground': '#54bef2',
'progressBar.background': '#54bef2',
'scrollbar.shadow': '#11172000',
'scrollbarSlider.activeBackground': '#54bef240',
'scrollbarSlider.background': '#54bef230',
'scrollbarSlider.hoverBackground': '#111720',
'selection.background': '#54bef240',
'settings.checkboxBackground': '#111720',
'settings.checkboxForeground': '#cacde2',
'settings.dropdownBackground': '#111720',
'settings.dropdownForeground': '#cacde2',
'settings.headerForeground': '#54bef2',
'settings.modifiedItemIndicator': '#54bef2',
'settings.numberInputBackground': '#111720',
'settings.numberInputForeground': '#cacde2',
'settings.textInputBackground': '#111720',
'settings.textInputForeground': '#cacde2',
'sideBar.background': '#111720',
'sideBar.border': '#111720',
'sideBar.foreground': '#7e8995',
'sideBarSectionHeader.background': '#111720',
'sideBarSectionHeader.border': '#111720',
'sideBarTitle.foreground': '#cacde2',
'statusBar.background': '#111720',
'statusBar.border': '#111720',
'statusBar.debuggingBackground': '#54bef2',
'statusBar.debuggingForeground': '#00111a',
'statusBar.foreground': '#7e8995',
'statusBar.noFolderBackground': '#111720',
'statusBarItem.hoverBackground': '#00111a50',
'statusBarItem.prominentForeground': '#00111a',
'statusBarItem.remoteBackground': '#54bef2',
'statusBarItem.remoteForeground': '#00111a',
'tab.activeBorder': '#d19a66',
'tab.activeForeground': '#cacde2',
'tab.activeModifiedBorder': '#7e8995',
'tab.border': '#111720',
'tab.inactiveBackground': '#111720',
'tab.inactiveForeground': '#7e8995',
'tab.unfocusedActiveBorder': '#7e8995',
'tab.unfocusedActiveForeground': '#cacde2',
'terminal.ansiBlack': '#5c6270',
'terminal.ansiBlue': '#54bef2',
'terminal.ansiBrightBlack': '#7e8995',
'terminal.ansiBrightBlue': '#54bef2',
'terminal.ansiBrightCyan': '#67e8f9',
'terminal.ansiBrightGreen': '#82f1b1',
'terminal.ansiBrightMagenta': '#c792ea',
'terminal.ansiBrightRed': '#fb7185',
'terminal.ansiBrightWhite': '#ffffff',
'terminal.ansiBrightYellow': '#ffcb6b',
'terminal.ansiCyan': '#67e8f9',
'terminal.ansiGreen': '#82f1b1',
'terminal.ansiMagenta': '#c792ea',
'terminal.ansiRed': '#fb7185',
'terminal.ansiWhite': '#ffffff',
'terminal.ansiYellow': '#ffcb6b',
'terminalCursor.background': '#00111a',
'terminalCursor.foreground': '#cacde2',
'textCodeBlock.background': '#7e8995',
'textLink.activeForeground': '#54bef2',
'textLink.foreground': '#54bef2',
'textPreformat.foreground': '#7e8995',
'titleBar.activeBackground': '#111720',
'titleBar.activeForeground': '#d2d8e7',
'titleBar.border': '#111720',
'titleBar.inactiveBackground': '#111720',
'titleBar.inactiveForeground': '#7e8995',
'toolbar.hoverBackground': '#00111a50',
'widget.shadow': '#00111a10',
//"activityBar.dropBorder": "#cacde2",
//"activityBar.inactiveForeground": "#cacde266",
//"banner.background": "#7e899560",
//"banner.foreground": "#ffffff",
//"banner.iconForeground": "#54bef240",
//"charts.lines": "#cacde280",
//"checkbox.background": "#111720",
//"checkbox.border": "#cacde210",
//"checkbox.foreground": "#f0f0f0",
//"debugExceptionWidget.background": "#420b0d",
//"debugExceptionWidget.border": "#a31515",
//"debugIcon.breakpointCurrentStackframeForeground": "#ffcc00",
//"debugIcon.breakpointDisabledForeground": "#848484",
//"debugIcon.breakpointForeground": "#e51400",
//"debugIcon.breakpointStackframeForeground": "#89d185",
//"debugIcon.breakpointUnverifiedForeground": "#848484",
//"debugIcon.continueForeground": "#75beff",
//"debugIcon.disconnectForeground": "#f48771",
//"debugIcon.pauseForeground": "#75beff",
//"debugIcon.restartForeground": "#89d185",
//"debugIcon.startForeground": "#89d185",
//"debugIcon.stepBackForeground": "#75beff",
//"debugIcon.stepIntoForeground": "#75beff",
//"debugIcon.stepOutForeground": "#75beff",
//"debugIcon.stepOverForeground": "#75beff",
//"debugIcon.stopForeground": "#f48771",
//"debugTokenExpression.boolean": "#4e94ce",
//"debugTokenExpression.error": "#f48771",
//"debugTokenExpression.name": "#c586c0",
//"debugTokenExpression.number": "#b5cea8",
//"debugTokenExpression.string": "#ce9178",
//"debugTokenExpression.value": "#cccccc99",
//"debugView.exceptionLabelBackground": "#6c2022",
//"debugView.exceptionLabelForeground": "#cacde2",
//"debugView.stateLabelBackground": "#88888844",
//"debugView.stateLabelForeground": "#cacde2",
//"debugView.valueChangedHighlight": "#569cd6",
//"diffEditor.diagonalFill": "#cccccc33",
//"dropdown.foreground": "#f0f0f0",
//"editor.findRangeHighlightBackground": "#3a3d4166",
//"editor.focusedStackFrameHighlightBackground": "#7abd7a4d",
//"editor.foldBackground": "#54bef213",
//"editor.hoverHighlightBackground": "#264f7840",
//"editor.inactiveSelectionBackground": "#54bef220",
//"editor.inlineValuesBackground": "#ffc80033",
//"editor.inlineValuesForeground": "#ffffff80",
//"editor.lineHighlightBorder": "#282828",
//"editor.linkedEditingBackground": "#ff00004d",
//"editor.rangeHighlightBackground": "#ffffff0b",
//"editor.snippetFinalTabstopHighlightBorder": "#525252",
//"editor.snippetTabstopHighlightBackground": "#7c7c7c4d",
//"editor.stackFrameHighlightBackground": "#ffff0033",
//"editor.symbolHighlightBackground": "#54bef260",
//"editor.wordHighlightBackground": "#575757b8",
//"editor.wordHighlightStrongBackground": "#004972b8",
//"editorActiveLineNumber.foreground": "#c6c6c6",
//"editorBracketHighlight.foreground1": "#ffd700",
//"editorBracketHighlight.foreground2": "#da70d6",
//"editorBracketHighlight.foreground3": "#179fff",
//"editorBracketHighlight.foreground4": "#00000000",
//"editorBracketHighlight.foreground5": "#00000000",
//"editorBracketHighlight.foreground6": "#00000000",
//"editorBracketHighlight.unexpectedBracket.foreground": "#ff1212cc",
//"editorGhostText.foreground": "#ffffff56",
//"editorGroup.dropBackground": "#53595d80",
//"editorGroupHeader.noTabsBackground": "#111720",
//"editorGutter.background": "#111720",
//"editorGutter.commentRangeForeground": "#c5c5c5",
//"editorGutter.foldingControlForeground": "#cacde2",
//"editorHint.foreground": "#eeeeeeb3",
//"editorHoverWidget.foreground": "#cacde2",
//"editorHoverWidget.statusBarBackground": "#141c26",
//"editorLightBulb.foreground": "#ffcc00",
//"editorLightBulbAutoFix.foreground": "#75beff",
//"editorMarkerNavigationError.background": "#fb718540",
//"editorMarkerNavigationError.headerBackground": "#fb718506",
//"editorMarkerNavigationInfo.background": "#54bef240",
//"editorMarkerNavigationInfo.headerBackground": "#54bef206",
//"editorMarkerNavigationWarning.background": "#ffcb6b40",
//"editorMarkerNavigationWarning.headerBackground": "#ffcb6b06",
//"editorOverviewRuler.bracketMatchForeground": "#a0a0a0",
//"editorOverviewRuler.commonContentForeground": "#60606066",
//"editorPane.background": "#111720",
//"editorSuggestWidget.selectedIconForeground": "#ffffff",
//"editorUnnecessaryCode.opacity": "#000000aa",
//"editorWidget.foreground": "#cacde2",
//"errorForeground": "#f48771",
//"extensionBadge.remoteBackground": "#54bef2",
//"extensionBadge.remoteForeground": "#00111a",
//"extensionButton.prominentForeground": "#00111a",
//"extensionIcon.starForeground": "#ff8e00",
//"gitDecoration.addedResourceForeground": "#81b88b",
//"gitDecoration.renamedResourceForeground": "#73c991",
//"gitDecoration.stageDeletedResourceForeground": "#c74e39",
//"gitDecoration.stageModifiedResourceForeground": "#e2c08d",
//"gitlens.decorations.addedForegroundColor": "#81b88b",
//"gitlens.decorations.branchUpToDateForegroundColor": "#7e8995",
//"gitlens.decorations.copiedForegroundColor": "#73c991",
//"gitlens.decorations.deletedForegroundColor": "#fb7185cc",
//"gitlens.decorations.ignoredForegroundColor": "#5c6270",
//"gitlens.decorations.modifiedForegroundColor": "#ffcb6bcc",
//"gitlens.decorations.renamedForegroundColor": "#73c991",
//"gitlens.decorations.untrackedForegroundColor": "#82f1b1cc",
//"inputOption.activeForeground": "#ffffff",
//"inputValidation.errorBackground": "#5a1d1d",
//"inputValidation.infoBackground": "#063b49",
//"inputValidation.warningBackground": "#352a05",
//"interactive.activeCodeBorder": "#cacde210",
//"interactive.inactiveCodeBorder": "#111720",
//"list.deemphasizedForeground": "#8c8c8c",
//"list.errorForeground": "#f88070",
//"list.filterMatchBackground": "#54bef260",
//"list.filterMatchBorder": "#cacde210",
//"list.focusOutline": "#11172000",
//"list.invalidItemForeground": "#b89500",
//"list.warningForeground": "#cca700",
//"merge.commonContentBackground": "#60606029",
//"merge.commonHeaderBackground": "#60606066",
//"merge.currentContentBackground": "#40c8ae33",
//"merge.currentHeaderBackground": "#40c8ae80",
//"merge.incomingContentBackground": "#40a6ff33",
//"merge.incomingHeaderBackground": "#40a6ff80",
//"minimap.errorHighlight": "#ff1212b3",
//"minimap.findMatchHighlight": "#d18616",
//"minimap.selectionHighlight": "#264f78",
//"minimap.warningHighlight": "#ffcb6b40",
//"minimapGutter.addedBackground": "#587c0c",
//"minimapGutter.deletedBackground": "#94151b",
//"minimapGutter.modifiedBackground": "#0c7d9d",
//"minimapSlider.activeBackground": "#54bef220",
//"minimapSlider.background": "#54bef218",
//"minimapSlider.hoverBackground": "#11172080",
//"notebook.cellBorderColor": "#111720",
//"notebook.cellEditorBackground": "#cacde20a",
//"notebook.cellInsertionIndicator": "#11172000",
//"notebook.cellStatusBarItemHoverBackground": "#ffffff26",
//"notebook.cellToolbarSeparator": "#80808059",
//"notebook.focusedCellBorder": "#11172000",
//"notebook.focusedEditorBorder": "#11172000",
//"notebook.inactiveFocusedCellBorder": "#111720",
//"notebook.selectedCellBackground": "#111720",
//"notebook.selectedCellBorder": "#111720",
//"notebook.symbolHighlightBackground": "#ffffff0b",
//"notebookScrollbarSlider.activeBackground": "#54bef240",
//"notebookScrollbarSlider.background": "#54bef230",
//"notebookScrollbarSlider.hoverBackground": "#111720",
//"notebookStatusErrorIcon.foreground": "#f48771",
//"notebookStatusRunningIcon.foreground": "#cacde2",
//"notebookStatusSuccessIcon.foreground": "#89d185",
//"notifications.border": "#111720",
//"panelSection.border": "#111720",
//"panelSection.dropBackground": "#53595d80",
//"panelSectionHeader.background": "#80808033",
//"peekViewResult.fileForeground": "#ffffff",
//"peekViewResult.lineForeground": "#bbbbbb",
//"peekViewResult.selectionForeground": "#ffffff",
//"peekViewTitleLabel.foreground": "#ffffff",
//"pickerGroup.border": "#3f3f46",
//"ports.iconRunningProcessForeground": "#54bef2",
//"problemsErrorIcon.foreground": "#fb718540",
//"problemsInfoIcon.foreground": "#54bef240",
//"problemsWarningIcon.foreground": "#ffcb6b40",
//"quickInput.background": "#111720",
//"quickInput.foreground": "#cacde2",
//"quickInputList.focusBackground": "#7e899560",
//"quickInputList.focusForeground": "#ffffff",
//"quickInputList.focusIconForeground": "#ffffff",
//"quickInputTitle.background": "#ffffff1b",
//"rust_analyzer.inlayHints.background": "#11223300",
//"rust_analyzer.inlayHints.background.chainingHints": "#11223300",
//"rust_analyzer.inlayHints.background.parameterHints": "#11223300",
//"rust_analyzer.inlayHints.background.typeHints": "#11223300",
//"rust_analyzer.inlayHints.foreground": "#a0a0a0f0",
//"rust_analyzer.inlayHints.foreground.chainingHints": "#a0a0a0f0",
//"rust_analyzer.inlayHints.foreground.parameterHints": "#a0a0a0f0",
//"rust_analyzer.inlayHints.foreground.typeHints": "#a0a0a0f0",
//"rust_analyzer.syntaxTreeBorder": "#ffffff",
//"sash.hoverBorder": "#11172000",
//"scm.providerBorder": "#454545",
//"searchEditor.findMatchBackground": "#54bef23f",
//"searchEditor.findMatchBorder": "#cacde20b",
//"searchEditor.textInputBorder": "#111720",
//"settings.checkboxBorder": "#cacde210",
//"settings.dropdownBorder": "#cacde210",
//"settings.dropdownListBorder": "#54bef2",
//"settings.focusedRowBackground": "#80808024",
//"settings.focusedRowBorder": "#ffffff1f",
//"settings.numberInputBorder": "#111720",
//"settings.rowHoverBackground": "#80808012",
//"settings.textInputBorder": "#111720",
//"sideBar.dropBackground": "#53595d80",
//"sideBarSectionHeader.foreground": "#7e8995",
//"statusBar.debuggingBorder": "#111720",
//"statusBar.noFolderBorder": "#111720",
//"statusBar.noFolderForeground": "#7e8995",
//"statusBarItem.activeBackground": "#ffffff2e",
//"statusBarItem.errorBackground": "#c72e0f",
//"statusBarItem.errorForeground": "#ffffff",
//"statusBarItem.prominentBackground": "#00000080",
//"statusBarItem.prominentHoverBackground": "#0000004d",
//"statusBarItem.warningBackground": "#d98d0040",
//"statusBarItem.warningForeground": "#ffffff",
//"symbolIcon.arrayForeground": "#cacde2",
//"symbolIcon.booleanForeground": "#cacde2",
//"symbolIcon.classForeground": "#ee9d28",
//"symbolIcon.colorForeground": "#cacde2",
//"symbolIcon.constantForeground": "#cacde2",
//"symbolIcon.constructorForeground": "#b180d7",
//"symbolIcon.enumeratorForeground": "#ee9d28",
//"symbolIcon.enumeratorMemberForeground": "#75beff",
//"symbolIcon.eventForeground": "#ee9d28",
//"symbolIcon.fieldForeground": "#75beff",
//"symbolIcon.fileForeground": "#cacde2",
//"symbolIcon.folderForeground": "#cacde2",
//"symbolIcon.functionForeground": "#b180d7",
//"symbolIcon.interfaceForeground": "#75beff",
//"symbolIcon.keyForeground": "#cacde2",
//"symbolIcon.keywordForeground": "#cacde2",
//"symbolIcon.methodForeground": "#b180d7",
//"symbolIcon.moduleForeground": "#cacde2",
//"symbolIcon.namespaceForeground": "#cacde2",
//"symbolIcon.nullForeground": "#cacde2",
//"symbolIcon.numberForeground": "#cacde2",
//"symbolIcon.objectForeground": "#cacde2",
//"symbolIcon.operatorForeground": "#cacde2",
//"symbolIcon.packageForeground": "#cacde2",
//"symbolIcon.propertyForeground": "#cacde2",
//"symbolIcon.referenceForeground": "#cacde2",
//"symbolIcon.snippetForeground": "#cacde2",
//"symbolIcon.stringForeground": "#cacde2",
//"symbolIcon.structForeground": "#cacde2",
//"symbolIcon.textForeground": "#cacde2",
//"symbolIcon.typeParameterForeground": "#cacde2",
//"symbolIcon.unitForeground": "#cacde2",
//"symbolIcon.variableForeground": "#75beff",
//"tab.activeBackground": "#111720",
//"tab.inactiveModifiedBorder": "#7e899580",
//"tab.lastPinnedBorder": "#585858",
//"tab.unfocusedActiveBackground": "#111720",
//"tab.unfocusedActiveModifiedBorder": "#7e899580",
//"tab.unfocusedInactiveBackground": "#111720",
//"tab.unfocusedInactiveForeground": "#7e899580",
//"tab.unfocusedInactiveModifiedBorder": "#7e899540",
//"terminal.border": "#111720",
//"terminal.dropBackground": "#53595d80",
//"terminal.foreground": "#cccccc",
//"terminal.selectionBackground": "#ffffff40",
//"terminal.tab.activeBorder": "#d19a66",
//"testing.iconErrored": "#f14c4c",
//"testing.iconFailed": "#f14c4c",
//"testing.iconPassed": "#73c991",
//"testing.iconQueued": "#cca700",
//"testing.iconSkipped": "#848484",
//"testing.iconUnset": "#848484",
//"testing.message.error.decorationForeground": "#fb718540",
//"testing.message.error.lineBackground": "#ff000033",
//"testing.message.info.decorationForeground": "#cacde280",
//"testing.peekBorder": "#fb718540",
//"testing.peekHeaderBackground": "#fb718506",
//"testing.runAction": "#73c991",
//"textBlockQuote.background": "#7f7f7f1a",
//"textBlockQuote.border": "#007acc80",
//"textSeparator.foreground": "#ffffff2e",
//"toolbar.activeBackground": "#00131d50",
//"tree.indentGuidesStroke": "#585858",
//"tree.tableColumnsBorder": "#cccccc20",
//"welcomePage.progress.background": "#00111a50",
//"welcomePage.progress.foreground": "#54bef2",
//"welcomePage.tileBackground": "#111720",
//"welcomePage.tileHoverBackground": "#141c26",
//"welcomePage.tileShadow.": "#00111a10",
//"activityBar.activeBackground": null,
//"activityBar.activeFocusBorder": null,
//"contrastActiveBorder": null,
//"contrastBorder": null,
//"debugToolBar.border": null,
//"diffEditor.border": null,
//"diffEditor.insertedTextBorder": null,
//"diffEditor.removedTextBorder": null,
//"dropdown.listBackground": null,
//"editor.findRangeHighlightBorder": null,
//"editor.rangeHighlightBorder": null,
//"editor.selectionForeground": null,
//"editor.selectionHighlightBorder": null,
//"editor.snippetFinalTabstopHighlightBackground": null,
//"editor.snippetTabstopHighlightBorder": null,
//"editor.symbolHighlightBorder": null,
//"editor.wordHighlightBorder": null,
//"editor.wordHighlightStrongBorder": null,
//"editorCursor.background": null,
//"editorError.background": null,
//"editorError.border": null,
//"editorGhostText.border": null,
//"editorGroup.background": null,
//"editorGroup.emptyBackground": null,
//"editorGroup.focusedEmptyBorder": null,
//"editorGroupHeader.border": null,
//"editorGroupHeader.tabsBorder": null,
//"editorHint.border": null,
//"editorInfo.background": null,
//"editorInfo.border": null,
//"editorUnnecessaryCode.border": null,
//"editorWarning.background": null,
//"editorWarning.border": null,
//"inputValidation.errorForeground": null,
//"inputValidation.infoForeground": null,
//"inputValidation.warningForeground": null,
//"list.inactiveFocusBackground": null,
//"list.inactiveFocusOutline": null,
//"list.inactiveSelectionIconForeground": null,
//"menu.border": null,
//"menu.selectionBorder": null,
//"menubar.selectionBorder": null,
//"merge.border": null,
//"minimap.background": null,
//"notebook.cellHoverBackground": null,
//"notebook.focusedCellBackground": null,
//"notebook.inactiveSelectedCellBorder": null,
//"notebook.outputContainerBackgroundColor": null,
//"notificationCenter.border": null,
//"notificationToast.border": null,
//"panelInput.border": null,
//"panelSectionHeader.border": null,
//"panelSectionHeader.foreground": null,
//"peekViewEditor.matchHighlightBorder": null,
//"quickInput.list.focusBackground": null,
//"tab.activeBorderTop": null,
//"tab.hoverBackground": null,
//"tab.hoverBorder": null,
//"tab.hoverForeground": null,
//"tab.unfocusedActiveBorderTop": null,
//"tab.unfocusedHoverBackground": null,
//"tab.unfocusedHoverBorder": null,
//"tab.unfocusedHoverForeground": null,
//"terminal.background": null,
//"testing.message.info.lineBackground": null,
//"toolbar.hoverOutline": null,
//"walkThrough.embeddedEditorBackground": null,
//"welcomePage.background": null,
//"welcomePage.buttonBackground": null,
//"welcomePage.buttonHoverBackground": null,
//"window.activeBorder": null,
//"window.inactiveBorder": null
} | the_stack |
import {IOas20NodeVisitor, IOas30NodeVisitor, IOasNodeVisitor} from "./visitor.iface";
import {Oas20Document} from "../models/2.0/document.model";
import {OasExtension} from "../models/extension.model";
import {Oas20Parameter, Oas20ParameterDefinition} from "../models/2.0/parameter.model";
import {Oas20Response, Oas20ResponseDefinition} from "../models/2.0/response.model";
import {
Oas20AdditionalPropertiesSchema,
Oas20AllOfSchema,
Oas20ItemsSchema,
Oas20PropertySchema,
Oas20SchemaDefinition
} from "../models/2.0/schema.model";
import {Oas20Example} from "../models/2.0/example.model";
import {Oas20Items} from "../models/2.0/items.model";
import {Oas20SecurityDefinitions} from "../models/2.0/security-definitions.model";
import {Oas20Scopes} from "../models/2.0/scopes.model";
import {Oas20Definitions} from "../models/2.0/definitions.model";
import {Oas20ParametersDefinitions} from "../models/2.0/parameters-definitions.model";
import {Oas20ResponsesDefinitions} from "../models/2.0/responses-definitions.model";
import {OasNodePath} from "../models/node-path";
import {OasDocument} from "../models/document.model";
import {OasInfo} from "../models/common/info.model";
import {OasContact} from "../models/common/contact.model";
import {OasLicense} from "../models/common/license.model";
import {OasPaths} from "../models/common/paths.model";
import {OasPathItem} from "../models/common/path-item.model";
import {OasOperation} from "../models/common/operation.model";
import {OasExternalDocumentation} from "../models/common/external-documentation.model";
import {OasSecurityRequirement} from "../models/common/security-requirement.model";
import {OasResponses} from "../models/common/responses.model";
import {OasSchema} from "../models/common/schema.model";
import {OasHeader} from "../models/common/header.model";
import {OasTag} from "../models/common/tag.model";
import {OasSecurityScheme} from "../models/common/security-scheme.model";
import {OasXML} from "../models/common/xml.model";
import {
Oas30AdditionalPropertiesSchema,
Oas30AllOfSchema,
Oas30AnyOfSchema,
Oas30ItemsSchema,
Oas30NotSchema,
Oas30OneOfSchema,
Oas30PropertySchema,
Oas30SchemaDefinition
} from "../models/3.0/schema.model";
import {Oas30Parameter, Oas30ParameterDefinition} from "../models/3.0/parameter.model";
import {Oas30Link, Oas30LinkDefinition} from "../models/3.0/link.model";
import {Oas30Callback, Oas30CallbackDefinition} from "../models/3.0/callback.model";
import {Oas30Example, Oas30ExampleDefinition} from "../models/3.0/example.model";
import {Oas30RequestBody, Oas30RequestBodyDefinition} from "../models/3.0/request-body.model";
import {Oas30Header, Oas30HeaderDefinition} from "../models/3.0/header.model";
import {
Oas30AuthorizationCodeOAuthFlow,
Oas30ClientCredentialsOAuthFlow,
Oas30ImplicitOAuthFlow,
Oas30PasswordOAuthFlow
} from "../models/3.0/oauth-flow.model";
import {Oas30OAuthFlows} from "../models/3.0/oauth-flows.model";
import {Oas30Components} from "../models/3.0/components.model";
import {Oas30CallbackPathItem} from "../models/3.0/path-item.model";
import {Oas30Response, Oas30ResponseDefinition} from "../models/3.0/response.model";
import {Oas30MediaType} from "../models/3.0/media-type.model";
import {Oas30Encoding} from "../models/3.0/encoding.model";
import {Oas30LinkParameterExpression} from "../models/3.0/link-parameter-expression.model";
import {Oas30LinkServer, Oas30Server} from "../models/3.0/server.model";
import {Oas30ServerVariable} from "../models/3.0/server-variable.model";
import {Oas20Headers} from "../models/2.0/headers.model";
import {Oas30LinkRequestBodyExpression} from "../models/3.0/link-request-body-expression.model";
import {Oas30Discriminator} from "../models/3.0/discriminator.model";
import {OasNode, OasValidationProblem} from "../models/node.model";
import {OasTraverserDirection, OasVisitorUtil} from "./visitor.utils";
/**
* Util for creating node paths.
*/
export class OasNodePathUtil {
public static createNodePath(node: OasNode): OasNodePath {
if (node.ownerDocument().is2xDocument()) {
let viz: Oas20NodePathVisitor = new Oas20NodePathVisitor();
OasVisitorUtil.visitTree(node, viz, OasTraverserDirection.up);
return viz.path();
} else if (node.ownerDocument().is3xDocument()) {
let viz: Oas30NodePathVisitor = new Oas30NodePathVisitor();
OasVisitorUtil.visitTree(node, viz, OasTraverserDirection.up);
return viz.path();
} else {
throw new Error("OAS version " + node.ownerDocument().getSpecVersion() + " not supported.");
}
}
}
/**
* Base class for Node Path visitors for all versions of OpenAPI.
*/
export abstract class OasNodePathVisitor implements IOasNodeVisitor {
protected _path: OasNodePath = new OasNodePath();
public path(): OasNodePath {
return this._path;
}
visitDocument(node: OasDocument): void {
// Nothing to do for the root
}
visitInfo(node: OasInfo): void {
this._path.prependSegment("info");
}
visitContact(node: OasContact): void {
this._path.prependSegment("contact");
}
visitLicense(node: OasLicense): void {
this._path.prependSegment("license");
}
visitPaths(node: OasPaths): void {
this._path.prependSegment("paths");
}
visitPathItem(node: OasPathItem): void {
this._path.prependSegment(node.path(), true);
}
visitOperation(node: OasOperation): void {
this._path.prependSegment(node.method());
}
visitExternalDocumentation(node: OasExternalDocumentation): void {
this._path.prependSegment("externalDocs");
}
visitSecurityRequirement(node: OasSecurityRequirement): void {
let securityRequirements: OasSecurityRequirement[] = (node.parent() as OasOperation | OasDocument).security;
let idx: number = 0;
for (let securityRequirement of securityRequirements) {
if (securityRequirement === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("security");
break;
} else {
idx++;
}
}
}
visitResponses(node: OasResponses): void {
this._path.prependSegment("responses");
}
visitSchema(node: OasSchema): void {
this._path.prependSegment("schema");
}
visitHeader(node: OasHeader): void {
this._path.prependSegment(node.headerName(), true);
}
visitTag(node: OasTag): void {
let tags: OasTag[] = (node.parent() as OasDocument).tags;
let idx: number = 0;
for (let tag of tags) {
if (tag === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("tags");
break;
} else {
idx++;
}
}
}
visitSecurityScheme(node: OasSecurityScheme): void {
this._path.prependSegment(node.schemeName(), true);
}
visitXML(node: OasXML): void {
this._path.prependSegment("xml");
}
visitExtension(node: OasExtension): void {
this._path.prependSegment(node.name);
}
visitValidationProblem(node: OasValidationProblem): void {
this._path.prependSegment(node.errorCode, true);
this._path.prependSegment("_validationProblems");
}
}
/**
* A visitor used to create a node path for any given node. Here are some examples
* of node paths:
*
* - The root document:
* /
*
* - An 'Info' object
* /info
*
* - A GET operation from pet-store:
* /paths[/pet/findByStatus]/get
*
* - External Documentation for a tag:
* /tags[2]/externalDocs
*
*/
export class Oas20NodePathVisitor extends OasNodePathVisitor implements IOas20NodeVisitor {
visitDocument(node: Oas20Document): void {
// Nothing to do for the root
}
visitParameter(node: Oas20Parameter): void {
let params: Oas20Parameter[] = (node.parent() as any).parameters;
let idx: number = 0;
for (let param of params) {
if (param === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("parameters");
break;
} else {
idx++;
}
}
}
visitParameterDefinition(node: Oas20ParameterDefinition): void {
this._path.prependSegment(node.parameterName(), true);
}
visitResponseDefinition(node: Oas20ResponseDefinition): void {
this._path.prependSegment(node.name(), true);
}
visitExample(node: Oas20Example): void {
this._path.prependSegment("examples");
}
visitItems(node: Oas20Items): void {
this._path.prependSegment("items");
}
visitSecurityDefinitions(node: Oas20SecurityDefinitions): void {
this._path.prependSegment("securityDefinitions");
}
visitScopes(node: Oas20Scopes): void {
this._path.prependSegment("scopes");
}
visitSchemaDefinition(node: Oas20SchemaDefinition): void {
this._path.prependSegment(node.definitionName(), true);
}
visitPropertySchema(node: Oas20PropertySchema): void {
this._path.prependSegment(node.propertyName(), true);
this._path.prependSegment("properties");
}
visitAdditionalPropertiesSchema(node: Oas20AdditionalPropertiesSchema): void {
this._path.prependSegment("additionalProperties");
}
visitAllOfSchema(node: Oas20AllOfSchema): void {
let schemas: Oas20AllOfSchema[] = (node.parent() as any).allOf;
let idx: number = 0;
for (let schema of schemas) {
if (schema === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("allOf");
break;
} else {
idx++;
}
}
}
visitItemsSchema(node: Oas20ItemsSchema): void {
let schemas: Oas20ItemsSchema[] = (node.parent() as any).items;
if (Array.isArray(schemas)) {
let idx: number = 0;
for (let schema of schemas) {
if (schema === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("items");
break;
} else {
idx++;
}
}
} else {
this._path.prependSegment("items");
}
}
visitDefinitions(node: Oas20Definitions): void {
this._path.prependSegment("definitions");
}
visitParametersDefinitions(node: Oas20ParametersDefinitions): void {
this._path.prependSegment("parameters");
}
visitResponsesDefinitions(node: Oas20ResponsesDefinitions): void {
this._path.prependSegment("responses");
}
visitResponse(node: Oas20Response): void {
this._path.prependSegment(node.statusCode() == null ? "default" : node.statusCode(), true);
}
visitHeaders(node: Oas20Headers): void {
this._path.prependSegment("headers");
}
}
/**
* The 3.0 version of a node path visitor (creates a node path from a node).
*/
export class Oas30NodePathVisitor extends OasNodePathVisitor implements IOas30NodeVisitor {
visitParameter(node: Oas30Parameter): void {
let params: Oas30Parameter[] = (node.parent() as any).parameters;
let idx: number = 0;
for (let param of params) {
if (param === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("parameters");
break;
} else {
idx++;
}
}
}
visitParameterDefinition(node: Oas30ParameterDefinition): void {
this._path.prependSegment(node.parameterName(), true);
this._path.prependSegment("parameters");
}
visitResponse(node: Oas30Response): void {
this._path.prependSegment(node.statusCode(), true);
}
visitMediaType(node: Oas30MediaType): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("content");
}
visitEncoding(node: Oas30Encoding): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("encoding");
}
visitExample(node: Oas30Example): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("examples");
}
visitLink(node: Oas30Link): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("links");
}
visitLinkParameterExpression(node: Oas30LinkParameterExpression): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("parameters");
}
visitLinkRequestBodyExpression(node: Oas30LinkRequestBodyExpression): void {
this._path.prependSegment("requestBody");
}
visitLinkServer(node: Oas30LinkServer): void {
this._path.prependSegment("server");
}
visitResponseDefinition(node: Oas30ResponseDefinition): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("responses");
}
visitRequestBody(node: Oas30RequestBody): void {
this._path.prependSegment("requestBody");
}
visitHeader(node: Oas30Header): void {
this._path.prependSegment(node.headerName(), true);
this._path.prependSegment("headers");
}
visitCallback(node: Oas30Callback): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("callbacks");
}
visitCallbackPathItem(node: Oas30CallbackPathItem): void {
this._path.prependSegment(node.path(), true);
}
visitServer(node: Oas30Server): void {
let servers: any[] = (node.parent() as any).servers;
let idx: number = 0;
for (let server of servers) {
if (server === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("servers");
break;
} else {
idx++;
}
}
}
visitServerVariable(node: Oas30ServerVariable): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("variables");
}
visitAllOfSchema(node: Oas30AllOfSchema): void {
let schemas: Oas30AllOfSchema[] = (node.parent() as any).allOf;
let idx: number = 0;
for (let schema of schemas) {
if (schema === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("allOf");
break;
} else {
idx++;
}
}
}
visitAnyOfSchema(node: Oas30AnyOfSchema): void {
let schemas: Oas30AnyOfSchema[] = (node.parent() as any).anyOf;
let idx: number = 0;
for (let schema of schemas) {
if (schema === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("anyOf");
break;
} else {
idx++;
}
}
}
visitOneOfSchema(node: Oas30OneOfSchema): void {
let schemas: Oas30OneOfSchema[] = (node.parent() as any).oneOf;
let idx: number = 0;
for (let schema of schemas) {
if (schema === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("oneOf");
break;
} else {
idx++;
}
}
}
visitNotSchema(node: Oas30NotSchema): void {
this._path.prependSegment("not");
}
visitPropertySchema(node: Oas30PropertySchema): void {
this._path.prependSegment(node.propertyName(), true);
this._path.prependSegment("properties");
}
visitItemsSchema(node: Oas30ItemsSchema): void {
let schemas: Oas30ItemsSchema[] = (node.parent() as any).items;
if (Array.isArray(schemas)) {
let idx: number = 0;
for (let schema of schemas) {
if (schema === node) {
this._path.prependSegment(idx, true);
this._path.prependSegment("items");
break;
} else {
idx++;
}
}
} else {
this._path.prependSegment("items");
}
}
visitAdditionalPropertiesSchema(node: Oas30AdditionalPropertiesSchema): void {
this._path.prependSegment("additionalProperties");
}
visitDiscriminator(node: Oas30Discriminator): void {
this._path.prependSegment("discriminator");
}
visitComponents(node: Oas30Components): void {
this._path.prependSegment("components");
}
visitSchemaDefinition(node: Oas30SchemaDefinition): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("schemas");
}
visitExampleDefinition(node: Oas30ExampleDefinition): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("examples");
}
visitRequestBodyDefinition(node: Oas30RequestBodyDefinition): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("requestBodies");
}
visitHeaderDefinition(node: Oas30HeaderDefinition): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("headers");
}
visitOAuthFlows(node: Oas30OAuthFlows): void {
this._path.prependSegment("flows");
}
visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void {
this._path.prependSegment("implicit");
}
visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void {
this._path.prependSegment("password");
}
visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void {
this._path.prependSegment("clientCredentials");
}
visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void {
this._path.prependSegment("authorizationCode");
}
visitLinkDefinition(node: Oas30LinkDefinition): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("links");
}
visitCallbackDefinition(node: Oas30CallbackDefinition): void {
this._path.prependSegment(node.name(), true);
this._path.prependSegment("callbacks");
}
visitSecurityScheme(node: OasSecurityScheme): void {
this._path.prependSegment(node.schemeName(), true);
this._path.prependSegment("securitySchemes");
}
} | the_stack |
import resolve from 'resolve';
import { join } from 'path';
import merge from 'lodash/merge';
import fs from 'fs-extra';
import { loadFromFixtureData } from './helpers';
import { appReleaseScenario, dummyAppScenarios, baseAddon } from './scenarios';
import { PreparedApp } from 'scenario-tester';
import QUnit from 'qunit';
const { module: Qmodule, test } = QUnit;
appReleaseScenario
.map('stage-1', project => {
let addon = baseAddon();
merge(addon.files, loadFromFixtureData('hello-world-addon'));
addon.pkg.name = 'my-addon';
addon.linkDependency('@embroider/sample-transforms', { baseDir: __dirname });
addon.linkDependency('@embroider/macros', { baseDir: __dirname });
project.addDependency(addon);
// our app will include an in-repo addon
project.pkg['ember-addon'] = { paths: ['lib/in-repo-addon'] };
merge(project.files, loadFromFixtureData('basic-in-repo-addon'));
})
.forEachScenario(async scenario => {
Qmodule(`${scenario.name} max compatibility`, function (hooks) {
let app: PreparedApp;
let workspaceDir: string;
hooks.before(async () => {
process.env.THROW_UNLESS_PARALLELIZABLE = '1'; // see https://github.com/embroider-build/embroider/pull/924
app = await scenario.prepare();
await app.execute('cross-env STAGE1_ONLY=true node ./node_modules/ember-cli/bin/ember b');
workspaceDir = fs.readFileSync(join(app.dir, 'dist', '.stage1-output'), 'utf8');
});
hooks.after(async () => {
delete process.env.THROW_UNLESS_PARALLELIZABLE;
});
test('component in app tree', function (assert) {
assert.ok(fs.existsSync(join(workspaceDir, 'node_modules/my-addon/_app_/components/hello-world.js')));
});
test('addon metadata', function (assert) {
let assertMeta = fs.readJsonSync(join(workspaceDir, 'node_modules/my-addon/package.json'))['ember-addon'];
assert.deepEqual(assertMeta['app-js'], { './components/hello-world.js': './_app_/components/hello-world.js' });
assert.ok(
JSON.stringify(assertMeta['implicit-modules']).includes('./components/hello-world'),
'staticAddonTrees is off so we should include the component implicitly'
);
assert.ok(
JSON.stringify(assertMeta['implicit-modules']).includes('./templates/components/hello-world.hbs'),
'staticAddonTrees is off so we should include the template implicitly'
);
assert.equal(assertMeta.version, 2);
});
test('component in addon tree', function (assert) {
let fileContents = fs.readFileSync(join(workspaceDir, 'node_modules/my-addon/components/hello-world.js'));
assert.ok(fileContents.includes('getOwnConfig()'), 'JS macros have not run yet');
assert.ok(fileContents.includes('embroider-sample-transforms-result'), 'custom babel plugins have run');
});
test('component template in addon tree', function (assert) {
let fileContents = fs.readFileSync(
join(workspaceDir, 'node_modules/my-addon/templates/components/hello-world.hbs')
);
assert.ok(
fileContents.includes('<div class={{embroider-sample-transforms-result}}>hello world</div>'),
'template is still hbs and custom transforms have run'
);
assert.ok(
fileContents.includes('<span>{{macroDependencySatisfies "ember-source" ">3"}}</span>'),
'template macros have not run'
);
});
test('test module name added', function (assert) {
let fileContents = fs.readFileSync(
join(workspaceDir, 'node_modules/my-addon/templates/components/module-name.hbs')
);
let searchRegExp = /\\/gi;
let replaceWith = '\\\\';
assert.ok(
fileContents.includes(
`<div class={{embroider-sample-transforms-module "${join(
'my-addon',
'templates',
'components',
'module-name.hbs'
).replace(searchRegExp, replaceWith)}"}}>hello world</div>`
),
'template is still hbs and module name transforms have run'
);
});
test('component with inline template', function (assert) {
let fileContents = fs.readFileSync(
join(workspaceDir, 'node_modules/my-addon/components/has-inline-template.js')
);
assert.ok(
fileContents.includes('hbs`<div class={{embroider-sample-transforms-result}}>Inline</div>'),
'tagged template is still hbs and custom transforms have run'
);
assert.ok(
/hbs\(["']<div class={{embroider-sample-transforms-result}}>Extra<\/div>["']\)/.test(fileContents.toString()),
'called template is still hbs and custom transforms have run'
);
assert.ok(
/<span>{{macroDependencySatisfies ['"]ember-source['"] ['"]>3['"]}}<\/span>/.test(fileContents.toString()),
'template macros have not run'
);
});
test('in-repo-addon is available', function (assert) {
assert.ok(resolve.sync('in-repo-addon/helpers/helper-from-in-repo-addon', { basedir: workspaceDir }));
});
test('dynamic import is preserved', function (assert) {
let fileContents = fs.readFileSync(
join(workspaceDir, 'node_modules/my-addon/components/does-dynamic-import.js')
);
assert.ok(/return import\(['"]some-library['"]\)/.test(fileContents.toString()));
});
});
});
appReleaseScenario
.map('stage-1-inline-hbs', project => {
let addon = baseAddon();
merge(addon.files, {
addon: {
components: {
'has-inline-template.js': `
import Component from '@ember/component';
import hbs from 'htmlbars-inline-precompile';
export default Component.extend({
// tagged template form:
layout: ${"hbs`<div class={{embroider-sample-transforms-target}}>Inline</div><span>{{macroDependencySatisfies 'ember-source' '>3'}}</span>`"},
// call expression form:
extra: hbs("<div class={{embroider-sample-transforms-target}}>Extra</div>")
});
`,
},
},
});
addon.pkg.name = 'my-addon';
addon.linkDependency('@embroider/sample-transforms', { baseDir: __dirname });
addon.linkDependency('@embroider/macros', { baseDir: __dirname });
addon.linkDependency('ember-cli-htmlbars-inline-precompile', { baseDir: __dirname });
addon.linkDependency('ember-cli-htmlbars-3', { baseDir: __dirname, resolveName: 'ember-cli-htmlbars' });
project.addDependency(addon);
})
.forEachScenario(async scenario => {
Qmodule(`${scenario.name} inline hbs, ember-cli-htmlbars@3`, function (hooks) {
let app: PreparedApp;
let workspaceDir: string;
hooks.before(async () => {
app = await scenario.prepare();
await app.execute('cross-env STAGE1_ONLY=true node ./node_modules/ember-cli/bin/ember b');
workspaceDir = fs.readFileSync(join(app.dir, 'dist', '.stage1-output'), 'utf8');
});
test('component with inline template', function (assert) {
let fileContents = fs.readFileSync(
join(workspaceDir, 'node_modules/my-addon/components/has-inline-template.js')
);
assert.ok(
fileContents.includes('hbs`<div class={{embroider-sample-transforms-result}}>Inline</div>'),
'tagged template is still hbs and custom transforms have run'
);
assert.ok(
/hbs\(["']<div class={{embroider-sample-transforms-result}}>Extra<\/div>["']\)/.test(fileContents.toString()),
'called template is still hbs and custom transforms have run'
);
assert.ok(
/<span>{{macroDependencySatisfies ['"]ember-source['"] ['"]>3['"]}}<\/span>/.test(fileContents.toString()),
'template macros have not run'
);
});
});
});
appReleaseScenario
.map('stage-1-problematic-addon-zoo', project => {
let addon = baseAddon();
// an addon that emits a package.json file from its treeForAddon
merge(addon.files, {
index: `module.exports = {
name: require('./package').name,
treeForAddon() {
return require('path').join(__dirname, 'alpha-addon-tree');
}
};`,
'alpha-addon-tree': {
'package.json': '{}',
},
});
addon.pkg.name = 'alpha';
let hasCustomBase = baseAddon();
// an addon that manually extends the Addon base class
merge(hasCustomBase.files, {
'index.js': `
const { join } = require('path');
const Addon = require('ember-cli/lib/models/addon');
module.exports = Addon.extend({
name: 'has-custom-base',
treeForAddon() {
return join(__dirname, 'weird-addon-path');
}
});`,
'weird-addon-path': {
'has-custom-base': {
'file.js': '// weird-addon-path/file.js',
},
},
});
hasCustomBase.pkg.name = 'has-custom-base';
let undefinedFastboot = baseAddon();
// an addon that nullifies its custom fastboot tree with a custom fastboot hook
merge(undefinedFastboot.files, {
'index.js': `module.exports = {
name: 'undefined-fastboot',
treeForFastBoot() {}
}`,
fastboot: {
'something.js': '',
},
});
undefinedFastboot.pkg.name = 'undefined-fastboot';
// Use one addon to patch the hook on another (yes, this happens in the
// wild...), and ensure we still detect the customized hook
let externallyCustomized = baseAddon();
let troubleMaker = baseAddon();
merge(troubleMaker.files, {
injected: {
hello: { 'world.js': '// hello' },
},
'index.js': `
const { join } = require('path');
module.exports = {
name: 'trouble-maker',
included() {
let instance = this.project.addons.find(a => a.name === "externally-customized");
let root = this.root;
instance.treeForPublic = function() {
return join(root, 'injected');
}
}
}`,
});
externallyCustomized.pkg.name = 'externally-customized';
troubleMaker.pkg.name = 'trouble-maker';
// an addon that customizes packageJSON['ember-addon'].main and then uses
// stock trees. Setting the main actually changes the root for *all* stock
// trees.
let movedMain = baseAddon();
merge(movedMain.files, {
custom: {
'index.js': `module.exports = { name: 'moved-main'};`,
addon: { helpers: { 'hello.js': '// hello-world' } },
},
});
merge(movedMain.pkg, { 'ember-addon': { main: 'custom/index.js' }, name: 'moved-main' });
// an addon that uses treeFor() to sometimes suppress its stock trees
let suppressed = baseAddon();
merge(suppressed.files, {
'index.js': `module.exports = {
name: require('./package').name,
treeFor(name) {
if (name !== 'app') {
return this._super.treeFor(name);
} else {
return undefined;
}
}
}`,
addon: {
'addon-example.js': '// example',
},
app: {
'app-example.js': '// example',
},
});
suppressed.pkg.name = 'suppressed';
// an addon that uses treeFor() to sometimes suppress its custom trees
let suppressedCustom = baseAddon();
merge(suppressedCustom.files, {
'index.js': `module.exports = {
name: require('./package').name,
treeFor(name) {
if (name !== 'app') {
return this._super(name);
} else {
return undefined;
}
},
treeForApp() {
return require('path').join(__dirname, 'app-custom');
},
treeForAddon() {
return require('path').join(__dirname, 'addon-custom');
},
}`,
'addon-custom': {
'suppressed-custom': {
'addon-example.js': '// example',
},
},
'app-custom': {
'app-example.js': '// example',
},
});
suppressedCustom.pkg.name = 'suppressed-custom';
project.addDependency(addon);
project.addDependency(hasCustomBase);
project.addDependency(undefinedFastboot);
project.addDependency(externallyCustomized);
project.addDependency(troubleMaker);
project.addDependency(movedMain);
project.addDependency(suppressed);
project.addDependency(suppressedCustom);
project.pkg['ember-addon'] = { paths: ['lib/disabled-in-repo-addon', 'lib/blacklisted-in-repo-addon'] };
merge(project.files, loadFromFixtureData('blacklisted-addon-build-options'));
})
.forEachScenario(async scenario => {
Qmodule(`${scenario.name} problematic addon zoo`, function (hooks) {
let app: PreparedApp;
let workspaceDir: string;
hooks.before(async () => {
app = await scenario.prepare();
await app.execute('cross-env STAGE1_ONLY=true node ./node_modules/ember-cli/bin/ember b');
workspaceDir = fs.readFileSync(join(app.dir, 'dist', '.stage1-output'), 'utf8');
});
test('real package.json wins', function (assert) {
let fileContents = fs.readFileSync(join(workspaceDir, 'node_modules/alpha/package.json'));
assert.ok(fileContents.includes('alpha'));
});
test('custom tree hooks are detected in addons that manually extend from Addon', function (assert) {
let fileContents = fs.readFileSync(join(workspaceDir, 'node_modules/has-custom-base/file.js'));
assert.ok(/weird-addon-path\/file\.js/.test(fileContents.toString()));
});
test('no fastboot-js is emitted', function (assert) {
let fileContents = fs.readJsonSync(join(workspaceDir, 'node_modules/undefined-fastboot/package.json'));
assert.equal(fileContents['ember-addon']['fastboot-js'], null);
});
test('custom tree hooks are detected when they have been patched into the addon instance', function (assert) {
assert.ok(fs.existsSync(join(workspaceDir, 'node_modules/externally-customized/public/hello/world.js')));
});
test('addon with customized ember-addon.main can still use stock trees', function (assert) {
let fileContents = fs.readFileSync(join(workspaceDir, 'node_modules/moved-main/helpers/hello.js'));
assert.ok(/hello-world/.test(fileContents.toString()));
});
test('addon with customized treeFor can suppress a stock tree', function (assert) {
assert.notOk(fs.existsSync(join(workspaceDir, 'node_modules/suppressed/_app_/app-example.js')));
});
test('addon with customized treeFor can pass through a stock tree', function (assert) {
assert.ok(fs.existsSync(join(workspaceDir, 'node_modules/suppressed/addon-example.js')));
});
test('addon with customized treeFor can suppress a customized tree', function (assert) {
assert.notOk(fs.existsSync(join(workspaceDir, 'node_modules/suppressed-custom/_app_/app-example.js')));
});
test('addon with customized treeFor can pass through a customized tree', function (assert) {
assert.ok(fs.existsSync(join(workspaceDir, 'node_modules/suppressed-custom/addon-example.js')));
});
test('blacklisted in-repo addon is present but empty', function (assert) {
assert.ok(fs.existsSync(join(workspaceDir, 'lib/blacklisted-in-repo-addon/package.json')));
assert.notOk(fs.existsSync(join(workspaceDir, 'lib/blacklisted-in-repo-addon/example.js')));
});
test('disabled in-repo addon is present but empty', function (assert) {
assert.ok(fs.existsSync(join(workspaceDir, 'lib/disabled-in-repo-addon/package.json')));
assert.notOk(fs.existsSync(join(workspaceDir, 'lib/disabled-in-repo-addon/example.js')));
});
});
});
dummyAppScenarios
.map('stage-1-dummy-addon', project => {
project.pkg.name = 'my-addon';
project.linkDependency('@embroider/webpack', { baseDir: __dirname });
project.linkDependency('@embroider/core', { baseDir: __dirname });
project.linkDependency('@embroider/compat', { baseDir: __dirname });
merge(project.files, {
addon: {
components: {
'hello-world.js': '',
},
},
});
})
.forEachScenario(async scenario => {
Qmodule(`${scenario.name} addon dummy app`, function (hooks) {
let app: PreparedApp;
let workspaceDir: string;
hooks.before(async () => {
app = await scenario.prepare();
await app.execute('cross-env STAGE1_ONLY=true node ./node_modules/ember-cli/bin/ember b');
workspaceDir = fs.readFileSync(join(app.dir, 'dist', '.stage1-output'), 'utf8');
});
test('dummy app can resolve own addon', function (assert) {
assert.ok(resolve.sync('my-addon/components/hello-world.js', { basedir: workspaceDir }));
});
});
}); | the_stack |
import { expect } from 'chai';
import * as sinon from 'sinon';
import { Network } from '../../../src/compose/network';
import { NetworkInspectInfo } from 'dockerode';
import { createNetwork, withMockerode } from '../../lib/mockerode';
import { log } from '../../../src/lib/supervisor-console';
describe('compose/network', () => {
describe('creating a network from a compose object', () => {
it('creates a default network configuration if no config is given', () => {
const network = Network.fromComposeObject('default', 12345, {});
expect(network.name).to.equal('default');
expect(network.appId).to.equal(12345);
// Default configuration options
expect(network.config.driver).to.equal('bridge');
expect(network.config.ipam).to.deep.equal({
driver: 'default',
config: [],
options: {},
});
expect(network.config.enableIPv6).to.equal(false);
expect(network.config.labels).to.deep.equal({});
expect(network.config.options).to.deep.equal({});
});
it('normalizes legacy labels', () => {
const network = Network.fromComposeObject('default', 12345, {
labels: {
'io.resin.features.something': '1234',
},
});
expect(network.config.labels).to.deep.equal({
'io.balena.features.something': '1234',
});
});
it('accepts valid IPAM configurations', () => {
const network0 = Network.fromComposeObject('default', 12345, {
ipam: { driver: 'dummy', config: [], options: {} },
});
// Default configuration options
expect(network0.config.ipam).to.deep.equal({
driver: 'dummy',
config: [],
options: {},
});
const network1 = Network.fromComposeObject('default', 12345, {
ipam: {
driver: 'default',
config: [
{
subnet: '172.20.0.0/16',
ip_range: '172.20.10.0/24',
aux_addresses: { host0: '172.20.10.15', host1: '172.20.10.16' },
gateway: '172.20.0.1',
},
],
options: {},
},
});
// Default configuration options
expect(network1.config.ipam).to.deep.equal({
driver: 'default',
config: [
{
subnet: '172.20.0.0/16',
ipRange: '172.20.10.0/24',
gateway: '172.20.0.1',
auxAddress: { host0: '172.20.10.15', host1: '172.20.10.16' },
},
],
options: {},
});
});
it('warns about IPAM configuration without both gateway and subnet', () => {
const logSpy = sinon.spy(log, 'warn');
Network.fromComposeObject('default', 12345, {
ipam: {
driver: 'default',
config: [
{
subnet: '172.20.0.0/16',
},
],
options: {},
},
});
expect(logSpy).to.have.been.calledOnce;
expect(logSpy).to.have.been.calledWithMatch(
'Network IPAM config entries must have both a subnet and gateway',
);
logSpy.resetHistory();
Network.fromComposeObject('default', 12345, {
ipam: {
driver: 'default',
config: [
{
gateway: '172.20.0.1',
},
],
options: {},
},
});
expect(logSpy).to.have.been.calledOnce;
expect(logSpy).to.have.been.calledWithMatch(
'Network IPAM config entries must have both a subnet and gateway',
);
logSpy.restore();
});
it('parses values from a compose object', () => {
const network1 = Network.fromComposeObject('default', 12345, {
driver: 'bridge',
enable_ipv6: true,
internal: false,
ipam: {
driver: 'default',
options: {
'com.docker.ipam-option': 'abcd',
},
config: [
{
subnet: '172.18.0.0/16',
gateway: '172.18.0.1',
},
],
},
driver_opts: {
'com.docker.network-option': 'abcd',
},
labels: {
'com.docker.some-label': 'yes',
},
});
const dockerConfig = network1.toDockerConfig();
expect(dockerConfig.Driver).to.equal('bridge');
// Check duplicate forced to be true
expect(dockerConfig.CheckDuplicate).to.equal(true);
expect(dockerConfig.Internal).to.equal(false);
expect(dockerConfig.EnableIPv6).to.equal(true);
expect(dockerConfig.IPAM).to.deep.equal({
Driver: 'default',
Options: {
'com.docker.ipam-option': 'abcd',
},
Config: [
{
Subnet: '172.18.0.0/16',
Gateway: '172.18.0.1',
},
],
});
expect(dockerConfig.Labels).to.deep.equal({
'io.balena.supervised': 'true',
'com.docker.some-label': 'yes',
});
expect(dockerConfig.Options).to.deep.equal({
'com.docker.network-option': 'abcd',
});
});
});
describe('creating a network from docker engine state', () => {
it('rejects networks without the proper name format', () => {
expect(() =>
Network.fromDockerNetwork({
Id: 'deadbeef',
Name: 'abcd',
} as NetworkInspectInfo),
).to.throw();
expect(() =>
Network.fromDockerNetwork({
Id: 'deadbeef',
Name: 'abcd_1234',
} as NetworkInspectInfo),
).to.throw();
expect(() =>
Network.fromDockerNetwork({
Id: 'deadbeef',
Name: 'abcd_abcd',
} as NetworkInspectInfo),
).to.throw();
expect(() =>
Network.fromDockerNetwork({
Id: 'deadbeef',
Name: '1234',
} as NetworkInspectInfo),
).to.throw();
});
it('creates a network object from a docker network configuration', () => {
const network = Network.fromDockerNetwork({
Id: 'deadbeef',
Name: '1234_default',
Driver: 'bridge',
EnableIPv6: true,
IPAM: {
Driver: 'default',
Options: {},
Config: [
{
Subnet: '172.18.0.0/16',
Gateway: '172.18.0.1',
},
],
} as NetworkInspectInfo['IPAM'],
Internal: true,
Containers: {},
Options: {
'com.docker.some-option': 'abcd',
} as NetworkInspectInfo['Options'],
Labels: {
'io.balena.features.something': '123',
} as NetworkInspectInfo['Labels'],
} as NetworkInspectInfo);
expect(network.appId).to.equal(1234);
expect(network.name).to.equal('default');
expect(network.config.enableIPv6).to.equal(true);
expect(network.config.ipam.driver).to.equal('default');
expect(network.config.ipam.options).to.deep.equal({});
expect(network.config.ipam.config).to.deep.equal([
{
subnet: '172.18.0.0/16',
gateway: '172.18.0.1',
},
]);
expect(network.config.internal).to.equal(true);
expect(network.config.options).to.deep.equal({
'com.docker.some-option': 'abcd',
});
expect(network.config.labels).to.deep.equal({
'io.balena.features.something': '123',
});
});
it('normalizes legacy label names and excludes supervised label', () => {
const network = Network.fromDockerNetwork({
Id: 'deadbeef',
Name: '1234_default',
IPAM: {
Driver: 'default',
Options: {},
Config: [],
} as NetworkInspectInfo['IPAM'],
Labels: {
'io.resin.features.something': '123',
'io.balena.features.dummy': 'abc',
'io.balena.supervised': 'true',
} as NetworkInspectInfo['Labels'],
} as NetworkInspectInfo);
expect(network.config.labels).to.deep.equal({
'io.balena.features.something': '123',
'io.balena.features.dummy': 'abc',
});
});
});
describe('creating a network compose configuration from a network instance', () => {
it('creates a docker compose network object from the internal network config', () => {
const network = Network.fromDockerNetwork({
Id: 'deadbeef',
Name: '1234_default',
Driver: 'bridge',
EnableIPv6: true,
IPAM: {
Driver: 'default',
Options: {},
Config: [
{
Subnet: '172.18.0.0/16',
Gateway: '172.18.0.1',
},
],
} as NetworkInspectInfo['IPAM'],
Internal: true,
Containers: {},
Options: {
'com.docker.some-option': 'abcd',
} as NetworkInspectInfo['Options'],
Labels: {
'io.balena.features.something': '123',
} as NetworkInspectInfo['Labels'],
} as NetworkInspectInfo);
// Convert to compose object
const compose = network.toComposeObject();
expect(compose.driver).to.equal('bridge');
expect(compose.driver_opts).to.deep.equal({
'com.docker.some-option': 'abcd',
});
expect(compose.enable_ipv6).to.equal(true);
expect(compose.internal).to.equal(true);
expect(compose.ipam).to.deep.equal({
driver: 'default',
options: {},
config: [
{
subnet: '172.18.0.0/16',
gateway: '172.18.0.1',
},
],
});
expect(compose.labels).to.deep.equal({
'io.balena.features.something': '123',
});
});
});
describe('generateDockerName', () => {
it('creates a proper network name from the user given name and the app id', () => {
expect(Network.generateDockerName(12345, 'default')).to.equal(
'12345_default',
);
expect(Network.generateDockerName(12345, 'bleh')).to.equal('12345_bleh');
expect(Network.generateDockerName(1, 'default')).to.equal('1_default');
});
});
describe('comparing network configurations', () => {
it('ignores IPAM configuration', () => {
const network = Network.fromComposeObject('default', 12345, {
ipam: {
driver: 'default',
config: [
{
subnet: '172.20.0.0/16',
ip_range: '172.20.10.0/24',
gateway: '172.20.0.1',
},
],
options: {},
},
});
expect(
network.isEqualConfig(Network.fromComposeObject('default', 12345, {})),
).to.be.true;
// Only ignores ipam.config, not other ipam elements
expect(
network.isEqualConfig(
Network.fromComposeObject('default', 12345, {
ipam: { driver: 'aaa' },
}),
),
).to.be.false;
});
it('compares configurations recursively', () => {
expect(
Network.fromComposeObject('default', 12345, {}).isEqualConfig(
Network.fromComposeObject('default', 12345, {}),
),
).to.be.true;
expect(
Network.fromComposeObject('default', 12345, {
driver: 'default',
}).isEqualConfig(Network.fromComposeObject('default', 12345, {})),
).to.be.false;
expect(
Network.fromComposeObject('default', 12345, {
enable_ipv6: true,
}).isEqualConfig(Network.fromComposeObject('default', 12345, {})),
).to.be.false;
expect(
Network.fromComposeObject('default', 12345, {
enable_ipv6: false,
internal: false,
}).isEqualConfig(
Network.fromComposeObject('default', 12345, { internal: true }),
),
).to.be.false;
});
});
describe('creating networks', () => {
it('creates a new network on the engine with the given data', async () => {
await withMockerode(async (mockerode) => {
const network = Network.fromComposeObject('default', 12345, {
ipam: {
driver: 'default',
config: [
{
subnet: '172.20.0.0/16',
ip_range: '172.20.10.0/24',
gateway: '172.20.0.1',
},
],
options: {},
},
});
// Create the network
await network.create();
// Check that the create function was called with proper arguments
expect(mockerode.createNetwork).to.have.been.calledOnceWith({
Name: '12345_default',
Driver: 'bridge',
CheckDuplicate: true,
IPAM: {
Driver: 'default',
Config: [
{
Subnet: '172.20.0.0/16',
IPRange: '172.20.10.0/24',
Gateway: '172.20.0.1',
},
],
Options: {},
},
EnableIPv6: false,
Internal: false,
Labels: {
'io.balena.supervised': 'true',
},
Options: {},
});
});
});
it('throws the error if there is a problem while creating the network', async () => {
await withMockerode(async (mockerode) => {
const network = Network.fromComposeObject('default', 12345, {
ipam: {
driver: 'default',
config: [
{
subnet: '172.20.0.0/16',
ip_range: '172.20.10.0/24',
gateway: '172.20.0.1',
},
],
options: {},
},
});
// Re-define the dockerode.createNetwork to throw
mockerode.createNetwork.rejects('Unknown engine error');
// Creating the network should fail
return expect(network.create()).to.be.rejected.then((error) =>
expect(error).to.have.property('name', 'Unknown engine error'),
);
});
});
});
describe('removing a network', () => {
it('removes the network from the engine if it exists', async () => {
// Create a mock network to add to the mock engine
const dockerNetwork = createNetwork({
Id: 'deadbeef',
Name: '12345_default',
});
await withMockerode(
async (mockerode) => {
// Check that the engine has the network
expect(await mockerode.listNetworks()).to.have.lengthOf(1);
// Create a dummy network object
const network = Network.fromComposeObject('default', 12345, {});
// Perform the operation
await network.remove();
// The removal step should delete the object from the engine data
expect(mockerode.removeNetwork).to.have.been.calledOnceWith(
'deadbeef',
);
},
{ networks: [dockerNetwork] },
);
});
it('ignores the request if the given network does not exist on the engine', async () => {
// Create a mock network to add to the mock engine
const mockNetwork = createNetwork({
Id: 'deadbeef',
Name: 'some_network',
});
await withMockerode(
async (mockerode) => {
// Check that the engine has the network
expect(await mockerode.listNetworks()).to.have.lengthOf(1);
// Create a dummy network object
const network = Network.fromComposeObject('default', 12345, {});
// This should not fail
await expect(network.remove()).to.not.be.rejected;
// We expect the network state to remain constant
expect(await mockerode.listNetworks()).to.have.lengthOf(1);
},
{ networks: [mockNetwork] },
);
});
it('throws the error if there is a problem while removing the network', async () => {
// Create a mock network to add to the mock engine
const mockNetwork = createNetwork({
Id: 'deadbeef',
Name: '12345_default',
});
await withMockerode(
async (mockerode) => {
// We can change the return value of the mockerode removeNetwork
// to have the remove operation fail
mockerode.removeNetwork.throws('Failed to remove the network');
// Create a dummy network object
const network = Network.fromComposeObject('default', 12345, {});
await expect(network.remove()).to.be.rejected;
},
{ networks: [mockNetwork] },
);
});
});
}); | the_stack |
import React, { Component, SyntheticEvent, MouseEvent } from 'react'
import { Locale, DateTime, ApplyLocaleContext } from '@instructure/ui-i18n'
import type { Moment } from '@instructure/ui-i18n'
import { FormFieldGroup } from '@instructure/ui-form-field'
import type { FormMessage } from '@instructure/ui-form-field'
import { DateInput } from '@instructure/ui-date-input'
import { TimeSelect } from '@instructure/ui-time-select'
import { Calendar } from '@instructure/ui-calendar'
import { testable } from '@instructure/ui-testable'
import { AccessibleContent } from '@instructure/ui-a11y-content'
import { IconButton } from '@instructure/ui-buttons'
import {
IconArrowOpenEndSolid,
IconArrowOpenStartSolid
} from '@instructure/ui-icons'
import { debounce } from '@instructure/debounce'
import type { DateTimeInputProps, DateTimeInputState } from './props'
import { propTypes, allowedProps } from './props'
/**
---
category: components
---
@tsProps
**/
@testable()
class DateTimeInput extends Component<DateTimeInputProps, DateTimeInputState> {
// extra verbose localized date and time
private static readonly DEFAULT_MESSAGE_FORMAT = 'LLLL'
static propTypes = propTypes
static allowedProps = allowedProps
static defaultProps = {
layout: 'inline',
timeStep: 30,
messageFormat: DateTimeInput.DEFAULT_MESSAGE_FORMAT,
isRequired: false,
dateFormat: 'LL' // Localized date with full month, e.g. "August 6, 2014"
} as const
context!: React.ContextType<typeof ApplyLocaleContext>
static contextType = ApplyLocaleContext
private _timeInput?: TimeSelect
ref: Element | null = null // This is used by Tooltip for positioning
handleRef = (el: Element | null) => {
this.ref = el
}
constructor(props: DateTimeInputProps) {
super(props)
// State needs to be calculated because render could be called before
// componentDidMount()
this.state = this.recalculateState(props.value || props.defaultValue)
}
componentDidMount() {
// we'll need to recalculate the state because the context value is
// set at this point (and it might change locale & timezone)
const initState = this.recalculateState(
this.props.value || this.props.defaultValue
)
this.setState(initState)
}
componentDidUpdate(prevProps: Readonly<DateTimeInputProps>): void {
const valueChanged =
prevProps.value !== this.props.value ||
prevProps.defaultValue !== this.props.defaultValue
const isUpdated =
valueChanged ||
prevProps.locale !== this.props.locale ||
prevProps.timezone !== this.props.timezone ||
prevProps.dateFormat !== this.props.dateFormat ||
prevProps.messageFormat !== this.props.messageFormat ||
prevProps.invalidDateTimeMessage !== this.props.invalidDateTimeMessage
if (isUpdated) {
this.setState((_prevState: DateTimeInputState) => {
return {
...this.recalculateState(this.props.value || this.props.defaultValue)
}
})
}
}
recalculateState(
dateStr?: string,
doNotChangeDate = false,
doNotChangeTime = false
): DateTimeInputState {
let errorMsg: FormMessage | undefined
if (dateStr) {
const parsed = DateTime.parse(dateStr, this.locale(), this.timezone())
if (parsed.isValid()) {
if (doNotChangeTime && this.state.timeSelectValue) {
// There is a selected time, adjust the parsed date to its value
const timeParsed = DateTime.parse(
this.state.timeSelectValue,
this.locale(),
this.timezone()
)
parsed.hour(timeParsed.hour()).minute(timeParsed.minute())
}
if (doNotChangeDate && this.state.iso) {
parsed
.date(this.state.iso.date())
.month(this.state.iso.month())
.year(this.state.iso.year())
}
const newTimeSelectValue = this.state?.timeSelectValue
? this.state.timeSelectValue
: this._timeInput
?.getBaseDate()
.minute(parsed.minute())
.hour(parsed.hour())
.toISOString()
return {
iso: parsed.clone(),
calendarSelectedDate: parsed.clone(),
dateInputTextChanged: false,
dateInputText: parsed.format(this.dateFormat),
message: {
type: 'success',
text: parsed.format(this.props.messageFormat)
},
timeSelectValue: newTimeSelectValue,
renderedDate: parsed.clone()
}
}
if (dateStr.length > 0 || this.props.isRequired) {
const text =
typeof this.props.invalidDateTimeMessage === 'function'
? this.props.invalidDateTimeMessage(dateStr)
: this.props.invalidDateTimeMessage
errorMsg = text ? { text, type: 'error' } : undefined
}
}
return {
iso: undefined,
calendarSelectedDate: undefined,
dateInputText: dateStr ? dateStr : '',
message: errorMsg,
renderedDate: DateTime.now(this.locale(), this.timezone()),
dateInputTextChanged: false
}
}
locale(): string {
if (this.props.locale) {
return this.props.locale
} else if (this.context && this.context.locale) {
return this.context.locale
}
return Locale.browserLocale()
}
timezone() {
if (this.props.timezone) {
return this.props.timezone
} else if (this.context && this.context.timezone) {
return this.context.timezone
}
return DateTime.browserTimeZone()
}
get dateFormat() {
return this.props.dateFormat
}
// Called when the user enters text into dateInput
handleDateTextChange = (_event: SyntheticEvent, date: { value: string }) => {
const dateParsed = this.tryParseDate(date.value)
this.setState({
dateInputText: date.value,
dateInputTextChanged: true,
calendarSelectedDate: dateParsed ? dateParsed : undefined,
renderedDate: dateParsed
? dateParsed.clone()
: DateTime.now(this.locale(), this.timezone())
})
}
tryParseDate(val: string) {
const parsed = DateTime.parse(val, this.locale(), this.timezone())
return parsed.isValid() ? parsed : null
}
// date is returned es a ISO string, like 2021-09-14T22:00:00.000Z
handleDayClick = (event: MouseEvent<any>, { date }: { date: string }) => {
const dateParsed = DateTime.parse(date, this.locale(), this.timezone())
this.updateStateBasedOnDateInput(dateParsed, event)
}
handleHideCalendar = (event: SyntheticEvent) => {
// update state based on the DateInput's text value
if (
this.state.dateInputTextChanged ||
((event as unknown) as KeyboardEvent).key === 'Enter'
) {
const dateParsed = this.tryParseDate(this.state.dateInputText)
this.updateStateBasedOnDateInput(dateParsed, event)
} else {
// user clicked outside or tabbed away or pressed esc, reset text
this.setState({
dateInputText: this.state.iso
? this.state.iso.format(this.dateFormat)
: '',
calendarSelectedDate: this.state.iso
? this.state.iso.clone()
: undefined
})
}
this.setState({ isShowingCalendar: false, dateInputTextChanged: false })
}
updateStateBasedOnDateInput(
dateParsed: Moment | null,
event: SyntheticEvent
) {
let newState
if (
dateParsed &&
this.state.timeSelectValue &&
(!this.state.dateInputText || this.state.dateInputText == '')
) {
// There is already a selected time, but no date. Adjust the time too
const timeParsed = DateTime.parse(
this.state.timeSelectValue,
this.locale(),
this.timezone()
)
const dateParsedAdjusted = dateParsed.set({
hour: timeParsed.hour(),
minute: timeParsed.minute()
})
newState = this.recalculateState(
dateParsedAdjusted.toISOString(),
false,
false
)
} else if (!dateParsed) {
// if the text in the dateInput is not readable display error
newState = this.recalculateState(this.state.dateInputText, false, true)
} else {
newState = this.recalculateState(dateParsed?.toISOString(), false, true)
}
this.changeStateIfNeeded(newState, event)
}
handleTimeChange = (
event: SyntheticEvent,
option: { value: string; inputText: string }
) => {
let newValue: string
if (this.state.iso) {
newValue = option.value
} else {
// if no date is set just return the input text, it will error
newValue = option.inputText
}
const newState = this.recalculateState(newValue, true, false)
this.changeStateIfNeeded(newState, event)
this.setState({ timeSelectValue: option.value })
}
changeStateIfNeeded = (newState: DateTimeInputState, e: SyntheticEvent) => {
this.setState({ message: newState.message })
if (!newState.iso && !this.state.iso) {
return
}
if (
!this.state.iso ||
!newState.iso ||
!this.state.iso.isSame(newState.iso)
) {
this.setState(newState)
if (this.props.onChange) {
this.props.onChange(e, newState.iso?.toISOString())
}
}
}
handleBlur = (e: SyntheticEvent) => {
// when TABbing from the DateInput to TimeInput or visa-versa, the blur
// happens on the target before the relatedTarget gets focus.
// The timeout gives it a moment for that to happen
if (typeof this.props.onBlur === 'function') {
window.setTimeout(() => {
this.props.onBlur?.(e)
}, 0)
}
}
timeInputComponentRef = (node: TimeSelect) => {
this._timeInput = node
}
handleShowCalendar = (_event: SyntheticEvent) => {
this.setState({ isShowingCalendar: true })
}
handleSelectNextDay = (_event: SyntheticEvent) => {
let toAlter
if (this.state.calendarSelectedDate) {
toAlter = this.state.calendarSelectedDate.clone()
} else if (this.state.iso) {
toAlter = this.state.iso.clone()
} else {
toAlter = DateTime.now(this.locale(), this.timezone())
}
toAlter.add({ days: 1 })
this.setState({
calendarSelectedDate: toAlter,
renderedDate: toAlter.clone(),
dateInputText: toAlter.format(this.dateFormat)
})
}
handleSelectPrevDay = (_event: SyntheticEvent) => {
let toAlter
if (this.state.calendarSelectedDate) {
toAlter = this.state.calendarSelectedDate.clone()
} else if (this.state.iso) {
toAlter = this.state.iso.clone()
} else {
toAlter = DateTime.now(this.locale(), this.timezone())
}
toAlter.subtract({ days: 1 })
this.setState({
calendarSelectedDate: toAlter,
renderedDate: toAlter.clone(),
dateInputText: toAlter.format(this.dateFormat)
})
}
handleRenderNextMonth = (_event: SyntheticEvent) => {
this.setState({
renderedDate: this.state.renderedDate.clone().add({ months: 1 })
})
}
handleRenderPrevMonth = (_event: SyntheticEvent) => {
this.setState({
renderedDate: this.state.renderedDate.clone().subtract({ months: 1 })
})
}
renderDays() {
if (!this.state.isShowingCalendar) {
// this is an expensive function, only execute if the calendar is open
return
}
const renderedDate = this.state.renderedDate
// Sets it to the first local day of the week counting back from the start of the month.
// Note that first day depends on the locale, e.g. it's Sunday in the US and
// Monday in most of the EU.
const currDate = DateTime.getFirstDayOfWeek(renderedDate.startOf('month'))
const arr: Moment[] = []
for (let i = 0; i < Calendar.DAY_COUNT; i++) {
arr.push(currDate.clone())
currDate.add({ days: 1 })
}
return arr.map((date) => {
const dateStr = date.toISOString()
return (
<DateInput.Day
key={dateStr}
date={dateStr}
isSelected={
this.state.calendarSelectedDate
? date.isSame(this.state.calendarSelectedDate, 'day')
: false
}
isToday={date.isSame(
DateTime.now(this.locale(), this.timezone()),
'day'
)}
isOutsideMonth={!date.isSame(renderedDate, 'month')}
label={date.format('D MMMM YYYY')} // used by screen readers
onClick={this.handleDayClick}
>
{date.format('DD')}
</DateInput.Day>
)
})
}
// The default weekdays rendered in the calendar
get defaultWeekdays() {
if (!this.state.isShowingCalendar) {
// this is an expensive function, only execute if the calendar is open
return []
}
const shortDayNames = DateTime.getLocalDayNamesOfTheWeek(
this.locale(),
'short'
)
const longDayNames = DateTime.getLocalDayNamesOfTheWeek(
this.locale(),
'long'
)
return [
<AccessibleContent key={1} alt={longDayNames[0]}>
{shortDayNames[0]}
</AccessibleContent>,
<AccessibleContent key={2} alt={longDayNames[1]}>
{shortDayNames[1]}
</AccessibleContent>,
<AccessibleContent key={3} alt={longDayNames[2]}>
{shortDayNames[2]}
</AccessibleContent>,
<AccessibleContent key={4} alt={longDayNames[3]}>
{shortDayNames[3]}
</AccessibleContent>,
<AccessibleContent key={5} alt={longDayNames[4]}>
{shortDayNames[4]}
</AccessibleContent>,
<AccessibleContent key={6} alt={longDayNames[5]}>
{shortDayNames[5]}
</AccessibleContent>,
<AccessibleContent key={7} alt={longDayNames[6]}>
{shortDayNames[6]}
</AccessibleContent>
]
}
renderNextPrevMonthButton(type: 'prev' | 'next') {
if (!this.state.isShowingCalendar) {
return
}
return (
<IconButton
size="small"
withBackground={false}
withBorder={false}
renderIcon={
type === 'prev' ? (
<IconArrowOpenStartSolid color="primary" />
) : (
<IconArrowOpenEndSolid color="primary" />
)
}
screenReaderLabel={
type === 'prev'
? this.props.prevMonthLabel
: this.props.nextMonthLabel
}
/>
)
}
render() {
const {
description,
datePlaceholder,
dateRenderLabel,
dateInputRef,
timeRenderLabel,
timeFormat,
timeStep,
timeInputRef,
locale,
timezone,
messages,
layout,
isRequired,
interaction,
renderWeekdayLabels
} = this.props
return (
<FormFieldGroup
description={description}
colSpacing="medium"
rowSpacing="small"
layout={layout}
vAlign="top"
elementRef={this.handleRef}
messages={[
...(this.state.message ? [this.state.message] : []),
...(messages || [])
]}
>
<DateInput
value={this.state.dateInputText}
onChange={this.handleDateTextChange}
onBlur={this.handleBlur}
inputRef={dateInputRef}
placeholder={datePlaceholder}
renderLabel={dateRenderLabel}
renderWeekdayLabels={
renderWeekdayLabels ? renderWeekdayLabels : this.defaultWeekdays
}
onRequestShowCalendar={this.handleShowCalendar}
// debounce is needed here because handleDayClick updates calendarSelectedDate
// and this is read in handleHideCalendar
onRequestHideCalendar={debounce(this.handleHideCalendar)}
isShowingCalendar={this.state.isShowingCalendar}
renderNextMonthButton={this.renderNextPrevMonthButton('next')}
renderPrevMonthButton={this.renderNextPrevMonthButton('prev')}
onRequestSelectNextDay={this.handleSelectNextDay}
onRequestSelectPrevDay={this.handleSelectPrevDay}
onRequestRenderNextMonth={this.handleRenderNextMonth}
onRequestRenderPrevMonth={this.handleRenderPrevMonth}
isRequired={isRequired}
interaction={interaction}
renderNavigationLabel={
<span>
<div>{this.state.renderedDate.format('MMMM')}</div>
<div>{this.state.renderedDate.format('y')}</div>
</span>
}
>
{this.renderDays()}
</DateInput>
<TimeSelect
value={this.state.timeSelectValue}
onChange={this.handleTimeChange}
onBlur={this.handleBlur}
ref={this.timeInputComponentRef}
renderLabel={timeRenderLabel}
locale={locale}
format={timeFormat}
step={timeStep}
timezone={timezone}
inputRef={timeInputRef}
interaction={interaction}
/>
</FormFieldGroup>
)
}
}
export default DateTimeInput
export { DateTimeInput } | the_stack |
import * as React from 'react'
import { DateTime, Settings } from 'luxon'
import * as d3 from 'd3'
import * as ChartClient from '../ChartClient';
import * as ChartUtils from './Components/ChartUtils';
import { translate, scale, rotate, skewX, skewY, matrix, scaleFor } from './Components/ChartUtils';
import { ChartRow } from '../ChartClient';
import { Rule } from './Components/Rule';
import InitialMessage from './Components/InitialMessage';
import { MemoRepository } from './Components/ReactChart';
import { ChartRequestModel } from '../Signum.Entities.Chart';
import { DashboardFilter } from '../../Dashboard/View/DashboardFilterController';
export default function renderCalendarStream({ data, width, height, parameters, loading, onDrillDown, initialLoad, dashboardFilter, chartRequest }: ChartClient.ChartScriptProps): React.ReactElement<any> {
if (data == null || data.rows.length == 0)
return (
<svg direction="ltr" width={width} height={height}>
<InitialMessage data={data} x={width / 2} y={height / 2} loading={loading} />
</svg>
);
var dateColumn = data.columns.c0! as ChartClient.ChartColumn<string>;
var valueColumn = data.columns.c1 as ChartClient.ChartColumn<number>;
var monday = parameters["StartDate"] == "Monday"
var scaleFunc = scaleFor(valueColumn, data.rows.map(r => valueColumn.getValue(r)), 0, 1, parameters["ColorScale"]);
var colorInterpolate = parameters["ColorInterpolate"];
var colorInterpolation = ChartUtils.getColorInterpolation(colorInterpolate)!;
var color = (r: ChartRow) => colorInterpolation(scaleFunc(valueColumn.getValue(r))!);
var minDate = d3.min(data.rows, r => new Date(dateColumn.getValue(r)))!;
var maxDate = d3.max(data.rows, r => new Date(dateColumn.getValue(r)))!;
var years = d3.range(minDate.getFullYear(), maxDate.getFullYear() + 1);
function getRules(weeksSize: number, daysSize: number): Rules {
var weeksRule = Rule.create({
_1: 4,
yearTitle: 14,
_2: 4,
weekDayTitle: 14,
_3: 4,
weeksContent: '*',
_4: 4,
}, weeksSize);
var daysRule = Rule.create({
_1: 4,
monthTitle: 14,
_3: 4,
daysContent: '*',
_4: 4,
}, daysSize);
var cellSizeWeeks = weeksRule.size("weeksContent") / 53;
var cellSizeDays = daysRule.size("daysContent") / 7;
var cellSize: number;
if (cellSizeWeeks < cellSizeDays) {
cellSize = cellSizeWeeks;
daysRule = Rule.create({
_1: 4,
monthTitle: 14,
_3: 4,
daysContent: cellSizeWeeks * 7,
_4: 4,
});
}
else {
cellSize = cellSizeDays;
weeksRule = Rule.create({
_1: 4,
yearTitle: 14,
_2: 4,
weekDayTitle: 14,
_3: 4,
weeksContent: cellSizeDays * 53,
_4: 4,
});
}
return {
cellSize,
weeksRule,
daysRule
};
}
var vertical = getRules(height, width / years.length);
var horizontal = getRules(width, height / years.length);
var rules = vertical.cellSize > horizontal.cellSize ? vertical : horizontal;
var rowByDate = data.rows.toObject(r => {
var date = dateColumn.getValueKey(r);
return date.tryBefore("T") ?? date;
});
var xRule = Rule.create({
_1: '*',
content: rules == vertical ? rules.daysRule.totalSize * years.length : rules.weeksRule.totalSize,
_2: '*',
}, width);
var yRule = Rule.create({
_1: '*',
content: rules == vertical ? rules.weeksRule.totalSize : rules.daysRule.totalSize * years.length,
_2: '*',
}, height);
return (
<svg direction="ltr" width={width} height={height}>
<g transform={translate(xRule.start("content"), yRule.start("content"))}>
{years.map((yr, i) => <CalendarYear key={yr}
transform={rules == vertical ?
translate(i * rules.daysRule.totalSize, 0) :
translate(0, i * rules.daysRule.totalSize) + rotate(-90) + translate(-rules.daysRule.totalSize, 0)
}
year={yr}
rules={rules}
rowByDate={rowByDate}
width={width}
height={height}
onDrillDown={onDrillDown}
initialLoad={initialLoad}
monday={monday}
valueColumn={valueColumn}
color={color}
isHorizontal={rules == horizontal}
dashboardFilter={dashboardFilter}
chartRequest={chartRequest} />)}
</g>
{/*{xRule.debugX()}*/}
{/*{yRule.debugY()}*/}
</svg>
);
}
interface Rules {
cellSize: number;
weeksRule: Rule<"yearTitle" | "weekDayTitle" | "weeksContent">;
daysRule: Rule<"monthTitle" | "daysContent">;
}
export function CalendarYear({ year, rules, rowByDate, width, height, onDrillDown, initialLoad, transform, monday, valueColumn, color, isHorizontal, dashboardFilter, chartRequest }: {
year: number;
rowByDate: { [date: string] : ChartRow }
rules: Rules;
data?: ChartClient.ChartTable;
onDrillDown: (row: ChartRow, e: React.MouseEvent<any> | MouseEvent) => void;
width: number;
height: number;
initialLoad: boolean;
isHorizontal: boolean;
transform: string;
monday: boolean;
valueColumn: ChartClient.ChartColumn<number>
color: (cr: ChartRow) => string;
dashboardFilter?: DashboardFilter,
chartRequest: ChartRequestModel
}) {
var cellSize = rules.cellSize;
var dayString = d3.timeFormat("%w");
var day = !monday ?
(d: Date) => parseInt(dayString(d)) :
(d: Date) => {
var old = parseInt(dayString(d));
return old == 0 ? 6 : old - 1;
};
var weekString = d3.timeFormat("%U");
var week = !monday ?
(d: Date) => parseInt(weekString(d)) :
(d: Date) => parseInt(dayString(d)) == 0 ? parseInt(weekString(d)) - 1 : parseInt(weekString(d));
var cleanDate = (d: Date) => d.toJSON().before("T");
function monthPath(t0: Date): string {
var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
d0 = +day(t0), w0 = +week(t0),
d1 = +day(t1), w1 = +week(t1);
return "M" + d0 * cellSize + "," + (w0) * cellSize
+ "V" + (w0 + 1) * cellSize + "H" + 0
+ "V" + (w1 + 1) * cellSize + "H" + (d1 + 1) * cellSize
+ "V" + (w1) * cellSize + "H" + 7 * cellSize
+ "V" + (w0) * cellSize + "Z";
}
var dateFormat = d3.timeFormat("%Y-%m-%d");
var monthNames = getMonthsNames();
var weekdayNames = getWeekDayNames(monday);
function monthPosition(i: number) {
var firstDay = week(DateTime.local(year, i, 1).toJSDate());
var lastDay = week(DateTime.local(year, i, 1).plus({ month: 1, day: -1 }).toJSDate());
return (firstDay + lastDay) / 2.0;
}
var detector = dashboardFilter?.getActiveDetector(chartRequest);
return (
<g key={year} className="year-group sf-transition"
transform={transform}>
<text transform={translate(rules.daysRule.middle("daysContent"), rules.weeksRule.end("yearTitle"))} textAnchor="middle" opacity={detector ? .5 : undefined}>
{year}
</text>
<g transform={translate(rules.daysRule.start("daysContent"), rules.weeksRule.end("weekDayTitle"))} textAnchor="middle" opacity={detector ? .5 : undefined}>
{weekdayNames.map((wdn, i) => <text key={i} transform={translate((i + 0.5) * cellSize, 0)} textAnchor="middle" opacity={detector ? .5 : undefined} fontSize="10">
{wdn}
</text>)
}
</g>
<g transform={translate(rules.daysRule.middle("monthTitle"), rules.weeksRule.start("weeksContent"))} textAnchor="middle" opacity={detector ? .5 : undefined}>
{monthNames.map((month, i) => <text key={i} transform={translate(0, (monthPosition(i + 1) + 0.5) * cellSize) + (isHorizontal ? rotate(90) :"") } textAnchor="middle" dominantBaseline="middle" opacity={detector ? .5 : undefined} fontSize="10">
{month}
</text>)
}
</g>
<g transform={translate(rules.daysRule.start("daysContent"), rules.weeksRule.start("weeksContent"))}>
{d3.utcDays(new Date(Date.UTC(year, 0, 1)), new Date(Date.UTC(year + 1, 0, 1))).map(d => {
const r: ChartRow | undefined = rowByDate[cleanDate(d)];
const active = r && detector?.(r);
return <rect key={d.toISOString()}
className="sf-transition"
opacity={active == false ? .5 : undefined}
stroke={active == true ? "black" : "#ccc"}
strokeWidth={active == true ? 2 : undefined}
fill={r == undefined || initialLoad ? "#fff" : color(r)}
width={cellSize}
height={cellSize}
x={day(d) * cellSize}
y={week(d) * cellSize}
cursor="pointer"
onClick={e => r == undefined ? null : onDrillDown(r, e)}>
<title>
{dateFormat(d) + (r == undefined ? "" : ("(" + valueColumn.getValueNiceName(r) + ")"))}
</title>
</rect>
})}
</g>
<g transform={translate(rules.daysRule.start("daysContent"), rules.weeksRule.start("weeksContent"))} opacity={detector ? .5 : undefined} >
{d3.timeMonths(new Date(year, 0, 1), new Date(year + 1, 0, 1))
.map(m => <path key={m.toString()}
className="month"
stroke="#666"
strokeWidth={1}
fill="none"
d={monthPath(m)} />
)
}
</g>
{/*{rules.daysRule.debugX(rules.weeksRule.totalSize)}*/}
{/*{rules.weeksRule.debugY(rules.daysRule.totalSize)}*/}
</g>
);
}
function getMonthsNames() {
var format = new Intl.DateTimeFormat(Settings.defaultLocale, { month: "short" });
var months = []
for (var month = 0; month < 12; month++) {
var testDate = new Date(Date.UTC(2000, month, 1, 0, 0, 0));
months.push(format.format(testDate))
}
return months;
}
function getWeekDayNames(monday: boolean) {
var format = new Intl.DateTimeFormat(Settings.defaultLocale, { weekday: "narrow" });
var months = []
for (var day = 0; day < 7; day++) {
var testDate = new Date(Date.UTC(2000, 0, 3 + day + (monday ? 0 : -1), 0, 0, 0));
months.push(format.format(testDate))
}
return months;
} | 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 } from 'chord/music/common/size';
import {
makeDemoAudio,
makeAudio,
makeEpisode,
makeEpisodes,
makePodcast,
makePodcasts,
makeRadio,
makeRadios,
makePodcastListOptions,
makePodcastOptionSubs,
} from 'chord/sound/ximalaya/parser';
import { getXmSign } from 'chord/sound/ximalaya/crypto';
export class XimalayaApi {
static readonly SERVER = 'https://www.ximalaya.com/';
static readonly HEADERS = {
'Referer': 'https://www.ximalaya.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: 'revision/track/trackPageInfo',
podcast: 'revision/album',
podcastEpisodes: 'revision/album/getTracksList',
search: 'revision/search',
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(node: string, params: object, url: string = XimalayaApi.SERVER): Promise<any> {
let paramstr = querystringify(params);
url = url + node + '?' + paramstr;
let headers = { ...XimalayaApi.HEADERS, 'xm-sign': getXmSign() };
let options: IRequestOptions = {
method: 'GET',
url,
headers,
gzip: true,
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('[XimalayaApi.request] [Error]: (params, response):', options, json);
}
return json;
}
/**
* Error:
* "ret":726, "msg":"立即购买畅听"
*/
public async demoAudios(episodeId: string): Promise<IAudio> {
let json = await this.request(
XimalayaApi.NODE_MAP.demoAudio + '/' + episodeId,
{
device: 'pc',
isBackend: 'false',
_: Date.now(),
},
'https://mpay.ximalaya.com/',
);
if (json.ret == 726) return null;
let audio = makeDemoAudio(json);
return audio;
}
public async audios(episodeId: string, supKbps?: number): Promise<Array<IAudio>> {
let json = await this.request(
XimalayaApi.NODE_MAP.audio,
{ trackIds: episodeId },
);
let audio;
let url = json.data.tracksForAudioPlay[0].src;
if (url) {
audio = makeAudio(url);
} else {
audio = await this.demoAudios(episodeId);
};
return audio ? [audio] : [];
}
public async episode(episodeId: string): Promise<IEpisode> {
let json = await this.request(
XimalayaApi.NODE_MAP.episode,
{ trackId: episodeId },
);
return makeEpisode(json.data);
}
public async podcast(podcastId: string): Promise<IPodcast> {
let json = await this.request(
XimalayaApi.NODE_MAP.podcast,
{ albumId: podcastId },
);
return makePodcast(json.data);
}
public async podcastEpisodeCount(podcastId: string): Promise<number> {
let json = await this.request(
XimalayaApi.NODE_MAP.podcastEpisodes,
{
albumId: podcastId,
pageNum: 1,
sort: 1,
},
);
return json.data.trackTotalCount;
}
// order:
// 0 正序
// 1 倒序
public async podcastEpisodes(podcastId: string, page: number = 1, order: string = '1'): Promise<Array<IEpisode>> {
let json = await this.request(
XimalayaApi.NODE_MAP.podcastEpisodes,
{
albumId: podcastId,
pageNum: page,
sort: order,
},
);
let episodes = makeEpisodes(json.data.tracks);
if (episodes.length == 0) return [];
for (let episode of episodes) {
try {
// Some episodes are not avaiable
let tmp_episode = await this.episode(episode.episodeOriginalId);
let {
radioId,
radioOriginalId,
radioName,
radioCoverUrl,
podcastName,
podcastCoverUrl,
description,
} = tmp_episode;
return episodes.map(s => ({
...s,
radioId,
radioOriginalId,
radioName,
radioCoverUrl,
podcastName,
podcastCoverUrl,
description,
}));
} catch {
continue;
}
}
return [];
}
public async search(type: string, keyword: string, page: number = 1, size: number = 10): Promise<any> {
let json = await this.request(
XimalayaApi.NODE_MAP.search,
{
core: type,
kw: keyword,
page,
rows: size,
spellchecker: 'true',
condition: 'relation', // play, recent
device: 'iPhone',
},
);
return json;
}
public async searchEpisodes(keyword: string, page: number = 1, size: number = 10): Promise<Array<IEpisode>> {
let json = await this.search('track', keyword, page, size);
return makeEpisodes(json.data.result.response.docs);
}
public async searchPodcasts(keyword: string, page: number = 1, size: number = 10): Promise<Array<IPodcast>> {
let json = await this.search('album', keyword, page, size);
return makePodcasts(json.data.result.response.docs);
}
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(
XimalayaApi.NODE_MAP.radioBasic,
{
uid: radioId,
},
);
let radio = makeRadio(json.data);
json = await this.request(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.NODE_MAP.podcastListOptions,
{},
);
return makePodcastListOptions(json.data);
}
public async podcastOptionSubs(category: string, subCategory: string): Promise<Array<IListOption>> {
let json = await this.request(
XimalayaApi.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(
XimalayaApi.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(
XimalayaApi.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 (size < ESize.Middle) {
// Big
return url + '!strip=1&quality=7&magick=webp&op_type=5&upload_type=album&name=mobile_large&device_type=ios';
} else {
// small
return url + '!strip=1&quality=7&magick=webp&op_type=5&upload_type=cover&name=web_large&device_type=ios';
}
}
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
[/\w+\/\d+\/(\d+)/, 'episode'],
// podcast
[/\w+\/(\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 |
import { Result, asyncResult, result, enforceAsyncResult } from '@expo/results';
import invariant from 'invariant';
import Entity, { IEntityClass } from './Entity';
import { EntityCompanionDefinition } from './EntityCompanionProvider';
import EntityConfiguration from './EntityConfiguration';
import EntityDatabaseAdapter from './EntityDatabaseAdapter';
import { EntityEdgeDeletionBehavior } from './EntityFieldDefinition';
import EntityLoaderFactory from './EntityLoaderFactory';
import {
EntityValidatorMutationInfo,
EntityMutationType,
EntityTriggerMutationInfo,
EntityMutationTriggerDeleteCascadeInfo,
} from './EntityMutationInfo';
import EntityMutationTriggerConfiguration, {
EntityMutationTrigger,
EntityNonTransactionalMutationTrigger,
} from './EntityMutationTriggerConfiguration';
import EntityMutationValidator from './EntityMutationValidator';
import EntityPrivacyPolicy from './EntityPrivacyPolicy';
import { EntityQueryContext, EntityTransactionalQueryContext } from './EntityQueryContext';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
import EntityInvalidFieldValueError from './errors/EntityInvalidFieldValueError';
import { timeAndLogMutationEventAsync } from './metrics/EntityMetricsUtils';
import IEntityMetricsAdapter, { EntityMetricsMutationType } from './metrics/IEntityMetricsAdapter';
import { mapMapAsync } from './utils/collections/maps';
abstract class BaseMutator<
TFields,
TID extends NonNullable<TFields[TSelectedFields]>,
TViewerContext extends ViewerContext,
TEntity extends Entity<TFields, TID, TViewerContext, TSelectedFields>,
TPrivacyPolicy extends EntityPrivacyPolicy<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
TSelectedFields extends keyof TFields
> {
constructor(
protected readonly viewerContext: TViewerContext,
protected readonly queryContext: EntityQueryContext,
protected readonly entityConfiguration: EntityConfiguration<TFields>,
protected readonly entityClass: IEntityClass<
TFields,
TID,
TViewerContext,
TEntity,
TPrivacyPolicy,
TSelectedFields
>,
protected readonly privacyPolicy: TPrivacyPolicy,
protected readonly mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[],
protected readonly mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
protected readonly entityLoaderFactory: EntityLoaderFactory<
TFields,
TID,
TViewerContext,
TEntity,
TPrivacyPolicy,
TSelectedFields
>,
protected readonly databaseAdapter: EntityDatabaseAdapter<TFields>,
protected readonly metricsAdapter: IEntityMetricsAdapter
) {}
protected validateFields(fields: Partial<TFields>): void {
for (const fieldName in fields) {
const fieldValue = fields[fieldName];
const fieldDefinition = this.entityConfiguration.schema.get(fieldName);
invariant(fieldDefinition, `must have field definition for field = ${fieldName}`);
const isInputValid = fieldDefinition.validateInputValue(fieldValue);
if (!isInputValid) {
throw new EntityInvalidFieldValueError(this.entityClass, fieldName, fieldValue);
}
}
}
protected async executeMutationValidatorsAsync(
validators: EntityMutationValidator<TFields, TID, TViewerContext, TEntity, TSelectedFields>[],
queryContext: EntityTransactionalQueryContext,
entity: TEntity,
mutationInfo: EntityValidatorMutationInfo<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>
): Promise<void> {
await Promise.all(
validators.map((validator) =>
validator.executeAsync(this.viewerContext, queryContext, entity, mutationInfo)
)
);
}
protected async executeMutationTriggersAsync(
triggers:
| EntityMutationTrigger<TFields, TID, TViewerContext, TEntity, TSelectedFields>[]
| undefined,
queryContext: EntityTransactionalQueryContext,
entity: TEntity,
mutationInfo: EntityTriggerMutationInfo<TFields, TID, TViewerContext, TEntity, TSelectedFields>
): Promise<void> {
if (!triggers) {
return;
}
await Promise.all(
triggers.map((trigger) =>
trigger.executeAsync(this.viewerContext, queryContext, entity, mutationInfo)
)
);
}
protected async executeNonTransactionalMutationTriggersAsync(
triggers:
| EntityNonTransactionalMutationTrigger<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[]
| undefined,
entity: TEntity,
mutationInfo: EntityTriggerMutationInfo<TFields, TID, TViewerContext, TEntity, TSelectedFields>
): Promise<void> {
if (!triggers) {
return;
}
await Promise.all(
triggers.map((trigger) => trigger.executeAsync(this.viewerContext, entity, mutationInfo))
);
}
}
/**
* Mutator for creating a new entity.
*/
export class CreateMutator<
TFields,
TID extends NonNullable<TFields[TSelectedFields]>,
TViewerContext extends ViewerContext,
TEntity extends Entity<TFields, TID, TViewerContext, TSelectedFields>,
TPrivacyPolicy extends EntityPrivacyPolicy<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
TSelectedFields extends keyof TFields
> extends BaseMutator<TFields, TID, TViewerContext, TEntity, TPrivacyPolicy, TSelectedFields> {
private readonly fieldsForEntity: Partial<TFields> = {};
/**
* Set the value for entity field.
* @param fieldName - entity field being updated
* @param value - value for entity field
*/
setField<K extends keyof Pick<TFields, TSelectedFields>>(fieldName: K, value: TFields[K]): this {
this.fieldsForEntity[fieldName] = value;
return this;
}
/**
* Commit the new entity after authorizing against creation privacy rules. Invalidates all caches for
* queries that would return new entity and caches the new entity if not in a transactional query context.
* @returns authorized, cached, newly-created entity result, where result error can be UnauthorizedError
*/
async createAsync(): Promise<Result<TEntity>> {
return await timeAndLogMutationEventAsync(
this.metricsAdapter,
EntityMetricsMutationType.CREATE,
this.entityClass.name
)(this.createInTransactionAsync());
}
/**
* Convenience method that returns the new entity or throws upon create failure.
*/
async enforceCreateAsync(): Promise<TEntity> {
return await enforceAsyncResult(this.createAsync());
}
private async createInTransactionAsync(): Promise<Result<TEntity>> {
return await this.queryContext.runInTransactionIfNotInTransactionAsync((innerQueryContext) =>
this.createInternalAsync(innerQueryContext)
);
}
private async createInternalAsync(
queryContext: EntityTransactionalQueryContext
): Promise<Result<TEntity>> {
this.validateFields(this.fieldsForEntity);
const temporaryEntityForPrivacyCheck = new this.entityClass(this.viewerContext, {
[this.entityConfiguration.idField]: '00000000-0000-0000-0000-000000000000', // zero UUID
...this.fieldsForEntity,
} as unknown as TFields);
const authorizeCreateResult = await asyncResult(
this.privacyPolicy.authorizeCreateAsync(
this.viewerContext,
queryContext,
temporaryEntityForPrivacyCheck,
this.metricsAdapter
)
);
if (!authorizeCreateResult.ok) {
return authorizeCreateResult;
}
await this.executeMutationValidatorsAsync(
this.mutationValidators,
queryContext,
temporaryEntityForPrivacyCheck,
{ type: EntityMutationType.CREATE }
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.beforeAll,
queryContext,
temporaryEntityForPrivacyCheck,
{ type: EntityMutationType.CREATE }
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.beforeCreate,
queryContext,
temporaryEntityForPrivacyCheck,
{ type: EntityMutationType.CREATE }
);
const insertResult = await this.databaseAdapter.insertAsync(queryContext, this.fieldsForEntity);
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, queryContext);
queryContext.appendPostCommitInvalidationCallback(
entityLoader.invalidateFieldsAsync.bind(entityLoader, insertResult)
);
const unauthorizedEntityAfterInsert = new this.entityClass(this.viewerContext, insertResult);
const newEntity = await entityLoader
.enforcing()
.loadByIDAsync(unauthorizedEntityAfterInsert.getID());
await this.executeMutationTriggersAsync(
this.mutationTriggers.afterCreate,
queryContext,
newEntity,
{ type: EntityMutationType.CREATE }
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.afterAll,
queryContext,
newEntity,
{ type: EntityMutationType.CREATE }
);
queryContext.appendPostCommitCallback(
this.executeNonTransactionalMutationTriggersAsync.bind(
this,
this.mutationTriggers.afterCommit,
newEntity,
{ type: EntityMutationType.CREATE }
)
);
return result(newEntity);
}
}
/**
* Mutator for updating an existing entity.
*/
export class UpdateMutator<
TFields,
TID extends NonNullable<TFields[TSelectedFields]>,
TViewerContext extends ViewerContext,
TEntity extends Entity<TFields, TID, TViewerContext, TSelectedFields>,
TPrivacyPolicy extends EntityPrivacyPolicy<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
TSelectedFields extends keyof TFields
> extends BaseMutator<TFields, TID, TViewerContext, TEntity, TPrivacyPolicy, TSelectedFields> {
private readonly originalEntity: TEntity;
private readonly fieldsForEntity: TFields;
private readonly updatedFields: Partial<TFields> = {};
constructor(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entityConfiguration: EntityConfiguration<TFields>,
entityClass: IEntityClass<
TFields,
TID,
TViewerContext,
TEntity,
TPrivacyPolicy,
TSelectedFields
>,
privacyPolicy: TPrivacyPolicy,
mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[],
mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
entityLoaderFactory: EntityLoaderFactory<
TFields,
TID,
TViewerContext,
TEntity,
TPrivacyPolicy,
TSelectedFields
>,
databaseAdapter: EntityDatabaseAdapter<TFields>,
metricsAdapter: IEntityMetricsAdapter,
originalEntity: TEntity
) {
super(
viewerContext,
queryContext,
entityConfiguration,
entityClass,
privacyPolicy,
mutationValidators,
mutationTriggers,
entityLoaderFactory,
databaseAdapter,
metricsAdapter
);
this.originalEntity = originalEntity;
this.fieldsForEntity = { ...originalEntity.getAllDatabaseFields() };
}
/**
* Set the value for entity field.
* @param fieldName - entity field being updated
* @param value - value for entity field
*/
setField<K extends keyof Pick<TFields, TSelectedFields>>(fieldName: K, value: TFields[K]): this {
this.fieldsForEntity[fieldName] = value;
this.updatedFields[fieldName] = value;
return this;
}
/**
* Commit the changes to the entity after authorizing against update privacy rules.
* Invalidates all caches for pre-update entity and caches the updated entity if not in a
* transactional query context.
* @returns authorized updated entity result, where result error can be UnauthorizedError
*/
async updateAsync(): Promise<Result<TEntity>> {
return await timeAndLogMutationEventAsync(
this.metricsAdapter,
EntityMetricsMutationType.UPDATE,
this.entityClass.name
)(this.updateInTransactionAsync());
}
/**
* Convenience method that returns the updated entity or throws upon update failure.
*/
async enforceUpdateAsync(): Promise<TEntity> {
return await enforceAsyncResult(this.updateAsync());
}
private async updateInTransactionAsync(): Promise<Result<TEntity>> {
return await this.queryContext.runInTransactionIfNotInTransactionAsync((innerQueryContext) =>
this.updateInternalAsync(innerQueryContext)
);
}
private async updateInternalAsync(
queryContext: EntityTransactionalQueryContext
): Promise<Result<TEntity>> {
this.validateFields(this.updatedFields);
const entityAboutToBeUpdated = new this.entityClass(this.viewerContext, this.fieldsForEntity);
const authorizeUpdateResult = await asyncResult(
this.privacyPolicy.authorizeUpdateAsync(
this.viewerContext,
queryContext,
entityAboutToBeUpdated,
this.metricsAdapter
)
);
if (!authorizeUpdateResult.ok) {
return authorizeUpdateResult;
}
await this.executeMutationValidatorsAsync(
this.mutationValidators,
queryContext,
entityAboutToBeUpdated,
{ type: EntityMutationType.UPDATE, previousValue: this.originalEntity }
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.beforeAll,
queryContext,
entityAboutToBeUpdated,
{ type: EntityMutationType.UPDATE, previousValue: this.originalEntity }
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.beforeUpdate,
queryContext,
entityAboutToBeUpdated,
{ type: EntityMutationType.UPDATE, previousValue: this.originalEntity }
);
const updateResult = await this.databaseAdapter.updateAsync(
queryContext,
this.entityConfiguration.idField,
entityAboutToBeUpdated.getID(),
this.updatedFields
);
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, queryContext);
queryContext.appendPostCommitInvalidationCallback(
entityLoader.invalidateFieldsAsync.bind(
entityLoader,
this.originalEntity.getAllDatabaseFields()
)
);
queryContext.appendPostCommitInvalidationCallback(
entityLoader.invalidateFieldsAsync.bind(entityLoader, this.fieldsForEntity)
);
const unauthorizedEntityAfterUpdate = new this.entityClass(this.viewerContext, updateResult);
const updatedEntity = await entityLoader
.enforcing()
.loadByIDAsync(unauthorizedEntityAfterUpdate.getID());
await this.executeMutationTriggersAsync(
this.mutationTriggers.afterUpdate,
queryContext,
updatedEntity,
{ type: EntityMutationType.UPDATE, previousValue: this.originalEntity }
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.afterAll,
queryContext,
updatedEntity,
{ type: EntityMutationType.UPDATE, previousValue: this.originalEntity }
);
queryContext.appendPostCommitCallback(
this.executeNonTransactionalMutationTriggersAsync.bind(
this,
this.mutationTriggers.afterCommit,
updatedEntity,
{ type: EntityMutationType.UPDATE, previousValue: this.originalEntity }
)
);
return result(updatedEntity);
}
}
/**
* Mutator for deleting an existing entity.
*/
export class DeleteMutator<
TFields,
TID extends NonNullable<TFields[TSelectedFields]>,
TViewerContext extends ViewerContext,
TEntity extends Entity<TFields, TID, TViewerContext, TSelectedFields>,
TPrivacyPolicy extends EntityPrivacyPolicy<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
TSelectedFields extends keyof TFields
> extends BaseMutator<TFields, TID, TViewerContext, TEntity, TPrivacyPolicy, TSelectedFields> {
constructor(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entityConfiguration: EntityConfiguration<TFields>,
entityClass: IEntityClass<
TFields,
TID,
TViewerContext,
TEntity,
TPrivacyPolicy,
TSelectedFields
>,
privacyPolicy: TPrivacyPolicy,
mutationValidators: EntityMutationValidator<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[],
mutationTriggers: EntityMutationTriggerConfiguration<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>,
entityLoaderFactory: EntityLoaderFactory<
TFields,
TID,
TViewerContext,
TEntity,
TPrivacyPolicy,
TSelectedFields
>,
databaseAdapter: EntityDatabaseAdapter<TFields>,
metricsAdapter: IEntityMetricsAdapter,
private readonly entity: TEntity
) {
super(
viewerContext,
queryContext,
entityConfiguration,
entityClass,
privacyPolicy,
mutationValidators,
mutationTriggers,
entityLoaderFactory,
databaseAdapter,
metricsAdapter
);
}
/**
* Delete the entity after authorizing against delete privacy rules. The entity is invalidated in all caches.
* @returns void result, where result error can be UnauthorizedError
*/
async deleteAsync(): Promise<Result<void>> {
return await timeAndLogMutationEventAsync(
this.metricsAdapter,
EntityMetricsMutationType.DELETE,
this.entityClass.name
)(this.deleteInTransactionAsync(new Set(), false, null));
}
/**
* Convenience method that throws upon delete failure.
*/
async enforceDeleteAsync(): Promise<void> {
return await enforceAsyncResult(this.deleteAsync());
}
private async deleteInTransactionAsync(
processedEntityIdentifiersFromTransitiveDeletions: Set<string>,
skipDatabaseDeletion: boolean,
cascadingDeleteCause: EntityMutationTriggerDeleteCascadeInfo | null
): Promise<Result<void>> {
return await this.queryContext.runInTransactionIfNotInTransactionAsync((innerQueryContext) =>
this.deleteInternalAsync(
innerQueryContext,
processedEntityIdentifiersFromTransitiveDeletions,
skipDatabaseDeletion,
cascadingDeleteCause
)
);
}
private async deleteInternalAsync(
queryContext: EntityTransactionalQueryContext,
processedEntityIdentifiersFromTransitiveDeletions: Set<string>,
skipDatabaseDeletion: boolean,
cascadingDeleteCause: EntityMutationTriggerDeleteCascadeInfo | null
): Promise<Result<void>> {
const authorizeDeleteResult = await asyncResult(
this.privacyPolicy.authorizeDeleteAsync(
this.viewerContext,
queryContext,
this.entity,
this.metricsAdapter
)
);
if (!authorizeDeleteResult.ok) {
return authorizeDeleteResult;
}
await this.processEntityDeletionForInboundEdgesAsync(
this.entity,
queryContext,
processedEntityIdentifiersFromTransitiveDeletions,
cascadingDeleteCause
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.beforeAll,
queryContext,
this.entity,
{ type: EntityMutationType.DELETE, cascadingDeleteCause }
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.beforeDelete,
queryContext,
this.entity,
{ type: EntityMutationType.DELETE, cascadingDeleteCause }
);
if (!skipDatabaseDeletion) {
await this.databaseAdapter.deleteAsync(
queryContext,
this.entityConfiguration.idField,
this.entity.getID()
);
}
const entityLoader = this.entityLoaderFactory.forLoad(this.viewerContext, queryContext);
queryContext.appendPostCommitInvalidationCallback(
entityLoader.invalidateFieldsAsync.bind(entityLoader, this.entity.getAllDatabaseFields())
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.afterDelete,
queryContext,
this.entity,
{ type: EntityMutationType.DELETE, cascadingDeleteCause }
);
await this.executeMutationTriggersAsync(
this.mutationTriggers.afterAll,
queryContext,
this.entity,
{ type: EntityMutationType.DELETE, cascadingDeleteCause }
);
queryContext.appendPostCommitCallback(
this.executeNonTransactionalMutationTriggersAsync.bind(
this,
this.mutationTriggers.afterCommit,
this.entity,
{ type: EntityMutationType.DELETE, cascadingDeleteCause }
)
);
return result();
}
/**
* Finds all entities referencing the specified entity and either deletes them, nullifies
* their references to the specified entity, or invalidates the cache depending on the
* {@link OnDeleteBehavior} of the field referencing the specified entity.
*
* @remarks
* This works by doing reverse fan-out queries:
* 1. Load all entity configurations of entity types that reference this type of entity
* 2. For each entity configuration, find all fields that contain edges to this type of entity
* 3. For each edge field, load all entities with an edge from target entity to this entity via that field
* 4. Perform desired OnDeleteBehavior for entities
*
* @param entity - entity to find all references to
*/
private async processEntityDeletionForInboundEdgesAsync(
entity: TEntity,
queryContext: EntityTransactionalQueryContext,
processedEntityIdentifiers: Set<string>,
cascadingDeleteCause: EntityMutationTriggerDeleteCascadeInfo | null
): Promise<void> {
// prevent infinite reference cycles by keeping track of entities already processed
if (processedEntityIdentifiers.has(entity.getUniqueIdentifier())) {
return;
}
processedEntityIdentifiers.add(entity.getUniqueIdentifier());
const companionDefinition = (
entity.constructor as any
).getCompanionDefinition() as EntityCompanionDefinition<
TFields,
TID,
TViewerContext,
TEntity,
TPrivacyPolicy,
TSelectedFields
>;
const entityConfiguration = companionDefinition.entityConfiguration;
const inboundEdges = entityConfiguration.getInboundEdges();
await Promise.all(
inboundEdges.map(async (entityClass) => {
return await mapMapAsync(
entityClass.getCompanionDefinition().entityConfiguration.schema,
async (fieldDefinition, fieldName) => {
const association = fieldDefinition.association;
if (!association) {
return;
}
const associatedConfiguration = association
.getAssociatedEntityClass()
.getCompanionDefinition().entityConfiguration;
if (associatedConfiguration !== entityConfiguration) {
return;
}
const associatedEntityLookupByField = association.associatedEntityLookupByField;
const loaderFactory = entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(entityClass)
.getLoaderFactory();
const mutatorFactory = entity
.getViewerContext()
.getViewerScopedEntityCompanionForClass(entityClass)
.getMutatorFactory();
let inboundReferenceEntities: readonly ReadonlyEntity<any, any, any, any>[];
if (associatedEntityLookupByField) {
inboundReferenceEntities = await loaderFactory
.forLoad(queryContext)
.enforcing()
.loadManyByFieldEqualingAsync(
fieldName,
entity.getField(associatedEntityLookupByField as any)
);
} else {
inboundReferenceEntities = await loaderFactory
.forLoad(queryContext)
.enforcing()
.loadManyByFieldEqualingAsync(fieldName, entity.getID());
}
switch (association.edgeDeletionBehavior) {
case undefined:
case EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE: {
await Promise.all(
inboundReferenceEntities.map((inboundReferenceEntity) =>
mutatorFactory
.forDelete(inboundReferenceEntity, queryContext)
.deleteInTransactionAsync(
processedEntityIdentifiers,
/* skipDatabaseDeletion */ true, // deletion is handled by DB
{
entity,
cascadingDeleteCause,
}
)
)
);
break;
}
case EntityEdgeDeletionBehavior.SET_NULL: {
await Promise.all(
inboundReferenceEntities.map((inboundReferenceEntity) =>
mutatorFactory
.forUpdate(inboundReferenceEntity, queryContext)
.setField(fieldName, null)
.enforceUpdateAsync()
)
);
break;
}
case EntityEdgeDeletionBehavior.CASCADE_DELETE: {
await Promise.all(
inboundReferenceEntities.map((inboundReferenceEntity) =>
mutatorFactory
.forDelete(inboundReferenceEntity, queryContext)
.deleteInTransactionAsync(
processedEntityIdentifiers,
/* skipDatabaseDeletion */ false,
{
entity,
cascadingDeleteCause,
}
)
)
);
}
}
}
);
})
);
}
} | the_stack |
import { SqrlObject } from "../object/SqrlObject";
import bluebird = require("bluebird");
import { foreachObject } from "../jslib/foreachObject";
import invariant from "../jslib/invariant";
import isPromise from "../jslib/isPromise";
import util = require("util");
import { niceForEach } from "node-nice";
import SqrlSourcePrinter from "../compile/SqrlSourcePrinter";
import { RuleSpecMap } from "../api/spec";
import * as moment from "moment";
import { isValidFeatureName } from "../feature/FeatureName";
import { DatabaseSet, Context } from "../api/ctx";
import {
Manipulator,
ExecutionErrorProperties,
FeatureMap,
Execution,
} from "../api/execute";
import { SqrlBoxed } from "sqrl-common";
import { SourcePrinter } from "../api/executable";
export interface SqrlExecutionOptions {
featureTimeout: number;
ruleSpecs: RuleSpecMap;
requiredSlots?: number[];
sourcePrinter?: SqrlSourcePrinter;
slotCost?: number[];
}
export class SlotMissingCallbackError extends Error {
constructor(public slotName: string) {
super(`Could not find function to generate slot value:: ${slotName}`);
}
}
export class SqrlExecutionState implements Execution {
slots: bluebird<any>[];
names: string[];
functionCache;
counterBumps;
loggedCodedErrors: Set<string>;
sourcePrinter: SqrlSourcePrinter;
featureTimeout: number;
currentCost: number = 0;
public traceFunctions: boolean;
public databaseSet: DatabaseSet | null;
private clockMs: number = null;
public ruleSpecs: RuleSpecMap;
public ctx: Context;
private data = new Map();
_fetch: (slot: number) => bluebird<any>;
constructor(
ctx: Context,
slotCallbacks,
names = [],
public manipulator: Manipulator = null,
props: SqrlExecutionOptions,
features: FeatureMap
) {
this.ctx = ctx;
this.featureTimeout = props.featureTimeout;
this.slots = Array(slotCallbacks.length);
this.counterBumps = [];
this.names = names;
this.functionCache = {};
this.loggedCodedErrors = new Set();
this.databaseSet = ctx.requireDatabaseSet();
this.ruleSpecs = props.ruleSpecs;
// Depending on the type of execution these may be null
this.sourcePrinter = props.sourcePrinter || null;
const slotCost: number[] = props.slotCost;
this._fetch = (slotIdx: number) => {
const slotCalc = slotCallbacks[slotIdx];
if (!slotCalc) {
throw new SlotMissingCallbackError(this.names[slotIdx]);
}
this.currentCost += slotCost ? slotCost[slotIdx] : 0;
return slotCalc.call(this);
};
this.setFeatures(features);
(props.requiredSlots || []).forEach((index) => {
invariant(
this.slots[index],
"Slot %s required for execution",
this.names[index]
);
});
}
/**
* Fetch a value from the executions data cache
*/
get<T>(symbol: symbol, defaultValue?: T): T {
if (!this.data.has(symbol)) {
if (typeof defaultValue !== "undefined") {
return defaultValue;
}
throw new Error(
"Could not find symbol in executions data: " + symbol.toString()
);
}
return this.data.get(symbol);
}
/**
* Fetch a value from the executions data cache
*/
set<T>(symbol: symbol, value: T) {
this.data.set(symbol, value);
}
/**
* Get a value on the executions data, setting a default value if not set
*/
setDefault<T>(symbol: symbol, defaultValue?: T): T {
if (!this.data.has(symbol)) {
this.data.set(symbol, defaultValue);
}
return this.data.get(symbol);
}
async fetchClock() {
const clockValue = await this.fetchBasicByName("SqrlClock");
invariant(
clockValue !== null,
"fetchClock() could not fetch the SqrlClock feature"
);
const clockMoment = moment(clockValue, moment.ISO_8601);
invariant(
clockMoment.isValid(),
"Invalid ISO 8601 string provided as SqrlClock"
);
this.clockMs = clockMoment.valueOf();
}
/**
* Get the source code printer for the executable.
*/
getSourcePrinter(): SourcePrinter {
return this.sourcePrinter;
}
getClock() {
invariant(this.clockMs !== null, "Clock not fetched or unavailable");
return this.clockMs;
}
getClockMs() {
return this.getClock();
}
async fetchFeature(featureName: string): Promise<SqrlObject> {
const value = await this.fetchByName(featureName);
if (value instanceof SqrlObject) {
return value;
} else {
return new SqrlBoxed(value);
}
}
fetchValue(featureName: string): Promise<any> {
return Promise.resolve(this.fetchBasicByName(featureName));
}
// @TODO: Deprecate in place of cacheAccessor
functionCacheAccessor<T>(key: string, callback: () => T): T {
if (!this.functionCache.hasOwnProperty(key)) {
this.functionCache[key] = callback();
}
return this.functionCache[key];
}
cacheAccessor<T>(symbol: symbol, key: string, callback: () => T): T {
this.functionCache[symbol] = this.functionCache[symbol] || {};
if (!this.functionCache[symbol].hasOwnProperty(key)) {
this.functionCache[symbol][key] = callback();
}
return this.functionCache[symbol][key];
}
trace(props: { [key: string]: any }, format: string, ...args: Array<any>) {
return this.ctx.trace(props, format, ...args);
}
debug(props: { [key: string]: any }, format: string, ...args: Array<any>) {
return this.ctx.debug(props, format, ...args);
}
info(props: { [key: string]: any }, format: string, ...args: Array<any>) {
return this.ctx.info(props, format, ...args);
}
warn(props: { [key: string]: any }, format: string, ...args: Array<any>) {
return this.ctx.warn(props, format, ...args);
}
error(props: { [key: string]: any }, format: string, ...args: Array<any>) {
return this.ctx.error(props, format, ...args);
}
fatal(props: { [key: string]: any }, format: string, ...args: Array<any>) {
return this.ctx.fatal(props, format, ...args);
}
codedWarning(format: string, ...args: Array<any>) {
const message = util.format(format, ...args);
if (this.manipulator) {
this.manipulator.codedWarnings.push(message);
}
this.warn({}, message);
}
setFeatures(featureMap: FeatureMap) {
foreachObject(featureMap, (value, featureName) => {
const index = this.getSlot(featureName);
invariant(!isPromise(value), "setFeatures() does not work with promises");
invariant(
!this.slots[index],
"setFeatures() cannot overwrite loaded slots"
);
this.slots[index] = bluebird.resolve(value);
});
}
setFutureFeatures(featureMap) {
foreachObject(featureMap, (promise: bluebird<any>, featureName) => {
const index = this.getSlot(featureName);
invariant(
promise instanceof bluebird,
"setFutureFeatures() requires bluebird promises"
);
invariant(
!this.slots[index],
"setFutureFeatures() cannot overwrite loaded slots"
);
this.slots[index] = promise;
});
}
fetch(slot) {
let value = this.slots[slot];
if (!value) {
value = this._fetch(slot);
this.slots[slot] = value;
}
return value;
}
getFeatureNames() {
return this.names.filter(isValidFeatureName);
}
getSlot(name: string): number {
invariant(typeof name === "string", "Expected string name for getSlot()");
const index = this.names.indexOf(name);
invariant(index >= 0, "Could not find the requested name:: %s", name);
return index;
}
async tryWait(name: string): Promise<void> {
const index = this.names.indexOf(name);
if (index > 0) {
await this.build([index]);
}
}
fetchByName(name) {
return bluebird.resolve(this.fetchByName_(name));
}
async fetchByName_(name): Promise<any> {
return this.fetch(this.getSlot(name));
}
fetchBasicByName(name) {
return this.fetchByName(name).then((result) =>
SqrlObject.ensureBasic(result)
);
}
prepare(slotIndexes: number[]): bluebird<void> {
return bluebird.resolve(this.prepare_(slotIndexes));
}
prepare_(slotIndexes: number[]): Promise<void> {
return niceForEach(slotIndexes, (idx) => {
if (!this.slots[idx]) {
this.slots[idx] = this._fetch(idx);
}
});
}
wait(slotIndexes: number[]): bluebird<void> {
// Wait for a given list of slot indexes to be ready. They *must* have
// already been prepared before calling wait.
let currentSlotIndex = 0;
const wait = () => {
while (currentSlotIndex < slotIndexes.length) {
const slot = this.slots[slotIndexes[currentSlotIndex++]];
if (!slot.isResolved()) {
return slot.then(wait);
}
}
};
return wait() || bluebird.resolve();
}
build(slotIndexes: number[]): bluebird<void> {
// This ensures all the given slot indexes have been fetched
return this.prepare(slotIndexes).then(() => this.wait(slotIndexes));
}
load(slotIndexes) {
// Fetch all the given slots and return an array containing the values
return this.prepare(slotIndexes).then(() => {
return bluebird.all(slotIndexes.map((idx) => this.slots[idx]));
});
}
loadByNames(featureNames) {
return this.load(featureNames.map((name) => this.getSlot(name)));
}
logCodedErrorMessage(format: string, ...args: Array<any>) {
const msg = util.format(format, ...args);
if (this.loggedCodedErrors.has(msg)) {
return;
}
this.loggedCodedErrors.add(msg);
this.ctx.warn({}, `CodedError during sqrl execution:: ${msg}`);
}
logError(err: Error, props: ExecutionErrorProperties = {}): void {
const errorType = (err as any).code || err.name || "other";
if (this.manipulator) {
this.manipulator.logError(err, props);
}
let msg: string;
if (props.functionName) {
msg = `Error in sqrl function ${props.functionName}: ${err.toString()}`;
} else {
msg = `Error in sqrl execution: ${err.toString()}`;
}
const errorProps = Object.assign(
{
err,
errorType,
},
props
);
if (props.fatal) {
this.fatal(errorProps, "Fatal error: " + msg);
} else {
this.error(errorProps, msg);
}
}
getNamedGlobals() {
const sortedNames = Array.from(this.names).sort();
return sortedNames.filter((name) => !name.startsWith("ast:"));
}
} | the_stack |
import type { RefObject } from 'react';
import React from 'react';
import classNames from 'classnames';
import type { ImagePluginViewerConfig, ImageData } from './types';
import { IMAGE_TYPE } from './types';
import { get, includes, isEqual, isFunction } from 'lodash';
import type {
Helpers,
RichContentTheme,
SEOSettings,
CustomAnchorScroll,
} from 'wix-rich-content-common';
import {
mergeStyles,
validate,
isSSR,
anchorScroll,
addAnchorTagToUrl,
GlobalContext,
} from 'wix-rich-content-common';
import { getImageSrc, isPNG, WIX_MEDIA_DEFAULT } from 'wix-rich-content-common/libs/imageUtils';
import pluginImageSchema from 'wix-rich-content-common/dist/statics/schemas/plugin-image.schema.json';
import { DEFAULTS, SEO_IMAGE_WIDTH } from './consts';
import styles from '../statics/styles/image-viewer.rtlignore.scss';
import ExpandIcon from './icons/expand';
import InPluginInput from './InPluginInput';
const isSafari = () => /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
const replaceUrlFileExtenstion = (url, extensionTarget) => {
// replace png or jpg file to extensionTarget
return url.replace(/(.*)\.(jp(e)?g|png)$/, `$1.${extensionTarget}`);
};
interface ImageViewerProps {
componentData: ImageData;
className?: string;
dataUrl: string;
settings: ImagePluginViewerConfig;
defaultCaption: string;
onCaptionChange: (caption: string) => void;
setFocusToBlock: () => void;
theme: RichContentTheme;
helpers: Helpers;
getInPluginEditingMode?: () => unknown;
setInPluginEditingMode?: () => unknown;
isMobile: boolean;
setComponentUrl: (highres?: string) => unknown;
seoMode?: SEOSettings;
blockKey: string;
isLoading: boolean;
customAnchorScroll?: CustomAnchorScroll;
}
interface ImageSrc {
preload: string;
highres: string;
}
interface ImageViewerState {
container?: HTMLDivElement;
ssrDone?: boolean;
fallbackImageSrc?: ImageSrc;
}
class ImageViewer extends React.Component<ImageViewerProps, ImageViewerState> {
preloadRef: RefObject<HTMLImageElement>;
imageRef: RefObject<HTMLImageElement>;
styles!: Record<string, string>;
constructor(props) {
super(props);
validate(props.componentData, pluginImageSchema);
this.state = {};
this.preloadRef = React.createRef();
this.imageRef = React.createRef();
}
static contextType = GlobalContext;
componentDidMount() {
this.setState({ ssrDone: true });
if (isSafari()) {
//In Safari, onload event doesn't always called when reloading the page
this.forceOnImageLoad();
}
}
componentWillReceiveProps(nextProps) {
if (!isEqual(nextProps.componentData, this.props.componentData)) {
validate(nextProps.componentData, pluginImageSchema);
}
}
forceOnImageLoad = () => {
let executionTimes = 0;
const interval = setInterval(() => {
if (this.imageRef?.current?.complete) {
this.onImageLoad(this.imageRef.current);
clearInterval(interval);
}
if (++executionTimes === 10) {
clearInterval(interval);
}
}, 200);
};
calculateHeight(width = 1, src) {
return src && src.height && src.width
? Math.ceil((src.height / src.width) * width)
: WIX_MEDIA_DEFAULT.SIZE;
}
getImageDataUrl(): ImageSrc | null {
return this.props.dataUrl
? {
preload: this.props.dataUrl,
highres: this.props.dataUrl,
}
: null;
}
getImageUrl(src): ImageSrc | null {
const { helpers, seoMode, isMobile } = this.props || {};
if (!src && helpers?.handleFileSelection) {
return null;
}
const { experiments } = this.context;
const removeUsm = experiments?.removeUsmFromImageUrls?.enabled;
const encAutoImageUrls = experiments?.encAutoImageUrls?.enabled;
const qualityPreloadPngs = experiments?.qualityPreloadPngs?.enabled;
const imageUrl: ImageSrc = {
preload: '',
highres: '',
};
const getImageDimensions = (width, isMobile) => {
let requiredHeight;
let requiredWidth = width || 1;
if (isMobile && !isSSR()) {
//adjust the image width to viewport scaling
requiredWidth *= window.screen.width / document.body.clientWidth;
}
//keep the image's original ratio
requiredHeight = this.calculateHeight(requiredWidth, src);
requiredWidth = Math.ceil(requiredWidth);
requiredHeight = Math.ceil(requiredHeight);
return [requiredWidth, requiredHeight];
};
let requiredWidth, requiredHeight;
let webAndNonPngPreloadOpts = {};
/**
PNG files can't reduce quality via Wix services and we want to avoid downloading a big png image that will affect performance.
**/
const validQualtyPreloadFileType = (encAutoImageUrls && qualityPreloadPngs) || !isPNG(src);
if (!isMobile && validQualtyPreloadFileType) {
const {
componentData: { config: { alignment, width, size } = {} },
} = this.props;
const usePredefinedWidth = (alignment === 'left' || alignment === 'right') && !width;
webAndNonPngPreloadOpts = {
imageType: 'quailtyPreload',
size: this.context.experiments.imagePreloadWidthByConfig?.enabled && size,
...(usePredefinedWidth && { requiredWidth: 300 }),
};
}
const commonPreloadOpts = {
encAutoImageUrls,
};
imageUrl.preload = getImageSrc(src, helpers?.getImageUrl, {
...commonPreloadOpts,
...webAndNonPngPreloadOpts,
});
if (seoMode) {
requiredWidth = src?.width && Math.min(src.width, SEO_IMAGE_WIDTH);
requiredHeight = this.calculateHeight(SEO_IMAGE_WIDTH, src);
} else if (this.state.container) {
const desiredWidth = this.state.container.getBoundingClientRect().width || src?.width;
[requiredWidth, requiredHeight] = getImageDimensions(desiredWidth, this.props.isMobile);
}
imageUrl.highres = getImageSrc(src, helpers?.getImageUrl, {
removeUsm,
requiredWidth,
requiredHeight,
requiredQuality: 90,
imageType: 'highRes',
});
if (this.state.ssrDone && !imageUrl.preload && !this.props.isLoading) {
console.error(`image plugin mounted with invalid image source!`, src); //eslint-disable-line no-console
}
return imageUrl;
}
onImageLoadError = () => {
const {
componentData: { src },
} = this.props;
if (src && src.fallback) {
this.setState({
fallbackImageSrc: {
preload: src.fallback,
highres: src.fallback,
},
});
}
};
renderImage = (imageClassName, imageSrc, alt, props, isGif, onlyHighRes) => {
return this.getImage(
classNames(imageClassName, this.styles.imageHighres, {
[this.styles.onlyHighRes]: onlyHighRes,
}),
imageSrc.highres,
alt,
props,
{ fadeIn: !isGif, width: imageSrc.highresWidth, height: imageSrc.highresHeight }
);
};
renderPreloadImage = (imageClassName, imageSrc, alt, props) => {
return this.getImage(
classNames(imageClassName, this.styles.imagePreload),
imageSrc.preload,
alt,
{ 'aria-hidden': true, ...props }
);
};
getImageSize = opts => {
let width, height;
if (opts?.width && opts?.height) {
width = opts.width;
height = opts.height;
} else {
width = this.props.componentData?.src?.width;
height = this.props.componentData?.src?.height;
}
return { width, height };
};
getImage(
imageClassNames,
src,
alt,
props,
opts: {
fadeIn?: boolean;
width?: number | string;
height?: number | string;
} = {}
) {
const { fadeIn = false } = opts;
const loading = this.context.experiments.lazyImagesAndIframes?.enabled ? 'lazy' : undefined;
const { width, height } = this.getImageSize(opts);
return (
<img
{...props}
className={imageClassNames}
src={src}
alt={alt}
onError={this.onImageLoadError}
onLoad={fadeIn ? e => this.onImageLoad(e.target) : undefined}
ref={fadeIn ? this.imageRef : this.preloadRef}
width={width}
height={height}
loading={loading}
/>
);
}
onImageLoad = element => {
element.style.opacity = 1;
if (this.preloadRef.current) {
this.preloadRef.current.style.opacity = '0';
}
};
renderTitle(data, styles) {
const config = data.config || {};
return (
!!config.showTitle && (
<div className={classNames(styles.imageTitle)}>{(data && data.title) || ''}</div>
)
);
}
renderDescription(data, styles) {
const config = data.config || {};
return (
!!config.showDescription && (
<div className={classNames(styles.imageDescription)}>
{(data && data.description) || ''}
</div>
)
);
}
renderCaption(caption) {
const { onCaptionChange, setFocusToBlock, setInPluginEditingMode } = this.props;
const { imageCaption, link } = this.styles;
const classes = classNames(imageCaption, this.hasLink() && link);
return onCaptionChange ? (
<InPluginInput
setInPluginEditingMode={setInPluginEditingMode}
className={classes}
value={caption}
onChange={onCaptionChange}
setFocusToBlock={setFocusToBlock}
/>
) : (
<span dir="auto" className={classes}>
{caption}
</span>
);
}
shouldRenderCaption() {
const { getInPluginEditingMode, settings, componentData, defaultCaption } = this.props;
const caption = componentData.metadata?.caption;
if (includes(get(settings, 'toolbar.hidden'), 'settings')) {
return false;
}
if (
caption === undefined ||
(caption === '' && !getInPluginEditingMode?.()) ||
caption === defaultCaption
) {
return false;
}
const data = componentData || DEFAULTS;
if (data.config.size === 'original' && data.src && data.src.width) {
return data.src.width >= 350;
}
return true;
}
handleExpand = e => {
e.preventDefault();
const {
settings: { onExpand },
helpers = {},
} = this.props;
helpers.onViewerAction?.(IMAGE_TYPE, 'Click', 'expand_image');
this.hasExpand() && onExpand?.(this.props.blockKey);
};
scrollToAnchor = e => {
const {
componentData: {
config: { link: { anchor } = {} },
},
customAnchorScroll,
} = this.props;
if (customAnchorScroll) {
customAnchorScroll(e, anchor as string);
} else {
const anchorString = `viewer-${anchor}`;
const element = document.getElementById(anchorString);
addAnchorTagToUrl(anchorString);
anchorScroll(element);
}
};
hasLink = () => this.props.componentData?.config?.link?.url;
hasAnchor = () => this.props.componentData?.config?.link?.anchor;
onKeyDown = e => {
// Allow key events only in viewer
if ((e.key === 'Enter' || e.key === ' ') && !this.props.getInPluginEditingMode) {
this.handleClick(e);
}
};
handleClick = e => {
if (this.hasLink()) {
return null;
} else if (this.hasAnchor()) {
e.preventDefault();
e.stopPropagation(); // fix problem with wix platform, where it wouldn't scroll and sometimes jump to different page
this.scrollToAnchor(e);
} else {
this.handleExpand(e);
}
};
handleRef = e => {
if (!this.state.container) {
this.setState({ container: e }); //saving the container on the state to trigger a new render
}
};
handleContextMenu = e => {
const {
componentData: { disableDownload = false },
} = this.props;
return disableDownload && e.preventDefault();
};
hasExpand = () => {
const { componentData, settings } = this.props;
let disableExpand = false;
if (componentData.disableExpand !== undefined) {
disableExpand = componentData.disableExpand;
} else if (settings.disableExpand !== undefined) {
disableExpand = settings.disableExpand;
}
return !disableExpand && settings.onExpand;
};
renderExpandIcon = () => {
return (
<div className={this.styles.expandContainer}>
<ExpandIcon className={this.styles.expandIcon} onClick={this.handleExpand} />
</div>
);
};
// eslint-disable-next-line complexity
render() {
this.styles = this.styles || mergeStyles({ styles, theme: this.props.theme });
const { componentData, className, settings, setComponentUrl, seoMode } = this.props;
const { fallbackImageSrc, ssrDone } = this.state;
const data = componentData || DEFAULTS;
let { metadata } = componentData;
if (!metadata) {
metadata = {};
}
const itemClassName = classNames(this.styles.imageWrapper, className, {
[this.styles.pointer]: this.hasExpand() as boolean,
});
const imageClassName = this.styles.image;
const imageSrc = fallbackImageSrc || this.getImageDataUrl() || this.getImageUrl(data.src);
let imageProps = {};
if (data.src && settings && settings.imageProps) {
imageProps = isFunction(settings.imageProps)
? settings.imageProps(data.src)
: settings.imageProps;
}
const isGif = imageSrc?.highres?.endsWith?.('.gif');
setComponentUrl?.(imageSrc?.highres);
const shouldRenderPreloadImage = !seoMode && imageSrc && !isGif;
const shouldRenderImage = (imageSrc && (seoMode || ssrDone)) || isGif;
const accesibilityProps = !this.hasLink() && { role: 'button', tabIndex: 0 };
const onlyHiRes = seoMode || isGif;
/* eslint-disable jsx-a11y/no-static-element-interactions */
return (
<div
data-hook="imageViewer"
className={this.styles.imageContainer}
ref={this.handleRef}
onContextMenu={this.handleContextMenu}
onKeyDown={this.onKeyDown}
{...accesibilityProps}
>
<div
className={itemClassName}
aria-label={metadata.alt}
onClick={this.handleClick}
onKeyDown={this.onKeyDown}
>
{shouldRenderPreloadImage &&
this.renderPreloadImage(imageClassName, imageSrc, metadata.alt, imageProps)}
{shouldRenderImage &&
this.renderImage(imageClassName, imageSrc, metadata.alt, imageProps, isGif, onlyHiRes)}
{this.hasExpand() && this.renderExpandIcon()}
</div>
{this.renderTitle(data, this.styles)}
{this.renderDescription(data, this.styles)}
{this.shouldRenderCaption() && this.renderCaption(metadata.caption)}
</div>
);
}
}
export default ImageViewer; | the_stack |
import {emits} from '@lume/eventful'
import {attribute, untrack, element, variable, Variable} from '@lume/element'
import {TreeNode} from './TreeNode.js'
import {XYZSizeModeValues, SizeModeValue} from '../xyz-values/XYZSizeModeValues.js'
import {XYZNonNegativeValues} from '../xyz-values/XYZNonNegativeValues.js'
import {Motor} from './Motor.js'
import type {StopFunction} from '@lume/element'
import type {
XYZValues,
XYZValuesObject,
XYZPartialValuesArray,
XYZPartialValuesObject,
} from '../xyz-values/XYZValues.js'
import type {RenderTask} from './Motor.js'
import type {XYZNumberValues} from '../xyz-values/XYZNumberValues.js'
// Cache variables to avoid making new variables in repeatedly-called methods.
const previousSize: Partial<XYZValuesObject<number>> = {}
export type SizeableAttributes = 'sizeMode' | 'size'
const sizeMode = new WeakMap<Sizeable, XYZSizeModeValues>()
const size = new WeakMap<Sizeable, XYZNonNegativeValues>()
// No decorators for private fields (yet), so we implement reactivity manually.
// const calculatedSize = new WeakMap<Sizeable, Variable<XYZValuesObject<number>>>()
const calculatedSize = new WeakMap<Sizeable, Variable<{x: number; y: number; z: number}>>()
/**
* @class Sizeable - A class that contains the `sizeMode` and `size` features LUME's elements.
* @extends TreeNode
*/
// Sizeable and its subclass Transformable extend TreeNode because they know
// about their `parent` when calculating proportional sizes or world matrices
// based on parent values.
@element
export class Sizeable extends TreeNode {
// TODO handle ctor arg types
constructor() {
super()
calculatedSize.set(
this,
// variable<XYZValuesObject<number>>({x: 0, y: 0, z: 0}),
variable({x: 0, y: 0, z: 0}),
)
this.sizeMode.on('valuechanged', () => !this._isSettingProperty && (this.sizeMode = this.sizeMode))
this.size.on('valuechanged', () => !this._isSettingProperty && (this.size = this.size))
}
/**
* @property {XYZSizeModeValues} sizeMode - Set the size mode for each
* axis. Possible size modes are "literal" and "proportional". The
* default values are "literal" for all axes. The size mode speicified
* for an axis dictates how the respective value of the same axis in
* the [`size`](TODO) property will behave. A value of
* "literal" for the X axis of `sizeMode` means the value for the X axis
* of `size` will be a literal value. A value of "proportional" for
* the X axis of `sizeMode` means the value for the X axis of
* `size` is a proportion of whatever the current size of
* this node's parent node is.
*/
@attribute
@emits('propertychange')
set sizeMode(newValue: XYZSizeModeValuesProperty) {
if (typeof newValue === 'function') throw new TypeError('property functions are not allowed for sizeMode')
if (!sizeMode.has(this)) sizeMode.set(this, new XYZSizeModeValues('literal', 'literal', 'literal'))
this._setPropertyXYZ('sizeMode', sizeMode.get(this)!, newValue)
}
get sizeMode(): XYZSizeModeValues {
if (!sizeMode.has(this)) sizeMode.set(this, new XYZSizeModeValues('literal', 'literal', 'literal'))
return sizeMode.get(this)!
}
// prettier-ignore
getSizeMode(): XYZSizeModeValues { return this.sizeMode as XYZSizeModeValues }
// TODO ^: Now that TS 4.3 landed the ability to have separate types for
// setters than for getters, we can remove methods like getSizeMode,
// etc.
// TODO: A "differential" size would be cool. Good for padding,
// borders, etc. Inspired from Famous' differential sizing.
//
// TODO: A "target" size where sizing can be relative to another node.
// This would be tricky though, because there could be circular size
// dependencies. Maybe we'd throw an error in that case, because there'd be no original size to base off of.
/**
* @property {XYZNonNegativeValues} size -
* Set the size of each axis. The size for each axis depends on the
* sizeMode for each axis. For example, if node.sizeMode is set to
* `sizeMode = ['literal', 'proportional', 'literal']`, then setting
* `size = [20, 0.5, 30]` means that X size is a literal value of 20,
* Y size is 0.5 of it's parent Y size, and Z size is a literal value
* of 30. It is easy this way to mix literal and proportional sizes for
* the different axes.
*
* Literal sizes can be any value (the literal size that you want) and
* proportional sizes are a number between 0 and 1 representing a
* proportion of the parent node size. 0 means 0% of the parent size,
* and 1.0 means 100% of the parent size.
*
* All size values must be positive numbers.
*
* Defaults to `0` for each axis.
*
* @param {Object} newValue
* @param {number} [newValue.x] The x-axis size to apply.
* @param {number} [newValue.y] The y-axis size to apply.
* @param {number} [newValue.z] The z-axis size to apply.
*/
@attribute
@emits('propertychange')
set size(newValue: XYZNonNegativeNumberValuesProperty | XYZNonNegativeNumberValuesPropertyFunction) {
if (!size.has(this)) size.set(this, new XYZNonNegativeValues(0, 0, 0))
this._setPropertyXYZ('size', size.get(this)!, newValue)
}
get size(): XYZNonNegativeValues {
if (!size.has(this)) size.set(this, new XYZNonNegativeValues(0, 0, 0))
return size.get(this)!
}
// prettier-ignore
getSize(): XYZNonNegativeValues { return this.size as XYZNonNegativeValues }
/**
* Get the actual size of the Node. This can be useful when size is
* proportional, as the actual size of the Node depends on the size of
* it's parent.
*
* @readonly
*
* @return {Array.number} An Oject with x, y, and z properties, each
* property representing the computed size of the x, y, and z axes
* respectively.
*
* @reactive
*/
get calculatedSize() {
// TODO we can re-calculate the actual size lazily, this way it can
// normally be deferred to a Motor render task, unless a user
// explicitly needs it and reads the value.
// if (this.__sizeDirty) this._calcSize
// TODO make __calculatedSize properties readonly and don't clone it
// each time.
return {...(calculatedSize.get(this)?.get() ?? {x: 0, y: 0, z: 0})}
}
/**
* Subclasses should push stop functions returned by autorun() into this
* array in connectedCallback, then disconnectedCallback will
* automatically clean them up.
*/
// XXX Perhaps move this to a separate mixin, as it isn't really related to sizing.
_stopFns: Array<StopFunction> = []
connectedCallback() {
super.connectedCallback()
// For example, subclasses should push autoruns in connectedCallback.
// this._stopFns.push(autorun(...))
}
disconnectedCallback() {
super.disconnectedCallback?.()
for (const stop of this._stopFns) stop()
this._stopFns.length = 0
}
get composedLumeParent(): Sizeable | null {
const result = super._composedParent
if (!(result instanceof Sizeable)) return null
return result
}
get composedLumeChildren(): Sizeable[] {
return super._composedChildren as Sizeable[]
}
_getParentSize() {
return (this.composedLumeParent && calculatedSize.get(this.composedLumeParent)?.get()) ?? {x: 0, y: 0, z: 0}
}
_calcSize() {
const _calculatedSize = calculatedSize.get(this)!.get()
Object.assign(previousSize, _calculatedSize)
const size = this.getSize()
const sizeMode = this.getSizeMode()
const parentSize = this._getParentSize()
if (sizeMode.x == 'literal') {
_calculatedSize.x = size.x
} else {
// proportional
_calculatedSize.x = parentSize.x * size.x
}
if (sizeMode.y == 'literal') {
_calculatedSize.y = size.y
} else {
// proportional
_calculatedSize.y = parentSize.y * size.y
}
if (sizeMode.z == 'literal') {
_calculatedSize.z = size.z
} else {
// proportional
_calculatedSize.z = parentSize.z * size.z
}
// trigger reactive updates (although we set it to the same value)
calculatedSize.get(this)!.set(_calculatedSize)
if (
previousSize.x !== _calculatedSize.x ||
previousSize.y !== _calculatedSize.y ||
previousSize.z !== _calculatedSize.z
) {
this.emit('sizechange', {..._calculatedSize})
}
}
#isSettingProperty = false
get _isSettingProperty() {
return this.#isSettingProperty
}
_setPropertyXYZ<K extends keyof this, V>(name: K, xyz: XYZValues, newValue: V) {
// if (newValue === (this as any)['__' + name]) return
// @ts-ignore
if (newValue === xyz) return
this.#isSettingProperty = true
if (isXYZPropertyFunction(newValue)) {
this.#handleXYZPropertyFunction(newValue, name, xyz)
} else {
if (!this.#settingValueFromPropFunction) this.#removePropertyFunction(name)
else this.#settingValueFromPropFunction = false
// If we're in a computation, we don't want the valuechanged
// event that will be emitted to trigger reactivity (see
// valuechanged listeners above). If we've reached this logic,
// it is because a property is being set, which will already
// trigger reactivity.
untrack(() => {
// ;(this as any)['__' + name].from(newValue)
xyz.from(newValue)
})
}
this.#isSettingProperty = false
}
_setPropertySingle<K extends keyof this, V>(name: K, setter: (newValue: this[K]) => void, newValue: V) {
this.#isSettingProperty = true
if (isSinglePropertyFunction(newValue)) {
this.#handleSinglePropertyFunction(newValue, name)
} else {
if (!this.#settingValueFromPropFunction) this.#removePropertyFunction(name)
else this.#settingValueFromPropFunction = false
// Same note about this untrack() call as the one in _setPropertyXYZ.
untrack(() => {
// ;(this as any)['__' + name] = newValue
setter(newValue as any) // FIXME no any
})
}
this.#isSettingProperty = false
}
#propertyFunctions: Map<string, RenderTask> | null = null
#settingValueFromPropFunction = false
#handleXYZPropertyFunction(fn: XYZNumberValuesPropertyFunction, name: keyof this, xyz: XYZValues) {
if (!this.#propertyFunctions) this.#propertyFunctions = new Map()
const propFunction = this.#propertyFunctions.get(name as string)
if (propFunction) Motor.removeRenderTask(propFunction)
this.#propertyFunctions.set(
name as string,
Motor.addRenderTask(time => {
const result = fn(
// (this as any)['__' + name].x,
// (this as any)['__' + name].y,
// (this as any)['__' + name].z,
xyz.x,
xyz.y,
xyz.z,
time,
)
if (result === false) {
this.#propertyFunctions!.delete(name as string)
return false
}
// mark this true, so that the following set of this[name]
// doesn't override the prop function (normally a
// user can set this[name] to a value that isn't a function
// to disable the prop function).
this.#settingValueFromPropFunction = true
// ;(this as any)[name] = result
xyz.from(result)
return
}),
)
}
#handleSinglePropertyFunction(fn: SinglePropertyFunction, name: keyof this) {
if (!this.#propertyFunctions) this.#propertyFunctions = new Map()
const propFunction = this.#propertyFunctions.get(name as string)
if (propFunction) Motor.removeRenderTask(propFunction)
this.#propertyFunctions.set(
name as string,
Motor.addRenderTask(time => {
// const result = fn((this as any)['__' + name], time)
const result = fn((this as any)[name], time)
if (result === false) {
this.#propertyFunctions!.delete(name as string)
return false
}
this.#settingValueFromPropFunction = true
;(this as any)[name] = result
// TODO The RenderTask return type is `false | void`, so why
// does the noImplicitReturns TS option require a return
// here? Open bug on TypeScript.
return
}),
)
}
// remove property function (render task) if any.
#removePropertyFunction(name: keyof this) {
if (!this.#propertyFunctions) return
const propFunction = this.#propertyFunctions.get(name as string)
if (propFunction) {
Motor.removeRenderTask(propFunction)
this.#propertyFunctions.delete(name as string)
if (!this.#propertyFunctions.size) this.#propertyFunctions = null
}
}
}
// the following type guards are used above just to satisfy the type system,
// though the actual runtime check does not guarantee that the functions are of
// the expected shape.
function isXYZPropertyFunction(f: any): f is XYZNumberValuesPropertyFunction {
return typeof f === 'function'
}
function isSinglePropertyFunction(f: any): f is SinglePropertyFunction {
return typeof f === 'function'
}
// This type represents the types of values that can be set via attributes or
// properties (attributes pass strings to properties and properties all handle
// string values for example, hence why it includes `| string`)
export type XYZValuesProperty<XYZValuesType extends XYZValues, DataType> =
| XYZValuesType
| XYZPartialValuesArray<DataType>
| XYZPartialValuesObject<DataType>
| string
export type XYZNumberValuesProperty = XYZValuesProperty<XYZNumberValues, number>
export type XYZNonNegativeNumberValuesProperty = XYZValuesProperty<XYZNonNegativeValues, number>
export type XYZSizeModeValuesProperty = XYZValuesProperty<XYZSizeModeValues, SizeModeValue>
// Property functions are used for animating properties of type XYZNumberValues
export type XYZValuesPropertyFunction<XYZValuesPropertyType, DataType> = (
x: DataType,
y: DataType,
z: DataType,
time: number,
) => XYZValuesPropertyType | false
export type XYZNumberValuesPropertyFunction = XYZValuesPropertyFunction<XYZNumberValuesProperty, number>
export type XYZNonNegativeNumberValuesPropertyFunction = XYZValuesPropertyFunction<
XYZNonNegativeNumberValuesProperty,
number
>
export type SinglePropertyFunction = (value: number, time: number) => number | false | the_stack |
import { cdmObjectType } from '../../../Enums/cdmObjectType';
import {
CdmAttributeGroupDefinition,
CdmCorpusDefinition,
CdmEntityDefinition,
CdmTypeAttributeDefinition,
CdmTraitReference,
CdmAttributeGroupReference,
} from '../../../internal';
import { testHelper } from '../../testHelper';
import { projectionTestUtils } from '../../Utilities/projectionTestUtils';
/**
* Class for testing the mao type with a set of foundational operations in a projection
*/
describe('Cdm/Projection/TestProjectionMap', () => {
/**
* The path between TestDataPath and TestName.
*/
const testsSubpath: string = 'Cdm/Projection/ProjectionMapTest';
/**
* All possible combinations of the different resolution directives
*/
const resOptsCombinations: string[][] = [
[],
['referenceOnly'],
['normalized'],
['structured'],
['referenceOnly', 'normalized'],
['referenceOnly', 'structured'],
['normalized', 'structured'],
['referenceOnly', 'normalized', 'structured']
];
/**
* Test Map type on an entity attribute.
*/
it('TestEntityAttribute', async () => {
const testName: string = 'TestEntityAttribute';
const entityName: string = 'ThreeMusketeers';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const nonStructuredResolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
// Original set of attributes: ["name", "age", "address"]
// in non-structured form
// addArtifactAttribute : { "key" , "insertAtTop": true }
// Expand 1...3;
// renameAttributes = { {a}_{o}_key, apply to "key" }
// renameAttributes = { {a}_{m}_{o}_value, apply to "name", "age", "address" }
// alterTraits = { indicates.expansionInfo.mapKey(expansionName: "{a}", ordinal: "{o}") , apply to "key" , "argumentsContainWildcards" : true }
// alterTraits = { has.expansionInfo.mapValue(expansionName: "{a}", ordinal: "{o}", memberAttribute: "{mo}") , apply to "name", "age", "address" , "argumentsContainWildcards" : true }
// addArtifactAttribute : "personCount"
// alterTraits = { indicates.expansionInfo.count(expansionName: "{a}") , apply to "personCount" , "argumentsContainWildcards" : true }
expect(nonStructuredResolvedEntity.attributes.length)
.toEqual(13);
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition, 'key_1_key', 1, 'ThreePeople', undefined, true);
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition, "ThreePeople_name_1_value", 1, "ThreePeople", "name");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition, "ThreePeople_age_1_value", 1, "ThreePeople", "age");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition, "ThreePeople_address_1_value", 1, "ThreePeople", "address");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[4] as CdmTypeAttributeDefinition, 'key_2_key', 2, 'ThreePeople', undefined, true);
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[5] as CdmTypeAttributeDefinition, "ThreePeople_name_2_value", 2, "ThreePeople", "name");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[6] as CdmTypeAttributeDefinition, "ThreePeople_age_2_value", 2, "ThreePeople", "age");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[7] as CdmTypeAttributeDefinition, "ThreePeople_address_2_value", 2, "ThreePeople", "address");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[8] as CdmTypeAttributeDefinition, 'key_3_key', 3, 'ThreePeople', undefined, true);
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[9] as CdmTypeAttributeDefinition, "ThreePeople_name_3_value", 3, "ThreePeople", "name");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[10] as CdmTypeAttributeDefinition, "ThreePeople_age_3_value", 3, "ThreePeople", "age");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[11] as CdmTypeAttributeDefinition, "ThreePeople_address_3_value", 3, "ThreePeople", "address");
expect((nonStructuredResolvedEntity.attributes.allItems[12] as CdmTypeAttributeDefinition).name)
.toEqual('personCount');
expect(nonStructuredResolvedEntity.attributes.allItems[12].appliedTraits.item('indicates.expansionInfo.count'))
.not.toBeUndefined;
expect((nonStructuredResolvedEntity.attributes.allItems[12].appliedTraits.item('indicates.expansionInfo.count') as CdmTraitReference).arguments.allItems[0].value)
.toEqual('ThreePeople');
// Original set of attributes: ["name", "age", "address"]
// in structured form
// addAttributeGroup: favorite people
// alterTraits = { is.dataFormat.mapValue }
// addArtifactAttribute : { "favorite People Key" (with trait "is.dataFormat.mapKey") , "insertAtTop": true }
// addAttributeGroup: favorite People Group
// alterTraits = { is.dataFormat.map }
const structuredResolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ 'structured' ]);
expect(structuredResolvedEntity.attributes.length)
.toEqual(1);
const attGroupDefinition: CdmAttributeGroupDefinition = projectionTestUtils.validateAttributeGroup(structuredResolvedEntity.attributes, 'favorite People Group');
expect(attGroupDefinition.exhibitsTraits.item('is.dataFormat.map'))
.not
.toBeUndefined();
expect((attGroupDefinition.members.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('favorite People Key');
expect(attGroupDefinition.members.allItems[0].appliedTraits.item('is.dataFormat.mapKey'))
.not
.toBeUndefined();
expect(attGroupDefinition.members.allItems[1].objectType)
.toEqual(cdmObjectType.attributeGroupRef);
const innerAttGroupRef: CdmAttributeGroupReference = attGroupDefinition.members.allItems[1] as CdmAttributeGroupReference;
expect(innerAttGroupRef.explicitReference)
.not
.toBeUndefined();
const innerAttGroupDefinition: CdmAttributeGroupDefinition = innerAttGroupRef.explicitReference as CdmAttributeGroupDefinition;
expect(innerAttGroupDefinition.attributeGroupName)
.toEqual('favorite people');
expect(innerAttGroupDefinition.exhibitsTraits.item('is.dataFormat.mapValue'));
});
/**
* Test Map type on an type attribute.
*/
it('TestTypeAttribute', async () => {
const testName: string = 'TestTypeAttribute';
const entityName: string = 'Person';
const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, testName);
for (const resOpt of resOptsCombinations) {
await projectionTestUtils.loadEntityForResolutionOptionAndSave(corpus, testName, testsSubpath, entityName, resOpt);
}
const entity: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/${entityName}.cdm.json/${entityName}`);
const nonStructuredResolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ ]);
// Original set of attributes: [ "FavoriteTerms" ]
// in non-structured form
// addArtifactAttribute : { "Term key" , "insertAtTop": true }
// Expand 1...2;
// renameAttributes = { {m}_{o}_key, apply to "Term key" }
// renameAttributes = { {m}_{o}_value, apply to "FavoriteTerms" }
// alterTraits = { indicates.expansionInfo.mapKey(expansionName: "{a}", ordinal: "{o}") , apply to "Term key" , "argumentsContainWildcards" : true }
// alterTraits = { has.expansionInfo.mapValue(expansionName: "{a}", ordinal: "{o}") , apply to "FavoriteTerms" , "argumentsContainWildcards" : true }
// addArtifactAttribute : number of favorite terms"
// alterTraits = { indicates.expansionInfo.count(expansionName: "{a}") , apply to "number of favorite terms" , "argumentsContainWildcards" : true }
expect(nonStructuredResolvedEntity.attributes.length)
.toEqual(5);
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[0] as CdmTypeAttributeDefinition, 'Term key_1_key', 1, 'FavoriteTerms', undefined, true);
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[1] as CdmTypeAttributeDefinition, "FavoriteTerms_1_value", 1, "FavoriteTerms");
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[2] as CdmTypeAttributeDefinition, "Term key_2_key", 2, "FavoriteTerms", undefined, true);
validateAttributeTrait(nonStructuredResolvedEntity.attributes.allItems[3] as CdmTypeAttributeDefinition, "FavoriteTerms_2_value", 2, "FavoriteTerms");
expect((nonStructuredResolvedEntity.attributes.allItems[4] as CdmTypeAttributeDefinition).name)
.toEqual('number of favorite terms');
expect(nonStructuredResolvedEntity.attributes.allItems[4].appliedTraits.item('indicates.expansionInfo.count'))
.not.toBeUndefined();
expect((nonStructuredResolvedEntity.attributes.allItems[4].appliedTraits.item('indicates.expansionInfo.count') as CdmTraitReference).arguments.allItems[0].value)
.toEqual('FavoriteTerms');
// Original set of attributes: [ "FavoriteTerms" ]
// in structured form
// alterTraits = { is.dataFormat.mapValue }
// addArtifactAttribute : { "Favorite Terms Key" (with trait "is.dataFormat.mapKey") , "insertAtTop": true }
// addAttributeGroup: favorite Term Group
// alterTraits = { is.dataFormat.map }
const structuredResolvedEntity: CdmEntityDefinition = await projectionTestUtils.getResolvedEntity(corpus, entity, [ 'structured' ]);
expect(structuredResolvedEntity.attributes.length)
.toEqual(1);
const attGroupDefinition: CdmAttributeGroupDefinition = projectionTestUtils.validateAttributeGroup(structuredResolvedEntity.attributes, 'favorite Term Group');
expect(attGroupDefinition.exhibitsTraits.item('is.dataFormat.map'))
.not
.toBeUndefined();
expect((attGroupDefinition.members.allItems[0] as CdmTypeAttributeDefinition).name)
.toEqual('Favorite Terms Key');
expect(attGroupDefinition.members.allItems[0].appliedTraits.item('is.dataFormat.mapKey'))
.not
.toBeUndefined();
expect((attGroupDefinition.members.allItems[1] as CdmTypeAttributeDefinition).name)
.toEqual('FavoriteTerms');
expect(attGroupDefinition.members.allItems[1].appliedTraits.item('is.dataFormat.mapValue'))
.not
.toBeUndefined();
});
/**
* Validates trait for map's value or key.
* @param attribute The type attribute
* @param expectedAttrName The expected attribute name
* @param ordinal The expected ordinal
* @param expansionName The expected expansion name
* @param memberAttribute The expected member attribute name
* @param isKey Whether this is a key
* @internal
*/
function validateAttributeTrait(attribute: CdmTypeAttributeDefinition, expectedAttrName: string, ordinal: number, expansionName: string, memberAttribute?: string, isKey?: boolean) {
expect(attribute.name)
.toEqual(expectedAttrName);
const trait: CdmTraitReference = attribute.appliedTraits.item(isKey ? 'indicates.expansionInfo.mapKey' : 'has.expansionInfo.mapValue') as CdmTraitReference;
expect(trait)
.not
.toBeUndefined();
expect(trait.arguments.fetchValue('expansionName'))
.toEqual(expansionName);
expect(trait.arguments.fetchValue('ordinal'))
.toEqual(ordinal.toString());
if (memberAttribute !== undefined) {
expect(trait.arguments.fetchValue('memberAttribute'))
.toEqual(memberAttribute);
}
}
}); | the_stack |
import { Component, OnInit, OnDestroy } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { Title } from '@angular/platform-browser'
import { TreeNode } from 'primeng/api'
import { MenuItem } from 'primeng/api'
import { MessageService } from 'primeng/api'
import { AuthService } from '../auth.service'
import { humanBytes } from '../utils'
import { ManagementService } from '../backend/api/management.service'
import { ExecutionService } from '../backend/api/execution.service'
import { BreadcrumbsService } from '../breadcrumbs.service'
@Component({
selector: 'app-flow-results',
templateUrl: './flow-results.component.html',
styleUrls: ['./flow-results.component.sass'],
})
export class FlowResultsComponent implements OnInit, OnDestroy {
flowId = 0
flow = null
runs: any[]
runsTree: TreeNode[]
flatTree: any[]
activeTabIndex = 0
args: any[]
nodeMenuItems: MenuItem[]
// artifacts
artifacts: any[]
totalArtifacts = 0
loadingArtifacts = false
refreshTimer: any = null
refreshing = false
selectedNode: any = {
stage: {
name: '',
id: null,
},
run: null,
selected: false,
}
repoUrl = 'awe'
diffUrl = 'dafsd'
constructor(
private route: ActivatedRoute,
private router: Router,
public auth: AuthService,
protected managementService: ManagementService,
protected executionService: ExecutionService,
protected breadcrumbService: BreadcrumbsService,
private msgSrv: MessageService,
private titleService: Title
) {}
ngOnInit() {
this.route.paramMap.subscribe((params) => {
this.flowId = parseInt(params.get('id'), 10)
this.titleService.setTitle('Kraken - Flow ' + this.flowId)
this.runsTree = [
{
label: `Flow [${this.flowId}]`,
expanded: true,
type: 'root',
data: { created: '' },
children: [],
},
]
this.refresh()
})
}
ngOnDestroy() {
if (this.refreshTimer) {
clearTimeout(this.refreshTimer)
this.refreshTimer = null
}
}
_getRunForStage(stageName) {
for (const run of this.flow.runs) {
if (run.stage_name === stageName) {
return run
}
}
return null
}
_getParamFromStage(stageName, paramName) {
for (const stage of this.flow.stages) {
if (stage.name === stageName) {
for (const param of stage.schema.parameters) {
if (param.name === paramName) {
return param
}
}
}
}
return null
}
_buildSubtree(node, allParents, children) {
for (const c of children) {
const subtree = {
label: c.name,
expanded: true,
data: {
stage: c,
run: this._getRunForStage(c.name),
selected: false,
},
}
if (allParents[c.name] !== undefined) {
this._buildSubtree(subtree, allParents, allParents[c.name])
}
if (node.children === undefined) {
node.children = []
}
node.children.push(subtree)
}
}
_traverseTree(node, level) {
if (node.data.run || node.data.stage) {
let selected = false
if (this.selectedNode.stage.id === null) {
this.selectedNode = node.data
selected = true
}
this.flatTree.push({
level,
run: node.data.run,
stage: node.data.stage,
selected,
})
}
if (node.children) {
for (const c of node.children) {
this._traverseTree(c, level + 1)
}
}
}
refresh() {
this.refreshing = true
this.executionService.getFlow(this.flowId).subscribe((flow) => {
this.refreshing = false
this.flow = flow
const crumbs = [
{
label: 'Projects',
project_id: flow.project_id,
project_name: flow.project_name,
},
{
label: 'Branches',
branch_id: flow.branch_id,
branch_name: flow.base_branch_name,
},
{
label: 'Results',
branch_id: flow.branch_id,
flow_kind: flow.kind,
},
{
label: 'Flows',
flow_id: flow.id,
},
]
this.breadcrumbService.setCrumbs(crumbs)
// collect args from flow
const args = []
let sectionArgs = []
if (this.flow.kind === 'dev') {
sectionArgs.push({
name: 'BRANCH',
value: this.flow.branch_name,
})
}
args.push({
name: 'Common',
args: sectionArgs,
})
// collect args from runs
for (const run of this.flow.runs) {
sectionArgs = []
for (const a of Object.keys(run.args)) {
const param = this._getParamFromStage(run.stage_name, a)
let description = ''
let defaultValue
if (param) {
description = param.description
defaultValue = param.default
}
sectionArgs.push({
name: a,
value: run.args[a],
description,
default: defaultValue,
})
}
if (sectionArgs.length > 0) {
args.push({
name: run.stage_name,
args: sectionArgs,
})
}
}
this.args = args
// build tree of runs
const allParents = {
root: [],
}
for (const stage of flow.stages) {
if (allParents[stage.schema.parent] === undefined) {
allParents[stage.schema.parent] = []
}
allParents[stage.schema.parent].push(stage)
}
this.runsTree = [
{
label: `Flow [${this.flowId}]`,
expanded: true,
type: 'root',
data: flow,
},
]
this._buildSubtree(this.runsTree[0], allParents, allParents.root)
// console.info(this.runsTree);
this.flatTree = []
this._traverseTree(this.runsTree[0], 0)
// console.info('flatTree', this.flatTree);
const tab = this.route.snapshot.queryParamMap.get('tab')
if (
tab === 'artifacts' &&
flow.artifacts &&
flow.artifacts._public &&
flow.artifacts._public.count > 0
) {
setTimeout(() => {
this.activeTabIndex = 3
}, 100)
}
// put back selection
if (this.selectedNode.stage.id) {
this.changeSelection(this.selectedNode.stage.id)
}
// refresh data every 10secs
this.refreshTimer = setTimeout(() => {
this.refresh()
}, 10000)
})
}
showNodeMenu($event, nodeMenu, node) {
console.info(node)
if (node.data.run) {
this.nodeMenuItems = [
{
label: 'Show Details',
icon: 'pi pi-folder-open',
routerLink: '/runs/' + node.data.run.id + '/jobs',
},
{
label: 'Rerun',
icon: 'pi pi-replay',
disabled: !this.auth.hasPermission('manage'),
title: this.auth.permTip('manage'),
},
]
} else {
this.nodeMenuItems = [
{
label: 'Run this stage',
icon: 'pi pi-caret-right',
command: () => {
const stage = node.data.stage
console.info(stage.schema.parameters)
if (stage.schema.parameters.length === 0) {
this.executionService
.createRun(this.flowId, stage.id)
.subscribe(
(data) => {
this.msgSrv.add({
severity: 'success',
summary: 'Run succeeded',
detail: 'Run operation succeeded.',
})
this.refresh()
},
(err) => {
this.msgSrv.add({
severity: 'error',
summary: 'Run erred',
detail:
'Run operation erred: ' +
err.statusText,
life: 10000,
})
}
)
} else {
this.router.navigate([
'/flows/' + this.flowId + '/runs/new',
])
}
},
disabled: !this.auth.hasPermission('manage'),
title: this.auth.permTip('manage'),
},
]
}
nodeMenu.toggle($event)
}
onStageRun(newRun) {
// console.info(newRun)
this.refresh()
}
humanFileSize(bytes) {
return humanBytes(bytes, false)
}
loadArtifactsLazy(event) {
this.loadingArtifacts = true
this.executionService
.getFlowArtifacts(this.flowId, event.first, event.rows)
.subscribe((data) => {
this.artifacts = data.items
this.totalArtifacts = data.total
this.loadingArtifacts = false
})
}
changeSelection(stageId) {
for (const node of this.flatTree) {
if (node.stage.id === stageId) {
node.selected = true
this.selectedNode = node
} else {
node.selected = false
}
}
}
hasFlowCommits(flow) {
if (
flow &&
flow.trigger &&
(flow.trigger.commits || flow.trigger.pull_request)
) {
return true
}
return false
}
} | the_stack |
import * as vscode from 'vscode';
import * as path from 'path';
import * as child_process from 'child_process';
import * as request from 'request';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';
import { CommandUtil } from '../../extension/util/CommandUtil';
import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter';
import { ExtensionUtil } from '../../extension/util/ExtensionUtil';
import { OutputAdapter, LogType, FabricRuntimeUtil } from 'ibm-blockchain-platform-common';
import { VSCodeBlockchainDockerOutputAdapter } from '../../extension/logging/VSCodeBlockchainDockerOutputAdapter';
chai.should();
chai.use(sinonChai);
chai.use(chaiAsPromised);
// tslint:disable no-unused-expression
describe('CommandUtil Tests', () => {
let mySandBox: sinon.SinonSandbox;
beforeEach(() => {
mySandBox = sinon.createSandbox();
});
afterEach(() => {
mySandBox.restore();
});
describe('sendCommand', () => {
it('should send a shell command', async () => {
const rootPath: string = path.dirname(__dirname);
const uri: vscode.Uri = vscode.Uri.file(path.join(rootPath, '../../test'));
const command: string = await CommandUtil.sendCommand('echo Hyperledgendary', uri.fsPath);
command.should.equal('Hyperledgendary');
});
});
describe('sendCommandWithProgress', () => {
it('should send a shell command', async () => {
const rootPath: string = path.dirname(__dirname);
const uri: vscode.Uri = vscode.Uri.file(path.join(rootPath, '../../test'));
const command: string = await CommandUtil.sendCommandWithProgress('echo Hyperledgendary', uri.fsPath, 'such progress message');
command.should.equal('Hyperledgendary');
});
});
describe('sendCommandWithOutput', () => {
it('should send a command and get output', async () => {
const spawnSpy: sinon.SinonSpy = mySandBox.spy(child_process, 'spawn');
const cmd: string = process.platform === 'win32' ? 'cmd' : 'echo';
const args: string[] = process.platform === 'win32' ? ['/c', 'echo hyperlegendary'] : ['hyperlegendary'];
await CommandUtil.sendCommandWithOutput(cmd, args);
spawnSpy.should.have.been.calledOnce;
spawnSpy.should.have.been.calledWith(cmd, args);
spawnSpy.getCall(0).args[2].shell.should.equal(false);
});
it('should send a script and get output', async () => {
const spawnSpy: sinon.SinonSpy = mySandBox.spy(child_process, 'spawn');
await CommandUtil.sendCommandWithOutput('echo', ['hyperlegendary'], undefined, undefined, undefined, true);
spawnSpy.should.have.been.calledOnce;
spawnSpy.should.have.been.calledWith('echo', ['hyperlegendary']);
spawnSpy.getCall(0).args[2].shell.should.equal(true);
});
it('should send a command and get output with cwd set', async () => {
const spawnSpy: sinon.SinonSpy = mySandBox.spy(child_process, 'spawn');
const cmd: string = process.platform === 'win32' ? 'cmd' : 'echo';
const args: string[] = process.platform === 'win32' ? ['/c', 'echo hyperlegendary'] : ['hyperlegendary'];
await CommandUtil.sendCommandWithOutput(cmd, args, ExtensionUtil.getExtensionPath());
spawnSpy.should.have.been.calledOnce;
spawnSpy.should.have.been.calledWith(cmd, args);
spawnSpy.getCall(0).args[2].cwd.should.equal(ExtensionUtil.getExtensionPath());
});
it('should send a command and get output with env set', async () => {
const spawnSpy: sinon.SinonSpy = mySandBox.spy(child_process, 'spawn');
const env: any = Object.assign({}, process.env, {
TEST_ENV: 'my env',
});
const cmd: string = process.platform === 'win32' ? 'cmd' : 'echo';
const args: string[] = process.platform === 'win32' ? ['/c', 'echo hyperlegendary'] : ['hyperlegendary'];
await CommandUtil.sendCommandWithOutput(cmd, args, null, env);
spawnSpy.should.have.been.calledOnce;
spawnSpy.should.have.been.calledWith(cmd, args);
spawnSpy.getCall(0).args[2].env.TEST_ENV.should.equal('my env');
});
it('should send a command and get output with custom output adapter', async () => {
const spawnSpy: sinon.SinonSpy = mySandBox.spy(child_process, 'spawn');
const output: VSCodeBlockchainOutputAdapter = VSCodeBlockchainOutputAdapter.instance();
const outputSpy: sinon.SinonSpy = mySandBox.spy(output, 'log');
const cmd: string = process.platform === 'win32' ? 'cmd' : 'echo';
const args: string[] = process.platform === 'win32' ? ['/c', 'echo hyperlegendary'] : ['hyperlegendary'];
await CommandUtil.sendCommandWithOutput(cmd, args, null, null, output, true);
spawnSpy.should.have.been.calledOnce;
spawnSpy.should.have.been.calledWith(cmd, args);
outputSpy.should.have.been.calledWith(LogType.INFO, undefined, 'hyperlegendary');
});
it('should send a command and handle error', async () => {
const spawnSpy: sinon.SinonSpy = mySandBox.spy(child_process, 'spawn');
await CommandUtil.sendCommandWithOutput('bob', ['hyperlegendary']).should.be.rejectedWith(/spawn bob ENOENT/);
spawnSpy.should.have.been.calledOnce;
spawnSpy.should.have.been.calledWith('bob', ['hyperlegendary']);
});
it('should send a command and handle error code', async () => {
const spawnSpy: sinon.SinonSpy = mySandBox.spy(child_process, 'spawn');
if (process.platform === 'win32') {
await CommandUtil.sendCommandWithOutput('cmd', ['/c', 'echo stdout && echo stderr >&2 && exit 1']).should.be.rejectedWith(`Failed to execute command "cmd" with arguments "/c, echo stdout && echo stderr >&2 && exit 1" return code 1`);
spawnSpy.should.have.been.calledOnce;
spawnSpy.should.have.been.calledWith('cmd', ['/c', 'echo stdout && echo stderr >&2 && exit 1']);
} else {
await CommandUtil.sendCommandWithOutput('/bin/sh', ['-c', 'echo stdout && echo stderr >&2 && false']).should.be.rejectedWith(`Failed to execute command "/bin/sh" with arguments "-c, echo stdout && echo stderr >&2 && false" return code 1`);
spawnSpy.should.have.been.calledOnce;
spawnSpy.should.have.been.calledWith('/bin/sh', ['-c', 'echo stdout && echo stderr >&2 && false']);
}
});
});
describe('sendCommandWithOutputAndProgress', () => {
const outputAdapter: OutputAdapter = VSCodeBlockchainOutputAdapter.instance();
let sendCommandWithOutputStub: sinon.SinonStub;
let withProgressSpy: sinon.SinonSpy;
beforeEach(() => {
sendCommandWithOutputStub = mySandBox.stub(CommandUtil, 'sendCommandWithOutput').rejects();
sendCommandWithOutputStub.withArgs('npm', ['install'], '/some/dir', { DOGE: 'WOW' }, outputAdapter, true).resolves();
withProgressSpy = mySandBox.spy(vscode.window, 'withProgress');
});
it('should call sendCommandWithOutput with a progress message', async () => {
await CommandUtil.sendCommandWithOutputAndProgress('npm', ['install'], 'hello world', '/some/dir', { DOGE: 'WOW' }, outputAdapter, true);
sendCommandWithOutputStub.should.have.been.calledOnceWithExactly('npm', ['install'], '/some/dir', { DOGE: 'WOW' }, outputAdapter, true);
withProgressSpy.should.have.been.calledOnce;
});
});
describe('sendRequestWithOutput', () => {
let outputSpy: sinon.SinonSpy;
const outputAdapter: OutputAdapter = VSCodeBlockchainDockerOutputAdapter.instance(FabricRuntimeUtil.LOCAL_FABRIC);
beforeEach(() => {
outputSpy = mySandBox.spy(outputAdapter, 'log');
});
it('should send a request', () => {
const onStub: sinon.SinonStub = mySandBox.stub();
onStub.yields(' some output \n some more output').returns({ on: mySandBox.stub() });
mySandBox.stub(request, 'get').returns({ on: onStub });
CommandUtil.sendRequestWithOutput('http://localhost:8000/logs', outputAdapter);
outputSpy.should.have.been.calledTwice;
outputSpy.should.have.been.calledWith(LogType.INFO, undefined, 'some output ');
outputSpy.should.have.been.calledWith(LogType.INFO, undefined, 'some more output');
});
it('should send a request that errors', () => {
const onStub: sinon.SinonStub = mySandBox.stub();
const errorStub: sinon.SinonStub = mySandBox.stub();
errorStub.yields(' some error \r some more error');
onStub.returns({ on: mySandBox.stub() }).returns({ on: errorStub });
mySandBox.stub(request, 'get').returns({ on: onStub });
CommandUtil.sendRequestWithOutput('http://localhost:8000/logs', outputAdapter);
outputSpy.should.have.been.calledTwice;
outputSpy.should.have.been.calledWith(LogType.ERROR, undefined, 'some error ');
outputSpy.should.have.been.calledWith(LogType.ERROR, undefined, 'some more error');
});
it('should send output with default adapter', () => {
const consoleSpy: sinon.SinonSpy = mySandBox.spy(console, 'log');
const onStub: sinon.SinonStub = mySandBox.stub();
onStub.yields('some output').returns({ on: mySandBox.stub() });
mySandBox.stub(request, 'get').returns({ on: onStub });
CommandUtil.sendRequestWithOutput('http://localhost:8000/logs');
outputSpy.should.not.have.been.called;
consoleSpy.should.have.been.called;
});
});
describe('abortRequest', () => {
it('should abort the request', () => {
const requestStub: any = {
abort: mySandBox.stub()
};
CommandUtil.abortRequest(requestStub);
requestStub.abort.should.have.been.called;
});
});
}); | the_stack |
import { CommunityMembersExclusion, CreateCommunityApiParams, UpdateCommunityApiParams } from '~/services/Apis/communities/CommunitiesApiServiceTypes';
import { ICommunity } from '~/models/communities/community/ICommunity';
import { IModerationCategory } from '~/models/moderation/moderation_category/IModerationCategory';
import { IList } from '~/models/lists/list/IList';
import { ICircle } from '~/models/connections/circle/ICircle';
import { IPost } from '~/models/posts/post/IPost';
import { IPostComment } from '~/models/posts/post-comment/IPostComment';
import { IEmoji } from '~/models/common/emoji/IEmoji';
import { IPostReaction } from '~/models/posts/post-reaction/IPostReaction';
import { IPostCommentReaction } from '~/models/posts/post-comment-reaction/IPostCommentReaction';
import { PostCommentsSortSetting } from '~/services/user-preferences/libs/PostCommentsSortSetting';
import { NotificationType } from '~/models/notifications/notification/lib/NotificationType';
import { INotification } from '~/models/notifications/notification/INotification';
import { IUser } from '~/models/auth/user/IUser';
import { ICategory } from '~/models/common/category/ICategory';
import { IHashtag } from '~/models/common/hashtag/IHashtag';
import { OkFile } from '~/services/media/IMediaService';
import { GetFollowersApiParams, GetFollowingsApiParams, SearchFollowersApiParams, SearchFollowingsApiParams, UpdateUserApiParams } from '../Apis/auth/AuthApiServiceTypes';
import { CheckConnectionsCircleNameIsAvailableApiParams, CreateConnectionsCircleApiParams, DeleteConnectionsCircleApiParams, UpdateConnectionsCircleApiParams } from '../Apis/connections/ConnectionsApiServiceTypes';
// AUTH START
export interface GetUserParams {
userUsername: string;
}
export interface UpdateUserParams extends UpdateUserApiParams {};
export interface ReportUserParams {
user: IUser;
description?: string;
moderationCategory: IModerationCategory;
}
export interface BlockUserParams {
user: IUser;
}
export interface UnblockUserParams {
user: IUser;
}
export interface ConnectWithUserParams {
user: IUser;
circles: ICircle[];
}
export interface DisconnectFromUserParams {
user: IUser;
}
export interface ConfirmConnectionWithUserParaUserParams {
user: IUser;
circles?: ICircle[];
}
export interface UpdateConnectionWithUserParaUserParams {
user: IUser;
circles: ICircle[];
}
export interface GetConnectionsCircleParams {
circleId: number;
}
export interface CreateConnectionsCircleParams extends CreateConnectionsCircleApiParams {};
export interface UpdateConnectionsCircleParams extends UpdateConnectionsCircleApiParams {};
export interface DeleteConnectionsCircleParams extends DeleteConnectionsCircleApiParams {};
export interface CheckConnectionsCircleNameIsAvailableParams extends CheckConnectionsCircleNameIsAvailableApiParams {};
export interface SearchUsersParams {
query: string;
}
export interface GetFollowersParams extends GetFollowersApiParams {}
export interface SearchFollowersParams extends SearchFollowersApiParams {};
export interface GetFollowingsParams extends GetFollowingsApiParams {}
export interface SearchFollowingsParams extends SearchFollowingsApiParams {};
// AUTH END
// COMMUNITIES START
export interface GetTrendingCommunitiesParams {
category?: ICategory;
}
export interface GetFavoriteCommunitiesParams {
offset?: number;
}
export interface GetAdministratedCommunitiesParams {
offset?: number;
}
export interface GetModeratedCommunitiesParams {
offset?: number;
}
export interface GetJoinedCommunitiesParams {
offset?: number;
}
export interface SearchJoinedCommunitiesParams {
query?: string;
}
export interface SearchCommunitiesParams {
query: string;
excludedFromProfilePosts?: boolean;
}
export interface GetCommunityAdministratorsParams {
community: ICommunity;
count: number;
maxId?: number;
}
export interface SearchCommunityAdministratorsParams {
community: ICommunity;
query: string;
}
export interface AddCommunityAdministratorParams {
community: ICommunity;
user: IUser;
}
export interface RemoveCommunityAdministratorParams {
community: ICommunity;
user: IUser;
}
export interface GetCommunityModeratorsParams {
community: ICommunity;
count: number;
maxId?: number;
}
export interface GetCommunityPostsParams {
community: ICommunity;
count?: number;
maxId?: number;
appendAuthorizationTokenIfExists?: boolean;
}
export interface SearchCommunityModeratorsParams {
community: ICommunity;
query: string;
}
export interface AddCommunityModeratorParams {
community: ICommunity;
user: IUser;
}
export interface RemoveCommunityModeratorParams {
community: ICommunity;
user: IUser;
}
export interface GetCommunityMembersParams {
community: ICommunity;
count: number;
maxId?: number;
exclude: CommunityMembersExclusion[];
}
export interface SearchCommunityMembersParams {
community: ICommunity;
query: string;
exclude: CommunityMembersExclusion[];
}
export interface GetCommunityBannedUsersParams {
community: ICommunity;
count: number;
maxId?: number;
}
export interface SearchCommunityBannedUsersParams {
community: ICommunity;
query: string;
}
export interface BanCommunityUserParams {
community: ICommunity;
user: IUser;
}
export interface UnbanCommunityUserParams {
community: ICommunity;
user: IUser;
}
export interface ReportCommunityParams {
community: ICommunity;
moderationCategory: IModerationCategory
description: string;
}
export interface GetCommunityParams {
communityName: string;
appendAuthorizationTokenIfExists?: boolean;
}
export interface GetCommunityPostsCountParams {
community: ICommunity;
}
export interface CreateCommunityParams extends CreateCommunityApiParams {
}
export interface JoinCommunityParams {
community: ICommunity;
}
export interface LeaveCommunityParams {
community: ICommunity;
}
export interface FavoriteCommunityParams {
community: ICommunity;
}
export interface UnfavoriteCommunityParams {
community: ICommunity;
}
export interface UpdateCommunityParams extends UpdateCommunityApiParams {
community: ICommunity;
}
export interface UpdateCommunityAvatarParams {
community: ICommunity;
avatar: File | Blob;
}
export interface DeleteCommunityAvatarParams {
community: ICommunity;
}
export interface UpdateCommunityCoverParams {
community: ICommunity;
cover: File | Blob;
}
export interface DeleteCommunityCoverParams {
community: ICommunity;
}
export interface CreateCommunityPostParams {
community: ICommunity;
text?: string;
isDraft?: boolean;
}
export interface DeleteCommunityParams {
community: ICommunity;
}
// COMMUNITIES END
// POSTS START
export interface GetTopPostsParams {
minId?: number;
maxId?: number;
count?: number;
excludeJoinedCommunities?: boolean;
}
export interface GetTrendingPostsParams {
minId?: number;
maxId?: number;
count?: number;
}
export interface PreviewLinkParams {
link: string;
}
export interface GetTimelinePostsParams {
minId?: number;
maxId?: number;
count?: number;
lists?: IList[];
circles?: ICircle[];
username?: string;
}
export interface GetPostCommentsParams {
post: IPost;
countMax?: number;
countMin?: number;
maxId?: number;
minId?: number;
sort?: PostCommentsSortSetting;
}
export interface GetPostCommentRepliesParams {
postComment: IPostComment;
post: IPost;
countMax?: number;
countMin?: number;
maxId?: number;
minId?: number;
sort?: PostCommentsSortSetting;
}
export interface CommentPostParams {
post: IPost;
text: string;
}
export interface EditPostParams {
post: IPost;
text: string;
}
export interface EditPostCommentParams {
postComment: IPostComment;
post: IPost;
text: string;
}
export interface ReplyToPostCommentParams {
postComment: IPostComment;
post: IPost;
text: string;
}
export interface DeletePostCommentParams {
postComment: IPostComment;
post: IPost;
}
export interface DeletePostParams {
post: IPost;
}
export interface GetPostParams {
postUuid: string;
}
export interface CreatePostParams {
text?: string;
circles?: ICircle[];
isDraft?: boolean;
}
export interface AddMediaToPostParams {
media: OkFile;
post: IPost;
}
export interface PublishPostParams {
post: IPost;
}
export interface GetPostStatusParams {
post: IPost;
}
export interface GetPostMediaParams {
post: IPost;
}
export interface ReactToPostParams {
post: IPost;
emoji: IEmoji;
}
export interface DeletePostReactionParams {
postReaction: IPostReaction;
post: IPost;
}
export interface GetPostReactionsParams {
post: IPost;
count?: number;
maxId?: number;
emojiId?: number;
}
export interface GetPostCommentReactionsParams {
count?: number;
maxId?: number;
emojiId?: number;
postComment: IPostComment;
post: IPost;
}
export interface GetPostCommentReactionsEmojiApiCountParams {
postComment: IPostComment;
post: IPost;
}
export interface GetPostReactionsEmojiApiCountParams {
post: IPost;
}
export interface ReactToPostCommentParams {
postComment: IPostComment;
post: IPost;
emoji: IEmoji;
}
export interface DeletePostCommentReactionParams {
postCommentReaction: IPostCommentReaction;
postComment: IPostComment;
post: IPost;
}
export interface ReportPostCommentParams {
description?: string;
post: IPost;
postComment: IPostComment;
moderationCategory: IModerationCategory;
}
export interface ReportPostParams {
description?: string;
post: IPost;
moderationCategory: IModerationCategory;
}
export interface OpenPostParams {
post: IPost;
}
export interface ClosePostParams {
post: IPost;
}
export interface EnablePostCommentsParams {
post: IPost;
}
export interface DisablePostCommentsParams {
post: IPost;
}
export interface TranslatePostParams {
post: IPost;
}
export interface TranslatePostCommentParams {
postComment: IPostComment;
post: IPost;
}
// POSTS END
// NOTIFICATIONS START
export interface ReadNotificationsParams {
maxId?: number;
types: NotificationType[]
}
export interface GetNotificationsParams {
maxId?: number;
types: NotificationType[]
count?: number;
}
export interface ReadNotificationParams {
notification: INotification;
}
export interface DeleteNotificationParams {
notification: INotification;
}
export interface GetUnreadNotificationsCountParams {
maxId?: number;
types: NotificationType[]
}
// NOTIFICATIONS END
// FOLLOWS START
export interface FollowUserParams {
user: IUser;
}
export interface RequestToFollowUserParams {
user: IUser;
}
export interface CancelRequestToFollowUserParams {
user: IUser;
}
export interface ApproveFollowRequestFromUserParams {
user: IUser;
}
export interface RejectFollowRequestFromUserParams {
user: IUser;
}
export interface UnfollowUserParams {
user: IUser;
}
// FOLLOWS END
// HASHTAGS START
export interface GetHashtagParams {
hashtagName: string;
appendAuthorizationTokenIfExists?: boolean;
}
export interface GetHashtagPostsParams {
hashtag: IHashtag;
count?: number;
maxId?: number;
appendAuthorizationTokenIfExists?: boolean;
}
export interface SearchHashtagsParams {
query: string;
appendAuthorizationTokenIfExists?: boolean;
}
export interface ReportHashtagParams {
hashtag: IHashtag;
description?: string;
moderationCategory: IModerationCategory;
}
// HASHTAGS END | the_stack |
import {RemoteComponentType} from '@remote-ui/types';
import {
ACTION_MOUNT,
ACTION_INSERT_CHILD,
ACTION_REMOVE_CHILD,
ACTION_UPDATE_PROPS,
ACTION_UPDATE_TEXT,
KIND_ROOT,
KIND_COMPONENT,
KIND_TEXT,
KIND_FRAGMENT,
} from './types';
import type {
Serialized,
RemoteRoot,
RemoteText,
RemoteChannel,
RemoteComponent,
RemoteFragment,
RemoteRootOptions,
RemoteFragmentSerialization,
} from './types';
import {isRemoteFragment} from './utilities';
type AnyChild = RemoteText<any> | RemoteComponent<any, any>;
type AnyNode = AnyChild | RemoteFragment<any>;
type AnyParent =
| RemoteRoot<any, any>
| RemoteComponent<any, any>
| RemoteFragment<any>;
interface RootInternals {
strict: boolean;
mounted: boolean;
channel: RemoteChannel;
nodes: WeakSet<AnyNode>;
tops: WeakMap<AnyNode, AnyParent>;
parents: WeakMap<AnyNode, AnyParent>;
children: ReadonlyArray<AnyChild>;
}
interface ComponentInternals {
externalProps: {readonly [key: string]: any};
internalProps: {readonly [key: string]: any};
children: ReadonlyArray<AnyChild>;
}
interface FragmentInternals {
children: ReadonlyArray<AnyChild>;
}
type ParentInternals = RootInternals | ComponentInternals | FragmentInternals;
interface TextInternals {
text: string;
}
const FUNCTION_CURRENT_IMPLEMENTATION_KEY = '__current';
const EMPTY_OBJECT = {} as any;
const EMPTY_ARRAY: any[] = [];
type HotSwappableFunction<T extends (...args: any[]) => any> = T & {
[FUNCTION_CURRENT_IMPLEMENTATION_KEY]: any;
};
export function createRemoteRoot<
AllowedComponents extends RemoteComponentType<
string,
any
> = RemoteComponentType<any, any>,
AllowedChildrenTypes extends AllowedComponents | boolean = true,
>(
channel: RemoteChannel,
{strict = true, components}: RemoteRootOptions<AllowedComponents> = {},
): RemoteRoot<AllowedComponents, AllowedChildrenTypes> {
type Root = RemoteRoot<AllowedComponents, AllowedChildrenTypes>;
let currentId = 0;
const rootInternals: RootInternals = {
strict,
mounted: false,
channel,
children: EMPTY_ARRAY,
nodes: new WeakSet(),
parents: new WeakMap(),
tops: new WeakMap(),
};
if (strict) Object.freeze(components);
const remoteRoot: Root = {
kind: KIND_ROOT,
options: strict
? Object.freeze({strict, components})
: {strict, components},
get children() {
return rootInternals.children as any;
},
createComponent(type, ...rest) {
if (components && components.indexOf(type) < 0) {
throw new Error(`Unsupported component: ${type}`);
}
const [initialProps, initialChildren, ...moreChildren] = rest;
const normalizedInitialProps = initialProps ?? {};
const normalizedInitialChildren: AnyChild[] = [];
const normalizedInternalProps: {[key: string]: any} = {};
if (initialProps) {
for (const key of Object.keys(initialProps)) {
// "children" as a prop can be extremely confusing with the "children" of
// a component. In React, a "child" can be anything, but once it reaches
// a host environment (like this remote `Root`), we want "children" to have
// only one meaning: the actual, resolved children components and text.
//
// To enforce this, we delete any prop named "children". We don’t take a copy
// of the props for performance, so a user calling this function must do so
// with an object that can handle being mutated.
if (key === 'children') continue;
normalizedInternalProps[key] = makeValueHotSwappable(
serializeProp(initialProps[key]),
);
}
}
if (initialChildren) {
if (Array.isArray(initialChildren)) {
for (const child of initialChildren) {
normalizedInitialChildren.push(normalizeChild(child, remoteRoot));
}
} else {
normalizedInitialChildren.push(
normalizeChild(initialChildren, remoteRoot),
);
// The complex tuple type of `rest` makes it so `moreChildren` is
// incorrectly inferred as potentially being the props of the component,
// lazy casting since we know it will be an array of child elements
// (or empty).
for (const child of moreChildren as any[]) {
normalizedInitialChildren.push(normalizeChild(child, remoteRoot));
}
}
}
const id = `${currentId++}`;
const internals: ComponentInternals = {
externalProps: strict
? Object.freeze(normalizedInitialProps)
: normalizedInitialProps,
internalProps: normalizedInternalProps,
children: strict
? Object.freeze(normalizedInitialChildren)
: normalizedInitialChildren,
};
const component: RemoteComponent<AllowedComponents, Root> = {
kind: KIND_COMPONENT,
get children() {
return internals.children;
},
get props() {
return internals.externalProps;
},
get remoteProps() {
return internals.internalProps;
},
updateProps: (newProps) =>
updateProps(component, newProps, internals, rootInternals),
appendChild: (child) =>
appendChild(
component,
normalizeChild(child, remoteRoot),
internals,
rootInternals,
),
removeChild: (child) =>
removeChild(component, child, internals, rootInternals),
insertChildBefore: (child, before) =>
insertChildBefore(
component,
normalizeChild(child, remoteRoot),
before,
internals,
rootInternals,
),
// Just satisfying the type definition, since we need to write
// some properties manually, which we do below. If we just `as any`
// the whole object, we lose the implicit argument types for the
// methods above.
...EMPTY_OBJECT,
};
Object.defineProperty(component, 'type', {
value: type,
configurable: false,
writable: false,
enumerable: true,
});
makePartOfTree(component, rootInternals);
makeRemote(component, id, remoteRoot);
for (const child of internals.children) {
moveNodeToContainer(component, child, rootInternals);
}
return component;
},
createText(content = '') {
const id = `${currentId++}`;
const internals: TextInternals = {text: content};
const text: RemoteText<Root> = {
kind: KIND_TEXT,
get text() {
return internals.text;
},
updateText: (newText) =>
updateText(text, newText, internals, rootInternals),
// Just satisfying the type definition, since we need to write
// some properties manually.
...EMPTY_OBJECT,
};
makePartOfTree(text, rootInternals);
makeRemote(text, id, remoteRoot);
return text;
},
createFragment() {
const id = `${currentId++}`;
const internals: FragmentInternals = {
children: strict ? Object.freeze([]) : [],
};
const fragment: RemoteFragment<Root> = {
kind: KIND_FRAGMENT,
get children() {
return internals.children;
},
appendChild: (child) =>
appendChild(
fragment,
normalizeChild(child, remoteRoot),
internals,
rootInternals,
),
removeChild: (child) =>
removeChild(fragment, child, internals, rootInternals),
insertChildBefore: (child, before) =>
insertChildBefore(
fragment,
normalizeChild(child, remoteRoot),
before,
internals,
rootInternals,
),
// Just satisfying the type definition, since we need to write
// some properties manually.
...EMPTY_OBJECT,
};
makePartOfTree(fragment, rootInternals);
makeRemote(fragment, id, remoteRoot);
return fragment;
},
appendChild: (child) =>
appendChild(
remoteRoot,
normalizeChild(child, remoteRoot),
rootInternals,
rootInternals,
),
removeChild: (child) =>
removeChild(remoteRoot, child, rootInternals, rootInternals),
insertChildBefore: (child, before) =>
insertChildBefore(
remoteRoot,
normalizeChild(child, remoteRoot),
before,
rootInternals,
rootInternals,
),
mount() {
if (rootInternals.mounted) return Promise.resolve();
rootInternals.mounted = true;
return Promise.resolve(
channel(ACTION_MOUNT, rootInternals.children.map(serializeChild)),
);
},
};
return remoteRoot;
}
function connected(element: AnyNode, {tops}: RootInternals) {
return tops.get(element)?.kind === KIND_ROOT;
}
function allDescendants(element: AnyNode, withEach: (item: AnyNode) => void) {
const recurse = (element: AnyNode) => {
if ('children' in element) {
for (const child of element.children) {
withEach(child);
recurse(child);
}
}
};
recurse(element);
}
function perform(
element: AnyChild | AnyParent,
rootInternals: RootInternals,
{
remote,
local,
}: {
remote(channel: RemoteChannel): void | Promise<void>;
local(): void;
},
) {
const {mounted, channel} = rootInternals;
if (
mounted &&
(element.kind === KIND_ROOT || connected(element, rootInternals))
) {
// should only create context once async queue is cleared
remote(channel);
// technically, we should be waiting for the remote update to apply,
// then apply it locally. The implementation below is too naive because
// it allows local updates to get out of sync with remote ones.
// if (remoteResult == null || !('then' in remoteResult)) {
// local();
// return;
// } else {
// return remoteResult.then(() => {
// local();
// });
// }
}
local();
}
function updateText(
text: RemoteText<any>,
newText: string,
internals: TextInternals,
rootInternals: RootInternals,
) {
return perform(text, rootInternals, {
remote: (channel) => channel(ACTION_UPDATE_TEXT, text.id, newText),
local: () => {
internals.text = newText;
},
});
}
type HotSwapRecord = readonly [HotSwappableFunction<any>, any];
const IGNORE = Symbol('ignore');
function updateProps(
component: RemoteComponent<any, any>,
newProps: any,
internals: ComponentInternals,
rootInternals: RootInternals,
) {
const {strict} = rootInternals;
const {internalProps: currentProps, externalProps: currentExternalProps} =
internals;
const normalizedNewProps: {[key: string]: any} = {};
const hotSwapFunctions: HotSwapRecord[] = [];
let hasRemoteChange = false;
for (const key of Object.keys(newProps)) {
// See notes above for why we treat `children` as a reserved prop.
if (key === 'children') continue;
const currentExternalValue = currentExternalProps[key];
const newExternalValue = newProps[key];
const currentValue = currentProps[key];
const newValue = serializeProp(newExternalValue);
// Bail out if we have equal, primitive types
if (
currentValue === newValue &&
(newValue == null || typeof newValue !== 'object')
) {
continue;
}
const [value, hotSwaps] = tryHotSwappingValues(currentValue, newValue);
if (hotSwaps) {
hotSwapFunctions.push(...hotSwaps);
}
if (value === IGNORE) continue;
hasRemoteChange = true;
normalizedNewProps[key] = value;
if (isRemoteFragment(currentExternalValue)) {
removeNodeFromContainer(currentExternalValue, rootInternals);
}
if (isRemoteFragment(newExternalValue)) {
moveNodeToContainer(component, newExternalValue, rootInternals);
}
}
return perform(component, rootInternals, {
remote: (channel) => {
if (hasRemoteChange) {
channel(ACTION_UPDATE_PROPS, component.id, normalizedNewProps);
}
},
local: () => {
const mergedExternalProps = {
...currentExternalProps,
...newProps,
};
internals.externalProps = strict
? Object.freeze(mergedExternalProps)
: mergedExternalProps;
internals.internalProps = {
...internals.internalProps,
...normalizedNewProps,
};
for (const [hotSwappable, newValue] of hotSwapFunctions) {
hotSwappable[FUNCTION_CURRENT_IMPLEMENTATION_KEY] = newValue;
}
},
});
}
// Imagine the following remote-ui components we might render in a remote context:
//
// const root = createRemoteRoot();
// const {value, onChange, onPress} = getPropsForValue();
//
// const textField = root.createComponent('TextField', {value, onChange});
// const button = root.createComponent('Button', {onPress});
//
// root.appendChild(textField);
// root.appendChild(button);
//
// function getPropsForValue(value = '') {
// return {
// value,
// onChange: () => {
// const {value, onChange, onPress} = getPropsForValue();
// textField.updateProps({value, onChange});
// button.updateProps({onPress});
// },
// onPress: () => console.log(value),
// };
// }
//
//
// In this example, assume that the `TextField` `onChange` prop is run on blur.
// If this were running on the host, the following steps would happen if you pressed
// on the button:
//
// 1. The text field blurs, and so calls `onChange()` with its current value, which
// then calls `setValue()` with the updated value.
// 2. We synchronously update the `value`, `onChange`, and `onPress` props to point at
// the most current `value`.
// 3. Handling blur is finished, so the browser now handles the click by calling the
// (newly-updated) `Button` `onPress()`, which logs out the new value.
//
// Because remote-ui reproduces a UI tree asynchronously from the remote context, the
// steps above run in a different order:
//
// 1. The text field blurs, and so calls `onChange()` with its current value.
// 2. Handling blur is finished **from the perspective of the main thread**, so the
// browser now handles the click by calling the (original) `Button` `onPress()`, which
// logs out the **initial** value.
// 3. In the remote context, we receive the `onChange()` call, which calls updates the props
// on the `Button` and `TextField` to be based on the new `value`, but by now it’s
// already too late for `onPress` — the old version has already been called!
//
// As you can see, the timing issue introduced by the asynchronous nature of remote-ui
// can cause “old props” to be called from the main thread. This example may seem like
// an unusual pattern, and it is if you are using `@remote-ui/core` directly; you’d generally
// keep a mutable reference to the state, instead of closing over the state with new props.
// However, abstractions on top of `@remote-ui/core`, like the React reconciler in
// `@remote-ui/react`, work almost entirely by closing over state, so this issue is
// much more common with those declarative libraries.
//
// To protect against this, we handle function props a bit differently. When we have a
// function prop, we replace it with a new function that calls the original. However,
// we make the original mutable, by making it a property on the function itself. When
// this function subsequently updates, we don’t send the update to the main thread (as
// we just saw, this can often be "too late" to be of any use). Instead, we swap out
// the mutable reference to the current implementation of the function prop, which can
// be done synchronously. In the example above, this would all happen synchronously in
// the remote context; in our handling of `TextField onChange()`, we update `Button onPress()`,
// and swap out the implementations. Now, when the main thread attempts to call `Button onPress()`,
// it instead calls our wrapper around the function, which can refer to, and call, the
// most recently-applied implementation, instead of directly calling the old implementation.
function tryHotSwappingValues(
currentValue: unknown,
newValue: unknown,
): [any, HotSwapRecord[]?] {
if (
typeof currentValue === 'function' &&
FUNCTION_CURRENT_IMPLEMENTATION_KEY in currentValue
) {
return [
typeof newValue === 'function' ? IGNORE : makeValueHotSwappable(newValue),
[[currentValue as HotSwappableFunction<any>, newValue]],
];
}
if (Array.isArray(currentValue)) {
return tryHotSwappingArrayValues(currentValue, newValue);
}
if (
typeof currentValue === 'object' &&
currentValue != null &&
!isRemoteFragment(currentValue)
) {
return tryHotSwappingObjectValues(currentValue, newValue);
}
return [currentValue === newValue ? IGNORE : newValue];
}
function makeValueHotSwappable(value: unknown): unknown {
if (isRemoteFragment(value)) {
return value;
}
if (typeof value === 'function') {
const wrappedFunction: HotSwappableFunction<any> = ((...args: any[]) => {
return wrappedFunction[FUNCTION_CURRENT_IMPLEMENTATION_KEY](...args);
}) as any;
Object.defineProperty(
wrappedFunction,
FUNCTION_CURRENT_IMPLEMENTATION_KEY,
{
enumerable: false,
configurable: false,
writable: true,
value,
},
);
return wrappedFunction;
} else if (Array.isArray(value)) {
return value.map(makeValueHotSwappable);
} else if (typeof value === 'object' && value != null) {
return Object.keys(value).reduce<{[key: string]: any}>((newValue, key) => {
newValue[key] = makeValueHotSwappable((value as any)[key]);
return newValue;
}, {});
}
return value;
}
// eslint-disable-next-line consistent-return
function collectNestedHotSwappableValues(
value: unknown,
): HotSwappableFunction<any>[] | undefined {
if (typeof value === 'function') {
if (FUNCTION_CURRENT_IMPLEMENTATION_KEY in value) return [value];
} else if (Array.isArray(value)) {
return value.reduce<HotSwappableFunction<any>[]>((all, element) => {
const nested = collectNestedHotSwappableValues(element);
return nested ? [...all, ...nested] : all;
}, []);
} else if (typeof value === 'object' && value != null) {
return Object.keys(value).reduce<HotSwappableFunction<any>[]>(
(all, key) => {
const nested = collectNestedHotSwappableValues((value as any)[key]);
return nested ? [...all, ...nested] : all;
},
[],
);
}
}
function appendChild(
container: AnyParent,
child: AnyChild,
internals: ParentInternals,
rootInternals: RootInternals,
) {
const {nodes, strict} = rootInternals;
if (!nodes.has(child)) {
throw new Error(
`Cannot append a node that was not created by this remote root`,
);
}
return perform(container, rootInternals, {
remote: (channel) =>
channel(
ACTION_INSERT_CHILD,
(container as any).id,
container.children.length,
serializeChild(child),
),
local: () => {
moveNodeToContainer(container, child, rootInternals);
const mergedChildren = [...internals.children, child];
internals.children = strict
? Object.freeze(mergedChildren)
: mergedChildren;
},
});
}
// there is a problem with this, because when multiple children
// are removed, there is no guarantee the messages will arrive in the
// order we need them to on the host side (it depends how React
// calls our reconciler). If it calls with, for example, the removal of
// the second last item, then the removal of the last item, it will fail
// because the indexes moved around.
//
// Might need to send the removed child ID, or find out if we
// can collect removals into a single update.
function removeChild(
container: AnyParent,
child: AnyChild,
internals: ParentInternals,
rootInternals: RootInternals,
) {
const {strict} = rootInternals;
return perform(container, rootInternals, {
remote: (channel) =>
channel(
ACTION_REMOVE_CHILD,
(container as any).id,
container.children.indexOf(child as any),
),
local: () => {
removeNodeFromContainer(child, rootInternals);
const newChildren = [...internals.children];
newChildren.splice(newChildren.indexOf(child), 1);
internals.children = strict ? Object.freeze(newChildren) : newChildren;
},
});
}
function insertChildBefore(
container: AnyParent,
child: AnyChild,
before: AnyChild,
internals: ParentInternals,
rootInternals: RootInternals,
) {
const {strict, nodes} = rootInternals;
if (!nodes.has(child)) {
throw new Error(
`Cannot insert a node that was not created by this remote root`,
);
}
return perform(container, rootInternals, {
remote: (channel) =>
channel(
ACTION_INSERT_CHILD,
(container as any).id,
container.children.indexOf(before as any),
serializeChild(child),
),
local: () => {
moveNodeToContainer(container, child, rootInternals);
const newChildren = [...internals.children];
newChildren.splice(newChildren.indexOf(before), 0, child);
internals.children = strict ? Object.freeze(newChildren) : newChildren;
},
});
}
function normalizeChild(
child: AnyChild | string,
root: RemoteRoot<any, any>,
): AnyChild {
return typeof child === 'string' ? root.createText(child) : child;
}
function moveNodeToContainer(
container: AnyParent,
node: AnyNode,
rootInternals: RootInternals,
) {
const {tops, parents} = rootInternals;
const newTop =
container.kind === KIND_ROOT ? container : tops.get(container)!;
tops.set(node, newTop);
parents.set(node, container);
moveFragmentToContainer(node, rootInternals);
allDescendants(node, (descendant) => {
tops.set(descendant, newTop);
moveFragmentToContainer(descendant, rootInternals);
});
}
function moveFragmentToContainer(node: AnyNode, rootInternals: RootInternals) {
if (node.kind !== KIND_COMPONENT) return;
const props = node.props as any;
if (!props) return;
Object.values(props).forEach((prop) => {
if (!isRemoteFragment(prop)) return;
moveNodeToContainer(node, prop, rootInternals);
});
}
function removeNodeFromContainer(node: AnyNode, rootInternals: RootInternals) {
const {tops, parents} = rootInternals;
tops.delete(node);
parents.delete(node);
allDescendants(node, (descendant) => {
tops.delete(descendant);
removeFragmentFromContainer(descendant, rootInternals);
});
removeFragmentFromContainer(node, rootInternals);
}
function removeFragmentFromContainer(
node: AnyNode,
rootInternals: RootInternals,
) {
if (node.kind !== KIND_COMPONENT) return;
const props = node.remoteProps as any;
for (const key of Object.keys(props ?? {})) {
const prop = props[key];
if (!isRemoteFragment(prop)) continue;
removeNodeFromContainer(prop, rootInternals);
}
}
function makePartOfTree(node: AnyNode, {parents, tops, nodes}: RootInternals) {
nodes.add(node);
Object.defineProperty(node, 'parent', {
get() {
return parents.get(node);
},
configurable: true,
enumerable: true,
});
Object.defineProperty(node, 'top', {
get() {
return tops.get(node);
},
configurable: true,
enumerable: true,
});
}
function serializeChild(value: AnyChild): Serialized<typeof value> {
return value.kind === KIND_TEXT
? {id: value.id, kind: value.kind, text: value.text}
: {
id: value.id,
kind: value.kind,
type: value.type,
props: value.remoteProps,
children: value.children.map((child) => serializeChild(child)),
};
}
function serializeProp(prop: any) {
if (isRemoteFragment(prop)) {
return serializeFragment(prop);
}
return prop;
}
function serializeFragment(
value: RemoteFragment<any>,
): RemoteFragmentSerialization {
return {
id: value.id,
kind: value.kind,
get children() {
return value.children.map((child) => serializeChild(child));
},
};
}
function makeRemote<Root extends RemoteRoot<any, any>>(
value: RemoteText<Root> | RemoteComponent<any, Root> | RemoteFragment<Root>,
id: string,
root: Root,
) {
Object.defineProperty(value, 'id', {
value: id,
configurable: true,
writable: false,
enumerable: false,
});
Object.defineProperty(value, 'root', {
value: root,
configurable: true,
writable: false,
enumerable: false,
});
}
function tryHotSwappingObjectValues(
// eslint-disable-next-line @typescript-eslint/ban-types
currentValue: object,
newValue: unknown,
): [any, HotSwapRecord[]?] {
if (typeof newValue !== 'object' || newValue == null) {
return [
makeValueHotSwappable(newValue),
collectNestedHotSwappableValues(currentValue)?.map(
(hotSwappable) => [hotSwappable, undefined] as const,
),
];
}
let hasChanged = false;
const hotSwaps: HotSwapRecord[] = [];
const normalizedNewValue: {[key: string]: any} = {};
// eslint-disable-next-line guard-for-in
for (const key in currentValue) {
const currentObjectValue = (currentValue as any)[key];
if (!(key in newValue)) {
hasChanged = true;
const nestedHotSwappables =
collectNestedHotSwappableValues(currentObjectValue);
if (nestedHotSwappables) {
hotSwaps.push(
...nestedHotSwappables.map(
(hotSwappable) => [hotSwappable, undefined] as const,
),
);
}
}
const newObjectValue = (newValue as any)[key];
const [updatedValue, elementHotSwaps] = tryHotSwappingValues(
currentObjectValue,
newObjectValue,
);
if (elementHotSwaps) hotSwaps.push(...elementHotSwaps);
if (updatedValue !== IGNORE) {
hasChanged = true;
normalizedNewValue[key] = updatedValue;
}
}
for (const key in newValue) {
if (key in normalizedNewValue) continue;
hasChanged = true;
normalizedNewValue[key] = makeValueHotSwappable((newValue as any)[key]);
}
return [hasChanged ? normalizedNewValue : IGNORE, hotSwaps];
}
function tryHotSwappingArrayValues(
currentValue: unknown[],
newValue: unknown,
): [any, HotSwapRecord[]?] {
if (!Array.isArray(newValue)) {
return [
makeValueHotSwappable(newValue),
collectNestedHotSwappableValues(currentValue)?.map(
(hotSwappable) => [hotSwappable, undefined] as const,
),
];
}
let hasChanged = false;
const hotSwaps: HotSwapRecord[] = [];
const newLength = newValue.length;
const currentLength = currentValue.length;
const maxLength = Math.max(currentLength, newLength);
const normalizedNewValue: any[] = [];
for (let i = 0; i < maxLength; i++) {
const currentArrayValue = currentValue[i];
const newArrayValue = newValue[i];
if (i < newLength) {
if (i >= currentLength) {
hasChanged = true;
normalizedNewValue[i] = makeValueHotSwappable(newArrayValue);
continue;
}
const [updatedValue, elementHotSwaps] = tryHotSwappingValues(
currentArrayValue,
newArrayValue,
);
if (elementHotSwaps) hotSwaps.push(...elementHotSwaps);
if (updatedValue === IGNORE) {
normalizedNewValue[i] = currentArrayValue;
continue;
}
hasChanged = true;
normalizedNewValue[i] = updatedValue;
} else {
hasChanged = true;
const nestedHotSwappables =
collectNestedHotSwappableValues(currentArrayValue);
if (nestedHotSwappables) {
hotSwaps.push(
...nestedHotSwappables.map(
(hotSwappable) => [hotSwappable, undefined] as const,
),
);
}
}
}
return [hasChanged ? normalizedNewValue : IGNORE, hotSwaps];
} | the_stack |
import { ClassDeclaration } from "../components/constructs/class";
import { ReturnStatement } from "../components/statements/statement";
import { Expression, Operation, VariableReference } from "../components/value/expression";
import { IfStatement, ElseStatement } from "../components/statements/if";
import { ValueTypes, Type, Value } from "../components/value/value";
import { ArgumentList, FunctionDeclaration } from "../components/constructs/function";
import { TemplateLiteral } from "../components/value/template-literal";
import { ObjectLiteral } from "../components/value/object";
import { ForIteratorExpression, ForStatementExpression, ForStatement } from "../components/statements/for";
import { VariableDeclaration } from "../components/statements/variable";
import { ArrayLiteral } from "../components/value/array";
import { astTypes } from "../javascript";
/**
* Returns variables spanning from "this.*"
* @param cls
*/
export function getVariablesInClass(cls: ClassDeclaration): Array<VariableReference> {
const variables: Array<VariableReference> = [];
for (const member of cls.members) {
for (const variable of findVariables(member)) {
if (variable.toChain()[0] === "this") {
variables.push(variable);
}
}
}
return variables;
}
/**
* Walks through a statement and yields ALL variable references
* TODO parent should maybe have a key of structure
* @param parent Used for replacing variables
*/
export function variableReferenceWalker(
statement: astTypes,
parent?: astTypes
): Array<{ variable: VariableReference, parent: astTypes }> {
const variables: Array<{ variable: VariableReference, parent: astTypes }> = []
if (statement instanceof VariableReference) {
variables.push({ variable: statement, parent: parent! });
} else if (statement instanceof Expression) {
if (statement.operation === Operation.OptionalChain) {
variables.push({ variable: variableReferenceFromOptionalChain(statement), parent: parent! });
} else {
variables.push(...variableReferenceWalker(statement.lhs, statement));
if (statement.rhs) variables.push(...variableReferenceWalker(statement.rhs, statement));
}
} else if (statement instanceof ReturnStatement) {
if (statement.returnValue) variables.push(...variableReferenceWalker(statement.returnValue, statement));
} else if (statement instanceof FunctionDeclaration) {
for (const statementInFunc of statement.statements) {
variables.push(...variableReferenceWalker(statementInFunc, statement));
}
} else if (statement instanceof ArgumentList) {
for (const value of statement.args) {
variables.push(...variableReferenceWalker(value, statement));
}
} else if (statement instanceof TemplateLiteral) {
for (const value of statement.entries) {
if (typeof value !== "string") variables.push(...variableReferenceWalker(value, statement));
}
} else if (statement instanceof ObjectLiteral) {
for (const [, value] of statement.values) {
variables.push(...variableReferenceWalker(value, statement))
}
} else if (statement instanceof ForIteratorExpression) {
variables.push(...variableReferenceWalker(statement.subject, statement));
} else if (statement instanceof ForStatement) {
variables.push(...variableReferenceWalker(statement.expression, statement));
for (const s of statement.statements) {
variables.push(...variableReferenceWalker(s, statement));
}
} else if (statement instanceof IfStatement) {
variables.push(...variableReferenceWalker(statement.condition, statement));
for (const s of statement.statements) {
variables.push(...variableReferenceWalker(s, statement));
}
}
return variables;
}
/**
* Mimic constructor signature of `VariableReference` but uses optional chain
*/
export function newOptionalVariableReference(name: string, parent: ValueTypes) {
return new Expression({
lhs: parent,
operation: Operation.OptionalChain,
rhs: new VariableReference(name)
});
}
/**
* Mimics `VariableReference.fromChain` but uses optional chain and optional index
*/
export function newOptionalVariableReferenceFromChain(...items: Array<string | number | ValueTypes>): ValueTypes {
let head: ValueTypes;
if (typeof items[0] === "number") {
throw Error("First arg to newOptionalVariableReferenceFromChain must be string");
} else if (typeof items[0] === "string") {
head = new VariableReference(items[0] as string);
} else {
head = items[0];
}
// Iterator through items appending forming linked list
for (let i = 1; i < items.length; i++) {
const currentProp = items[i];
if (typeof currentProp === "number") {
head = new Expression({
lhs: head,
operation: Operation.OptionalIndex,
rhs: new Value(Type.number, currentProp)
});
} else if (typeof currentProp === "string") {
head = new Expression({
lhs: head,
operation: Operation.OptionalChain,
rhs: new VariableReference(currentProp)
});
} else if (currentProp instanceof VariableReference) {
head = new Expression({
lhs: head,
operation: Operation.OptionalChain,
rhs: currentProp
});
} else {
throw Error("Cannot use prop in fromChain");
}
}
return head;
}
/**
* Returns a definite variable reference from a optional variable reference
* @param expr
* @example `a?.b?.c` -> `a.b.c`
*/
export function variableReferenceFromOptionalChain(expr: Expression): VariableReference {
if (expr.operation !== Operation.OptionalChain) {
throw Error(`Expected optional chain received ${Operation[expr.operation]}`);
}
return new VariableReference(
(expr.rhs as VariableReference).name,
expr.lhs instanceof Expression && expr.lhs.operation === Operation.OptionalChain ? variableReferenceFromOptionalChain(expr.lhs) : expr.lhs
);
}
/**
* Returns variables in a statement
* @param allVariables whether to return
*/
export function findVariables(statement: astTypes, allVariables: boolean = false): Array<VariableReference> {
const variables: Array<VariableReference> = [];
for (const {variable} of variableReferenceWalker(statement)) {
// Check variable has not already been registered
if (allVariables || !variables.some(regVariable => regVariable.isEqual(variable))) {
variables.push(variable);
}
}
return variables;
}
/**
* Alias variables in place
* TODO:
* Duplicate ...
* Also some sort of guard e.g I don't want functions to be aliased
* Pick up on new variables being introduced
* @example (myProp, this) -> this.myProp
* @param locals A set of variables to not alias
*/
export function aliasVariables(
value: astTypes,
parent: VariableReference,
locals: Array<VariableReference> = []
): void {
for (const {variable} of variableReferenceWalker(value)) {
if (!locals.some(local => local.isEqual(variable, true))) {
let parentVariable: VariableReference = variable;
while (parentVariable.parent) {
parentVariable = parentVariable.parent as VariableReference;
}
parentVariable.parent = parent;
}
}
}
/**
* Replaces variable in expression inline
*/
export function replaceVariables(
value: astTypes,
replacer: ValueTypes | ((intercepted: VariableReference) => ValueTypes),
targets: Array<VariableReference>
): void {
for (const {variable, parent} of variableReferenceWalker(value)) {
if (targets.some(targetVariable => targetVariable.isEqual(variable, true))) {
// TODO Needed for fuzzy match. Redundant and slow otherwise
let replaceVariable = variable;
while (!targets.some(targetVariable => targetVariable.isEqual(replaceVariable, false))) {
replaceVariable = variable.parent! as VariableReference;
}
let replacerValue: ValueTypes;
if (typeof replacer === "function") {
replacerValue = replacer(variable);
} else {
replacerValue = replacer;
}
// TODO use parent to not do this:
// Clear keys, reassign to object, set prototype
Object.keys(replaceVariable).forEach(key => delete replaceVariable[key]);
Object.assign(replaceVariable, replacerValue);
Object.setPrototypeOf(replaceVariable, Object.getPrototypeOf(replacerValue));
}
}
}
/**
* TODO temp
* Could do by rendering out ast and re parsing lol
*/
export function cloneAST(part: astTypes) {
if (part === null) return null;
if (part instanceof VariableReference) {
return new VariableReference(part.name, part.parent ? cloneAST(part.parent) : undefined);
} else if (part instanceof Value) {
return new Value(part.type, part.value ?? "");
} else if (part instanceof Expression) {
return new Expression({
lhs: cloneAST(part.lhs),
operation: part.operation,
rhs: part.rhs ? cloneAST(part.rhs) : undefined
});
} else if (part instanceof IfStatement) {
return new IfStatement(
cloneAST(part.condition),
part.statements,
part.consequent ? cloneAST(part.consequent) : undefined
);
} else if (part instanceof ElseStatement) {
return new ElseStatement(
part.condition ? cloneAST(part.condition) : undefined,
part.statements,
part.consequent ? cloneAST(part.consequent) : undefined);
} else if (part instanceof TemplateLiteral) {
return new TemplateLiteral(
part.entries.map(entry => typeof entry === "string" ? entry : cloneAST(entry)),
part.tag
);
} else if (part instanceof ArgumentList) {
return new ArgumentList(part.args.map(arg => cloneAST(arg)));
} else if (part instanceof ForIteratorExpression) {
return new ForIteratorExpression(cloneAST(part.variable), part.operation, cloneAST(part.subject));
} else if (part instanceof VariableDeclaration) {
return new VariableDeclaration(part.entries ?? part.name, { ...part });
} else if (part instanceof ForIteratorExpression) {
return new ForIteratorExpression(cloneAST(part.variable), part.operation, cloneAST(part.subject));
} else if (part instanceof ArrayLiteral) {
return new ArrayLiteral(part.elements.map(cloneAST));
} else if (part instanceof ForStatementExpression) {
return new ForStatementExpression(
part.initializer ? cloneAST(part.initializer) : null,
part.condition ? cloneAST(part.condition) : null,
part.finalExpression ? cloneAST(part.finalExpression) : null
);
} else if (part instanceof ObjectLiteral) {
return new ObjectLiteral(
part.values ? new Map(Array.from(part.values.entries()).map(([key, value]) => [key, cloneAST(value)])) : undefined,
part.spreadValues ? new Set(Array.from(part.spreadValues).map(value => cloneAST(value))) : undefined,
);
} else {
throw Error(`Could not clone part of instance "${part.constructor.name}"`)
}
} | the_stack |
export namespace Typeform {
/**
* Object that defines the Logic Jump's behavior.
*/
export interface Action {
/**
* Behavior the Logic Jump will take.
*/
action?: 'jump' | 'add' | 'subtract' | 'multiply' | 'divide'
/**
* Properties that further specify how the Logic Jump will behave.
*/
details?: ActionDetails
/**
* Conditions for executing the Logic Jump. Conditions answer the question, "Under what circumstances?"
* The condition object is the IF statement in your Logic Jump.
*/
condition?: Condition
}
/**
* Properties that further specify how the Logic Jump will behave.
*/
export interface ActionDetails {
/**
* Specifies where the Logic Jump leads---to another field ("field"), a Hidden Field ("hidden"), or thank you screen ("thankyou").
*/
to?: {
/**
* Logic Jump "to" option you are using.
*/
type?: 'field' | 'hidden' | 'thankyou'
/**
* The "ref" value for the field, Hidden Field, or thank you screen the Logic Jump leads to.
*/
value?: string
}
/**
* Keeps a running total for the `score` or `price` variable.
*/
target?: {
/**
* Specifies that the value is a variable.
*/
type?: 'variable'
/**
* Variable value to use in calculation.
*/
value?: 'score' | 'price'
}
/**
* Specifies the numeric value to use in the calculation for the `score` or `price` variable.
*/
value?: {
/**
* Specifies that the numeric value is a constant.
*/
type?: 'constant'
/**
* Numeric value to use in calculation.
*/
value?: number
}
}
export namespace API {
export namespace Forms {
export interface List {
total_items: number
page_count: number
items: {
id: string
title: string
last_updated_at: string
settings: {
},
self: {
href: string
},
theme: {
href: string
},
_links: {
display: string
}
}[]
}
}
export namespace Responses {
export interface List {
total_items: number
page_count: number
items: Response[]
}
}
export namespace Webhooks {
export interface List {
items: Webhook[]
}
}
export namespace Workspaces {
export interface List {
total_items: number
page_count: number
items: Workspace[]
}
}
export interface PATCH {
op: string
path: string
value: any
}
}
/**
* Base URL of Typeform API.
*/
export type API_URL = 'https://api.typeform.com'
/**
* Attachment to include as image, video, or `picture_choice`.
*/
export interface Attachment {
/**
* Type of attachment.
*/
type?: 'image' | 'video'
/**
* URL for the image or video you want to display.
* Images must already exist in your account---use the image's Typeform URL, such as `"https://images.typeform.com/images/kbn8tc98AHb"`.
* For videos, use the video's YouTube.com URL.
*/
href?: string
/**
* Optional parameter for responsively scaling videos. Available only for `"video"` type. Default value is 0.6
*/
scale?: 0.4 | 0.6 | 0.8 | 1
}
/**
* Choice answer for a properties's choices property of a field.
*/
export interface Choice {
/**
* Readable name you can use to reference the answer choice. Available for `multiple_choice` and `picture_choice` types.
* Not available for dropdown types.
*/
ref?: string
/**
* Text for the answer choice.
*/
label?: string
/**
* Identifies the image to use for the answer choice. Available only for `picture_choice` types.
*/
attachment?: Attachment
}
/**
* Argument object for Typeform API client
*/
export interface ClientArg extends DocumentData {
token?: string
}
/**
* Conditions for executing the Logic Jump. Conditions answer the question, "Under what circumstances?"
* The condition object is the IF statement in your Logic Jump.
*/
export interface Condition {
/**
* Operator for the condition.
*/
op?: 'begins_with' | 'ends_with' | 'contains' | 'not_contains' | 'lower_than' | 'lower_equal_than' | 'greater_than'
| 'greater_equal_than' | 'is' | 'is_not' | 'equal' | 'not_equal' | 'always' | 'on' | 'not_on' | 'earlier_than' | 'earlier_than_or_on'
| 'later_than' | 'later_than_or_on'
/**
* Object that defines the field type and value to evaluate with the operator.
*/
vars?: {
/**
* Type of value the condition object refers to.
*/
type?: 'field' | 'hidden' | 'variable' | 'constant' | 'end'
/**
* Value to check for in the "type" field to evaluate with the operator.
*/
value?: any
}[]
}
/**
* Generic document.
*/
export interface DocumentData {
[key: string]: any
}
/**
* Object that represents a field in the form and its properties, validations, and attachments.
*/
export interface Field {
/**
* The unique ID for the question.
*/
id?: string
/**
* Readable name you can use to reference the field.
*/
ref?: string
/**
* Unique name you assign to the field on this form.
*/
title?: string
/**
* The type of field.
*/
type?: Type
/**
* Properties of a field.
*/
properties?: Properties.Field
/**
* Validations of a field.
*/
validations?: Validations
/**
* Attachment of a field.
*/
attachment?: Attachment
}
/**
* Font for the theme.
*/
export type Font = 'Acme' | 'Arial' | 'Arvo' | 'Avenir Next' | 'Bangers' | 'Cabin' | 'Cabin Condensed' | 'Courier' | 'Crete Round'
| 'Dancing Script' | 'Exo' | 'Georgia' | 'Handlee' | 'Helvetica Neue' | 'Karla' | 'Lato' | 'Lekton' | 'Lobster' | 'Lora' | 'McLaren'
| 'Montserrat' | 'Nixie One' | 'Old Standard TT' | 'Open Sans' | 'Oswald' | 'Playfair Display' | 'Quicksand' | 'Raleway' | 'Signika'
| 'Sniglet' | 'Source Sans Pro' | 'Vollkorn'
export interface Form {
/**
* ID of a form.
*/
id?: string
/**
* Title to use for the form.
*/
title?: string
/**
* Language to present a form.
*/
language?: Language
/**
* Array of objects that specify the fields to use in the form and their properties, validations, and attachments.
*/
fields?: Field[]
/**
* Default: `""`
* Array of Hidden Fields to use in the form.
*/
hidden?: string[]
/**
* Array of objects that specify settings and properties for the form's welcome screen.
*/
welcome_screens?: WelcomeScreen[]
/**
* Array of objects that specify settings and properties for the form's thank you screen.
*/
thankyou_screens?: ThankYouScreen[]
/**
* Array of Logic Jump objects to use in the form.
*/
logic?: Logic[]
/**
* Theme to use for the form.
* Treat as string when creating a form/
*/
theme?: {
/**
* URL of the theme to use for the typeform.
* If you don't specify a URL for the theme, Typeform applies a new copy of the default theme to the form.
*/
href?: string
} | string
/**
* Workspace that contains the form.
*/
workspace?: {
/**
* URL of the workspace to use for the typeform.
* If you don't specify a URL for the workspace, Typeform saves the form in the default workspace.
*/
href?: string
}
/**
* Only available when retrieving a form.
*/
_links?: {
display?: string
}
/**
* Object that specifies form settings and metadata, including the language to use for the form,
* whether the form is publicly available, the basis for the progress bar, and search engine indexing settings.
*/
settings?: Settings
/**
* Object that keeps track of total score or price, if you use them in the form.
* Not available when retrieving a form.
*/
variables?: {
/**
* Recall Information for keeping score as users answer each question (for example, for quizzes).
*/
score?: 0
/**
* Recall Information for tracking the total price of all items users select
* (for example, for shopping carts, donation campaigns, and payment collections).
*/
price?: number
}
}
/**
* HTTP Client for API requests.
*/
export interface HTTPClient {
request: (args: Request) => Promise<any>
}
/**
* Typeform Image object.
*/
export interface Image {
/**
* Unique ID for the image.
*/
id?: string
/**
* URL for the image.
*/
src?: string
/**
* File name for the image (specified when image is created).
*/
file_name?: string
/**
* Width of the image in pixels.
*/
width?: number
/**
* Height of the image in pixels.
*/
height?: number
/**
* The MIME type of the image.
*/
media_type?: 'image/gif' | 'image/jpeg' | 'image/png'
/**
* True if image has alpha channel (some degree of transparency). Otherwise, false.
*/
has_alpha?: boolean
/**
* Average color of the image in hexadecimal format.
*/
avg_color?: string
}
/**
* Language that Typeform can be in.
*/
export type Language = 'en' | 'es' | 'ca' | 'fr' | 'de' | 'ru' | 'it' | 'da' | 'pt' | 'ch' | 'zh' | 'nl' | 'no' | 'uk' | 'ja' | 'ko'
| 'hr' | 'fi' | 'sv' | 'pl' | 'el' | 'hu' | 'tr' | 'cs' | 'et' | 'di'
/**
* Logic object of a form.
*/
export interface Logic {
/**
* Specifies whether the Logic Jump is based on a question field or Hidden Field.
*/
type?: 'field' | 'hidden'
/**
* Reference to the field that triggers the the Logic Jump.
*/
ref?: string
/**
* Array of objects that define the Logic Jump's behavior.
*/
actions?: Action[]
}
/**
* Messages that forms can use.
*/
export interface Messages {
/**
* Default tooltip button message. Maximum 28 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.buttonHint.default'?: string
/**
* Tooltip button message for long text blocks. Maximum 28 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.buttonHint.longtext'?: string
/**
* Server connection error message. Maximum 128 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden
*/
'label.warning.connection'?: string
/**
* Default continue button message. Maximum 100 characters.
*/
'label.buttonNoAnswer.default'?: string
/**
* List of errors message. Maximum 128 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.warning.correction'?: string
/**
* Credit card name message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'block.payment.cardNameTitle'?: string
/**
* Credit card number message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'block.payment.cardNumberTitle'?: string
/**
* Credit card security number message
*/
'block.payment.cvcDescription'?: string
/**
* Credit card CVC number message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'block.payment.cvcNumberTitle'?: string
/**
* Text input placeholder. Maximum 100 characters.
*/
'block.shortText.placeholder'?: string
/**
* Invalid email error message. Maximum 64 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.error.emailAddress'?: string
/**
* Credit card expiry month message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.error.expiryMonthTitle'?: string
/**
* Credit card expiry year message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.error.expiryYearTitle'?: string
/**
* Fallback alert message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.warning.fallbackAlert'?: string
/**
* File upload button message. Maximum 34 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'block.fileUpload.choose'?: string
/**
* File upload dragging action message. Maximum 35 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'block.fileUpload.drag'?: string
/**
* Still processing file upload message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'block.fileUpload.uploadingProgress'?: string
/**
* File too big error message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.error.sizeLimit'?: string
/**
* Private form error message. Accepts variable form:name. Maximum 128 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.warning.formUnavailable'?: string
/**
* Incomplete fields error message. Maximum 42 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.error.incompleteForm'?: string
/**
* Key letter hint message. Maximum 100 characters.
*/
'label.hint.key'?: string
/**
* Legal field deny message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'block.legal.reject'?: string
/**
* Legal field accept message. You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'block.legal.accept'?: string
/**
* Number maximum value tooltip message. Accepts variable `field:max`. Maximum 64 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.error.maxValue'?: string
/**
* Text fields maximum length tooltip message. Accepts variable `field:max_length`. Maximum 64 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.error.maxLength'?: string
/**
* Number minimum value tooltip message. Accepts variable `field:min`. Maximum 64 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.error.minValue'?: string
/**
* Number minimum and maximum range value tooltip message. Accepts variables `field:min` and `field:max`. Maximum 64 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.error.range'?: string
/**
* Choose as many as you like message for multiple choice fields. Maximum 45 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'block.multipleChoice.hint'?: string
/**
* Required value error message. Maximum 64 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.error.mustEnter'?: string
/**
* Required selection error message. Maximum 64 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.error.mustSelect'?: string
/**
* Keyboard shortcut for the "No" option. Maximum 1 character.
*/
'label.no.shortcut'?: string
/**
* Representation for the word "No." You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.no.default'?: string
/**
* Not suggestions found for dropdown fields error message. Maximum 64 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'block.dropdown.hint'?: string
/**
* Other answer message. Maximum 100 characters.
*/
'block.multipleChoice.other'?: string
/**
* Completion percentage message. Accepts variable `progress:percent`. Maximum 100 characters.
*/
'label.progress.percent'?: string
/**
* Completion proportion message. Accepts variables `progress:step` and `progress:total`. Maximum 100 characters.
*/
'label.progress.proportion'?: string
/**
* Required field error message. Maximum 64 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.error.required'?: string
/**
* Review fields error message. Accepts variable `form:unanswered_fields`. Maximum 64 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.preview'?: string
/**
* Review button message. Maximum 100 characters.
*/
'label.button.review'?: string
/**
* Server error message. Maximum 128 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.error.server'?: string
/**
* Share text message. Maximum 100 characters.
*/
'label.action.share'?: string
/**
* Submit button message. Maximum 100 characters.
*/
'label.button.submit'?: string
/**
* Successful submit message. Maximum 128 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.warning.success'?: string
/**
* Answer confirm. Maximum 100 characters.
*/
'label.button.ok'?: string
/**
* Legal field terms and conditions message. Maximum 64 characters.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.error.mustAccept'?: string
/**
* Long text field tooltip message. Maximum 128 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'block.longtext.hint'?: string
/**
* Placeholder message with instructions for dropdown fields. Maximum 100 characters.
*/
'block.dropdown.placeholder'?: string
/**
* Placeholder message with instructions for dropdown fields on touch devices. Maximum 100 characters.
*/
'block.dropdown.placeholderTouch'?: string
/**
* Invalid URL error message. Maximum 64 characters. You can format messages with bold (`*bold*`) and italic (`_italic_`) text.
* HTML tags are forbidden.
*/
'label.error.url'?: string
/**
* Keyboard shortcut for the "Yes" option. Maximum 1 character.
*/
'label.yes.shortcut'?: string
/**
* Representation for the word "Yes". You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
'label.yes.default'?: string
}
/**
* Notification object.
*/
export interface Notification {
/**
* Settings for notifications sent when respondents complete and submit the typeform.
*/
self?: {
/**
* Default: `""`
* true to send notifications. false to disable notifications.
*/
enabled?: boolean
recipients?: string[]
/**
* Email address to use for notification Reply-To.
* Must be a Recall Information value based on respondent's answer to a field: {{field:ref}} or {{hidden:ref}}.
*/
reply_to?: string
/**
* Subject to use for the notification email. Can combine text and Recall Information value from one or more fields.
* Available Recall Information values are {{form:title}}, {{account:email}}, {{account:name}}, {{link:report}},
* and standard Recall Information for fields {{field:ref}} and hidden fields {{hidden:ref}}.
*/
subject?: string
/**
* Message to include in the body of the notification email. Can combine text and Recall Information value from one or more fields.
* Available Recall Information values are {{form:title}}, {{account:email}}, {{account:name}}, {{link:report}},
* {{form:all_answers}}, and standard Recall Information for fields {{field:ref}} and hidden fields {{hidden:ref}}.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
message?: string
}
/**
* Settings for notifications sent to respondents immediately after submitting the typeform
*/
respondent?: {
/**
* Default: `""`
* true to send respondent notifications. false to disable respondent notifications.
*/
enabled?: boolean
/**
* Email where respondent notification will be sent.
* Must be a Recall Information value based on respondent's answer to a field: {{field:ref}} or {{hidden:ref}}.
*/
recipient?: string
reply_to?: string[]
/**
* Subject to use for the notification email. Can combine text and Recall Information value from one or more fields.
* Available Recall Information values are {{form:title}}, {{account:fullname}}, {{account:email}}, {{account:name}},
* {{link:report}}, and standard Recall Information for fields {{field:ref}} and hidden fields {{hidden:ref}}.
*/
subject?: string
/**
* Message to include in the body of the notification email. Can combine text and Recall Information value from one or more fields.
* Available Recall Information values are {{form:title}}, {{account:fullname}}, {{account:email}}, {{account:name}},
* {{link:report}}, {{form:all_answers}}, and standard Recall Information for fields {{field:ref}} and hidden fields {{hidden:ref}}.
* You can format messages with bold (`*bold*`) and italic (`_italic_`) text. HTML tags are forbidden.
*/
message?: string
}
}
/**
* Properties object.
*/
export namespace Properties {
export interface Field {
/**
* Question or instruction to display for the field.
*/
description?: string
/**
* Answer choices. Available for `dropdown`, `multiple_choice`, and `picture_choice` types.
*/
choices?: Choice[]
/**
* Contains the fields that belong in a question group. Only `payment` and `group` blocks are not allowed inside a question group.
* Available for the `group` type.
*/
fields?: any[][]
/**
* true to allow respondents to select more than one answer choice. false to allow respondents to select only one answer choice.
* Available for `multiple_choice` and `picture_choice` types.
*/
allow_multiple_selection?: boolean
/**
* true if answer choices should be presented in a new random order for each respondent.
* false if answer choices should be presented in the same order for each respondent.
* Available for `multiple_choice` and `picture_choice` types.
*/
randomize?: boolean
/**
* true to include an "Other" option so respondents can enter a different answer choice from those listed.
* false to limit answer choices to those listed.
* Available for `multiple_choice` and `picture_choice` types.
*/
allow_other_choice?: boolean
/**
* true to list answer choices vertically. false to list answer choices horizontally.
* Available for `multiple_choice` types.
*/
vertical_alignment?: boolean
/**
* true if you want to use larger-sized images for answer choices. Otherwise, false. Available for `picture_choice` types.
*/
supersized?: boolean
/**
* Default: `""`
* true to show text labels and images as answer choices. false to show only images as answer choices.
* Available for `picture_choice` types.
*/
show_labels?: boolean
/**
* true if question should list dropdown answer choices in alphabetical order.
* false if question should list dropdown answer choices in the order they're listed in the "choices" array.
* Available for `dropdown` types.
*/
alphabetical_order?: boolean
/**
* true if you want to display quotation marks around the statement on the form. Otherwise, false. Available for statement types.
*/
hide_marks?: boolean
/**
* Default: `"Continue"`
* Text to display in the button associated with the object. Available for `group`, `payment`, and `statement` types.
*/
button_text?: string
/**
* Number of steps in the scale's range. Minimum is 5 and maximum is 11. Available for `opinion_scale` and `rating` types.
*/
steps?: 5 | 6 | 7 | 8 | 9 | 10 | 11
/**
* Default: `"star"`
* Shape to display on the scale's steps. Available for `opinion_scale` and `rating` types.
*/
shape?: 'cat' | 'circle' | 'cloud' | 'crown' | 'dog' | 'droplet' | 'flag' | 'heart' | 'lightbulb' | 'pencil' | 'skull' | 'star'
| 'thunderbolt' | 'tick' | 'trophy' | 'up' | 'user'
/**
* Label to help respondents understand the scale's range. Available for `opinion_scale` and `rating` types.
*/
labels?: {
/**
* Text of the left-aligned label for the scale.
*/
left?: string
/**
* Text of the right-aligned label for the scale.
*/
right?: string
/**
* Text of the center-aligned label for the scale.
*/
center?: string
}
/**
* true if range numbering should start at 1. false if range numbering should start at 0. Available for `opinion_scale` types.
*/
start_at_one?: boolean
/**
* Default: `"DDMMYYYY"`
* Format for month, date, and year in answer. Available for `date` types.
*/
structure?: 'MMDDYYYY' | 'DDMMYYYY' | 'YYYYMMDD'
/**
* Default: `"/"`
* Character to use between month, day, and year in answer. Available for `date` types.
*/
separator?: '/' | '-' | '.'
currency?: 'AUD' | 'BRL' | 'CAD' | 'CHF' | 'DKK' | 'EUR' | 'GBP' | 'MXN' | 'NOK' | 'SEK' | 'USD'
}
export interface ThankYouScreen {
/**
* true to display a 'Submit' button on the thank you screen. Otherwise, false.
*/
show_button?: boolean
/**
* Text to display on the 'Submit' button on the thank you screen.
*/
button_text?: string
/**
* Specify whether the form should reload or redirect to another URL when respondents click the 'Submit' button. PRO+ feature.
*/
button_mode?: 'reload' | 'redirect'
/**
* URL where the typeform should redirect after submission, if you specified "redirect" for `button_mode`.
*/
redirect_url?: string
/**
* true to display social media sharing icons on the thank you screen so respondents can post your typeform's link on Facebook,
* Twitter, LinkedIn, and Google+. Otherwise, false.
*/
share_icons?: boolean
}
export interface WelcomeScreen {
/**
* Description of the welcome screen.
*/
description?: string
/**
* true to display a 'Start' button on the welcome screen. Otherwise, false.
*/
show_button?: boolean
/**
* Text to display on the 'Start' button on the welcome screen.
*/
button_text?: string
}
}
/**
* Typeform request object.
*/
export interface Request extends DocumentData {
url: string
method: string
data?: DocumentData
argsHeaders?: DocumentData
params?: DocumentData
}
/**
* Form response and date and time of form landing and submission.
*/
export interface Response {
/**
* Unique ID for the response. Note that `response_id` values are unique per form but are not unique globally.
*/
response_id?: string
/**
* Time of the form landing. In ISO 8601 format, UTC time, to the second, with T as a delimiter between the date and time.
*/
landed_at?: string
/**
* Time that the form response was submitted. In ISO 8601 format, UTC time, to the second, with T as a delimiter between the date and time.
*/
submitted_at?: string
/**
* Metadata about a client's HTTP request.
*/
metadata?: {
user_agent?: string
/**
* Derived from user agent
*/
platform?: string
referer?: string
/**
* Ip of the client
*/
network_id?: string
}
hidden?: DocumentData
/**
* Subset of a complete form definition to be included with a submission.
*/
definition?: {
fields?: {
id?: string
type?: string
title?: string
description?: string
}[]
}
answers?: {
field?: {
/**
* The unique id of the form field the answer refers to.
*/
id?: string
/**
* The field's type in the original form.
*/
type?: string
/**
* The reference for the question the answer relates to. Use the `ref` value to match answers with questions.
* The Responses payload only includes `ref` for the fields where you specified them when you created the form.
*/
ref?: string
/**
* The form field's title which the answer is related to.
*/
title?: string
}
/**
* The answer-field's type.
*/
type?: 'choice' | 'choices' | 'date' | 'email' | 'url' | 'file_url' | 'number' | 'boolean' | 'text' | 'payment'
/**
* Represents single choice answers for dropdown-like fields.
*/
choice?: {
label?: string
other?: string
}
/**
* Represents multiple choice answers.
*/
choices?: {
labels?: string[]
other?: string
}
date?: string
email?: string
file_url?: string
number?: number
boolean?: boolean
text?: string
url?: string
payment?: {
amount?: string
last4?: string
name?: string
}
}[]
calculated?: {
score?: number
}
}
/**
* Typeform Form Settings object.
*/
export interface Settings {
/**
* Language of form.
*/
language?: Language
/**
* Default: `""`
* true if your form is public. Otherwise, false (your form is private).
*/
is_public?: boolean
/**
* Default: `"proportion"`
* Basis for the progress bar displayed on the screen. Choose "proportion" to show the number of questions answered so far.
* Choose "percentage" to show the percentage of questions answered so far.
*/
progress_bar?: 'percentage' | 'proportion'
/**
* Default: `""`
* true to display progress bar on the typeform. Otherwise, false.
*/
show_progress_bar?: boolean
/**
* Default: `""`
* true to display Typeform brand on the typeform. false to hide Typeform branding on the typeform.
* Hiding Typeform branding is available for PRO+ accounts.
*/
show_typeform_branding?: boolean
meta?: {
/**
* Default: `""`
* true to allow search engines to index your typeform. Otherwise, false.
*/
allow_indexing?: boolean
/**
* Description for search engines to display for your typeform.
*/
description?: string
image?: {
/**
* URL of image for search engines to display for your typeform.
*/
href?: string
}
}
/**
* URL where the typeform should redirect upon submission.
*/
redirect_after_submit_url?: string
/**
* Google Analytics tracking ID to use for the form.
*/
google_analytics?: string
/**
* Facebook Pixel tracking ID to use for the form.
*/
facebook_pixel?: string
/**
* Google Tag Manager ID to use for the form.
*/
google_tag_manager?: string
/**
* Notification object.
*/
notification?: Notification
}
/**
* A theme in your Typeform account.
*/
export interface Theme {
/**
* Settings for the background.
*/
background?: ThemeBackground
/**
* Colors the theme will apply to answers, background, buttons, and questions.
*/
colors?: ThemeColors
/**
* Default: `"Source Sans Pro"`
* Font for the theme.
*/
font?: Font
/**
* `true` if buttons should be transparent. Otherwise, `false`.
*/
has_transparent_button?: boolean
/**
* Unique ID of the theme.
*/
id?: string
/**
* Name of the theme.
*/
name?: string
/**
* Default: `"private"`
* Specifies whether the theme is `public` (one of Typeform's built-in themes that are available in all accounts) or `private`
* (a theme you created). You can only change `private` themes. You can't change Typeform's public themes.
*/
visibility?: 'public' | 'private'
}
/**
* Settings for a theme's background.
*/
export interface ThemeBackground {
/**
* Background image URL.
*/
href?: string
/**
* Default: `"fullscreen"`
* Layout for the background.
*/
layout?: 'fullscreen' | 'repeat' | 'no-repeat'
/**
* Brightness for the background. -1 is least bright (minimum) and 1 is most bright (maximum).
*/
brightness?: number
}
/**
* Colors the theme will apply to answers, background, buttons, and questions.
*/
export interface ThemeColors {
/**
* Color the theme will apply to answers. Hexadecimal value.
*/
answer?: string
/**
* Color the theme will apply to background. Hexadecimal value.
*/
background?: string
/**
* Color the theme will apply to buttons. Hexadecimal value.
*/
button?: string
/**
* Color the theme will apply to questions. Hexadecimal value.
*/
question?: string
}
/**
* Object that specifies the settings and properties for the form's thank you screen.
*/
export interface ThankYouScreen {
/**
* Readable name you can use to reference the thank you screen.
*/
ref?: string
/**
* Title for the thank you screen.
*/
title?: string
/**
* Properties of a thank you screen
*/
properties?: Properties.ThankYouScreen
/**
* Allows you to display images and videos.
* Available for welcome and thank you screens, as well as `date`, `dropdown`, `email`, `group`, `long_text`, `multiple_choice`,
* `number`, `opinion_scale`, `payment`, `rating`, `short_text`, `statement`, `phone_number`, and `yes_no` fields.
*/
attachment?: Attachment
}
/**
* The type of field.
*/
type Type = 'date' | 'dropdown' | 'email' | 'file_upload' | 'group' | 'legal' | 'long_text' | 'multiple_choice' | 'number'
| 'opinion_scale' | 'payment' | 'picture_choice' | 'rating' | 'short_text' | 'statement' | 'website' | 'yes_no' | 'phone_number'
/**
* Validations of a field.
*/
export interface Validations {
/**
* true if respondents must provide an answer. Otherwise, false.
* Available for `date`, `dropdown`, `email`, `file_upload`, `legal`, `long_text`, `multiple_choice`, `number`, `opinion_scale`,
* `payment`, `picture_choice`, `rating`, `short_text`, `website`, `phone_number`, and `yes_no` types.
*/
required?: boolean
/**
* Maximum number of characters allowed in the answer. Available for `long_text`, `number`, and `short_text` types.
*/
max_length?: number
/**
* Maximum value allowed in the answer. Available for `number` types.
*/
min_value?: number
/**
* Maximum value allowed in the answer. Available for number types.
*/
max_value?: number
}
/**
* Typeform Webhook object.
*/
export interface Webhook {
/**
* Unique ID for the webhook.
*/
id?: string
/**
* Unique ID for the typeform.
*/
form_id?: string
/**
* Unique name you want to use for the webhook.
*/
tag?: string
/**
* Webhook URL.
*/
url?: string
/**
* True if you want to send responses to the webhook immediately. Otherwise, false.
*/
enabled?: boolean
/**
* True if you want Typeform to verify SSL certificates when delivering payloads
*/
verify_ssl?: boolean
/**
* Date and time when webhook was created.
* In ISO 8601 format, UTC time, to the second, with T as a delimiter between the date and time.
*/
created_at?: string
/**
* Date of last update to webhook.
* In ISO 8601 format, UTC time, to the second, with T as a delimiter between the date and time.
*/
updated_at?: string
}
/**
* Object that specifies the settings and properties for the form's welcome screen.
*/
export interface WelcomeScreen {
/**
* Readable name you can use to reference the welcome screen.
*/
ref?: string
/**
* Title for the welcome screen.
*/
title?: string
/**
* Properties of a welcome screen
*/
properties?: Properties.WelcomeScreen
/**
* Allows you to display images and videos.
* Available for welcome and thank you screens, as well as `date`, `dropdown`, `email`, `group`, `long_text`, `multiple_choice`,
* `number`, `opinion_scale`, `payment`, `rating`, `short_text`, `statement`, `phone_number`, and `yes_no` fields.
*/
attachment?: Attachment
}
/**
* Typeform Workspace object.
*/
export interface Workspace {
/**
* Unique identifier for the workspace.
*/
id?: string
/**
* Name of the workspace.
*/
name?: string
/**
* If the default workspace, `true`. Otherwise, `false`.
*/
default?: boolean
/**
* If the workspace is shared with a team, `true`. Otherwise, `false`.
*/
shared?: boolean
forms?: {
/**
* Link to typeforms in the workspace.
*/
href?: string
/**
* Number of typeforms in the workspace.
*/
count?: number
}
self: {
/**
* Link to the workspace.
*/
href?: string
}
/**
* ID in the ULID format of the account where workspace belongs to.
*/
account_id?: string
members: {
name: string
email: string
role: 'owner' | 'member'
}[]
}
} | the_stack |
import { AbstractInputProps, useInput, useInputIcon, wrappedInputPropsAdapter } from "../../input";
import { Box, BoxProps } from "../../box";
import { CaretIcon } from "../../icons";
import { ChangeEvent, ComponentProps, FocusEvent, FocusEventHandler, MouseEvent, ReactElement, Ref, SyntheticEvent, forwardRef, useCallback, useMemo } from "react";
import { Div, HtmlButton } from "../../html";
import {
OmitInternalProps,
cssModule,
isNil,
isNilOrEmpty,
mergeClasses,
mergeProps,
omitProps,
useChainedEventCallback,
useControllableState,
useEventCallback,
useFocusWithin,
useRefState
} from "../../shared";
import { ResponsiveProp, useResponsiveValue } from "../../styling";
import { useFieldInputProps } from "../../field";
import { useInputGroupProps } from "../../input-group";
import { useToolbarProps } from "../../toolbar";
const DefaultElement = "input";
interface InnerNumberInputProps extends Omit<AbstractInputProps<typeof DefaultElement>, "max" | "min" | "step" | "value"> {
/**
* The default value of `value` when uncontrolled.
*/
defaultValue?: number;
/**
* Whether or not the input take up the width of its container.
*/
fluid?: ResponsiveProp<boolean>;
/**
* [Icon](/?path=/docs/icon--default-story) component rendered before the value.
*/
icon?: ReactElement;
/**
* Whether or not to render a loader.
*/
loading?: boolean;
/**
* The maximum value of the input.
*/
max?: number;
/**
* The minimum value of the input.
*/
min?: number;
/**
* Called when the input value change.
* @param {SyntheticEvent} event - React's original event.
* @param {number} value - The new value.
* @returns {void}
*/
onValueChange?: (event: SyntheticEvent, value: number) => void;
/**
* The step used to increment or decrement the value.
*/
step?: number;
/**
* A controlled value.
*/
value?: number | null;
/**
* Additional props to render on the wrapper element.
*/
wrapperProps?: Partial<BoxProps>;
}
interface SpinnerProps extends Omit<ComponentProps<"div">, "ref"> {
disableDecrement?: boolean;
disableIncrement?: boolean;
onDecrement?: (event: MouseEvent) => void;
onFocus?: FocusEventHandler;
onIncrement?: (event: MouseEvent) => void;
ref?: Ref<any>;
}
function Spinner({
disableDecrement,
disableIncrement,
onDecrement,
onFocus,
onIncrement,
...rest
}: SpinnerProps) {
const handleIncrement = useEventCallback((event: MouseEvent) => {
onIncrement(event);
});
const handleDecrement = useEventCallback((event: MouseEvent) => {
onDecrement(event);
});
return (
<Div
{...mergeProps(
rest,
{
"aria-hidden": true,
className: "o-ui-number-input-spinner"
}
)}
>
<HtmlButton
aria-label="Increment value"
className="o-ui-number-input-spinner-increment"
disabled={disableIncrement}
onClick={handleIncrement}
onFocus={onFocus}
tabIndex={-1}
type="button"
>
<CaretIcon size="xs" />
</HtmlButton>
<HtmlButton
aria-label="Decrement value"
className="o-ui-number-input-spinner-decrement"
disabled={disableDecrement}
onClick={handleDecrement}
onFocus={onFocus}
tabIndex={-1}
type="button"
>
<CaretIcon
size="xs"
transform="rotate(180deg)"
/>
</HtmlButton>
</Div>
);
}
function countDecimalPlaces(value: number) {
return (value.toString().split(".")[1] || []).length;
}
function toNumber(value: string) {
if (isNilOrEmpty(value)) {
return null;
}
const result = parseFloat(value);
if (isNaN(result)) {
return null;
}
return result;
}
function toFixed(value: number, precision: number) {
return parseFloat(value.toFixed(precision));
}
export function InnerNumberInput(props: InnerNumberInputProps) {
const [toolbarProps] = useToolbarProps();
const [fieldProps] = useFieldInputProps();
const [inputGroupProps, isInGroup] = useInputGroupProps();
const contextualProps = mergeProps(
{},
omitProps(toolbarProps, ["orientation"]),
fieldProps,
inputGroupProps
);
const {
active,
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledBy,
as = DefaultElement,
autoFocus,
defaultValue,
disabled,
fluid,
focus,
forwardedRef,
hover,
icon,
id,
loading,
max,
min,
onBlur,
onChange,
onFocus,
onValueChange,
placeholder,
readOnly,
required,
step = 1,
validationState,
value: valueProp,
wrapperProps: { as: wrapperAs = "div", ...userWrapperProps } = {},
...rest
} = mergeProps(
props,
wrappedInputPropsAdapter(contextualProps)
);
if (isNil(ariaLabel) && isNil(ariaLabelledBy) && isNil(placeholder)) {
console.error("An input component must either have an \"aria-label\" attribute, an \"aria-labelledby\" attribute or a \"placeholder\" attribute.");
}
const fluidValue = useResponsiveValue(fluid);
const [inputValueRef, setInputValue] = useRefState("");
const [value, setValue] = useControllableState(valueProp, defaultValue, null, {
onChange: useCallback((newValue, { isControlled, isInitial }) => {
// Keep input value "mostly" in sync with the initial or controlled value.
if (isInitial || isControlled) {
const rawValue = isNil(newValue) ? "" : newValue.toString();
setInputValue(rawValue);
}
return undefined;
}, [setInputValue])
});
const updateValue = (event: SyntheticEvent, newValue: number) => {
if (newValue !== value) {
setValue(newValue);
if (!isNil(onValueChange)) {
onValueChange(event, newValue);
}
}
const newInputValue = isNil(newValue) ? "" : newValue.toString();
if (newInputValue !== inputValueRef.current) {
setInputValue(newInputValue, true);
}
};
const validateRange = useCallback(newValue => {
let isAboveMax = false;
let isBelowMin = false;
if (!isNil(newValue)) {
if (!isNil(max) && newValue > max) {
isAboveMax = true;
} else if (!isNil(min) && newValue < min) {
isBelowMin = true;
}
}
return {
isAboveMax,
isBelowMin,
isInRange: !isAboveMax && !isBelowMin
};
}, [min, max]);
const clampOrSetValue = (event: SyntheticEvent, newValue: number) => {
if (!isNil(newValue)) {
const { isAboveMax, isBelowMin, isInRange } = validateRange(newValue);
if (isInRange) {
updateValue(event, newValue);
} else {
if (isBelowMin) {
updateValue(event, min);
} else if (isAboveMax) {
updateValue(event, max);
}
}
}
};
const applyStep = (event: SyntheticEvent, factor: number) => {
const inputValue = toNumber(inputValueRef.current);
if (!isNil(inputValue)) {
const precision = Math.max(countDecimalPlaces(inputValue), countDecimalPlaces(step));
const newValue = toFixed(inputValue + factor * step, precision);
clampOrSetValue(event, newValue);
} else {
clampOrSetValue(event, factor * step);
}
};
const handleChange = useChainedEventCallback(onChange, (event: ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value, true);
});
const handleIncrement = useEventCallback((event: MouseEvent) => {
applyStep(event, 1);
inputRef.current.focus();
});
const handleDecrement = useEventCallback((event: MouseEvent) => {
applyStep(event, -1);
inputRef.current.focus();
});
const focusWithinProps = useFocusWithin({
onBlur: useEventCallback((event: FocusEvent<HTMLInputElement>) => {
clampOrSetValue(event, toNumber(inputValueRef.current));
if (!isNil(onBlur)) {
onBlur(event);
}
}),
onFocus: useEventCallback((event: FocusEvent<HTMLInputElement>) => {
if (!isNil(onFocus)) {
onFocus(event);
}
})
});
const { inputProps, inputRef, wrapperProps } = useInput({
active,
autoFocus,
cssModule: "o-ui-number-input",
disabled,
fluid: fluidValue,
focus,
forwardedRef,
hover,
id,
loading,
onChange: handleChange,
placeholder,
readOnly,
required,
type: "number",
validationState,
value: inputValueRef.current
});
// eslint-disable-next-line react-hooks/exhaustive-deps
const numericInputValue = useMemo(() => toNumber(inputValueRef.current), [inputValueRef.current]);
const iconMarkup = useInputIcon(icon, { disabled });
const content = (
<>
{iconMarkup}
<Box
{...mergeProps(
rest,
{
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledBy,
as,
max,
min,
step
},
inputProps
)}
/>
<Spinner
aria-hidden={loading}
disableDecrement={readOnly || disabled || (!isNil(numericInputValue) && numericInputValue <= min)}
disableIncrement={readOnly || disabled || (!isNil(numericInputValue) && numericInputValue >= max)}
onDecrement={handleDecrement}
onIncrement={handleIncrement}
/>
</>
);
return (
<Box
{...mergeProps(
userWrapperProps,
wrapperProps,
{
as: wrapperAs,
className: mergeClasses(
cssModule(
"o-ui-input",
iconMarkup && "has-icon",
isInGroup && "in-group"
),
cssModule(
"o-ui-number-input",
isInGroup && "in-group"
)
)
},
focusWithinProps
)}
>
{content}
</Box>
);
}
InnerNumberInput.defaultElement = DefaultElement;
export const NumberInput = forwardRef<any, OmitInternalProps<InnerNumberInputProps>>((props, ref) => (
<InnerNumberInput {...props} forwardedRef={ref} />
));
export type NumberInputProps = ComponentProps<typeof NumberInput>; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
class PrincipalObjectAttributeAccessApi {
/**
* DynamicsCrm.DevKit PrincipalObjectAttributeAccessApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the shared secured field */
AttributeId: DevKit.WebApi.GuidValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_account: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_activityfileattachment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appelement: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_applicationuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appmodulecomponentedge: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appmodulecomponentnode: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appnotification: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appointment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_appusersetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_attributeimageconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_bot: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_botcomponent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_businessunit: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_canvasappextendedmetadata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_catalog: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_catalogassignment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
channelaccessprofile_principalobjectattributeaccess: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_connection: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_connectionreference: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_connector: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_contact: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_conversationtranscript: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customapi: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customapirequestparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customapiresponseproperty: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_customeraddress: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_datalakefolder: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_datalakefolderpermission: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_datalakeworkspace: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_datalakeworkspacepermission: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_devkit_bpfaccount: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entityanalyticsconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_entityimageconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_environmentvariabledefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_environmentvariablevalue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_exportsolutionupload: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_fax: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_featurecontrolsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_feedback: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_flowmachine: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_flowmachinegroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_flowsession: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_goal: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_holidaywrapper: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_internalcatalogassignment: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_kbarticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_keyvaultreference: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_knowledgearticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_knowledgearticleviews: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_knowledgebaserecord: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_letter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_mailmergetemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_managedidentity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdynce_botcontent: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibdataset: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aimodel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiodimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiodlabel: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_aitemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_dataflow: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_federatedarticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_helppage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_pminferredtask: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_pmrecording: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_richtextfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_slakpi: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_msdyn_tour: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_organizationsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_package: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_pdfsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_phonecall: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_pluginpackage: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_position: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_processstageparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_provisionlanguageforuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_queue: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_queueitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_recurringappointmentmaster: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_relationshipattribute: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_reportcategory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_serviceplan: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_serviceplanmapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_settingdefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_sharepointdocumentlocation: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_sharepointsite: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_socialactivity: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_socialprofile: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_solutioncomponentbatchconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_stagesolutionupload: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_systemuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_task: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_territory: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_virtualentitymetadata: DevKit.WebApi.LookupValue;
/** Unique identifier of the entity instance with shared secured field */
objectid_workflowbinary: DevKit.WebApi.LookupValue;
/** Unique identifier of the associated organization. */
OrganizationId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the principal to which secured field is shared */
principalid_systemuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the principal to which secured field is shared */
principalid_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the shared secured field instance */
PrincipalObjectAttributeAccessId: DevKit.WebApi.GuidValue;
/** Read permission for secured field instance */
ReadAccess: DevKit.WebApi.BooleanValue;
/** Update permission for secured field instance */
UpdateAccess: DevKit.WebApi.BooleanValue;
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace PrincipalObjectAttributeAccess {
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':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {
mergeRows, calculateRequestedRange, rowToPageIndex,
recalculateBounds, trimRowsToInterval,
getForceReloadInterval, getAvailableRowCount,
needFetchMorePages, shouldSendRequest, getRequestMeta,
} from './helpers';
import { intervalUtil } from './utils';
import { createInterval, generateRows, createVirtualRows } from './test-utils';
describe('VirtualTableState helpers', () => {
describe('#mergeRows', () => {
describe('nonoverlapping', () => {
it('should merge rows when cache is before rows', () => {
const cacheInterval = createInterval(10, 14);
const rowsInterval = createInterval(14, 18);
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 14, 10)).toEqual({
skip: 10,
rows: [
...cache, ...rows,
],
});
});
it('should merge rows when rows are before cache', () => {
const cacheInterval = createInterval(14, 18);
const rowsInterval = createInterval(10, 14);
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 10, 14)).toEqual({
skip: 10,
rows: [
...rows, ...cache,
],
});
});
});
describe('overlapping', () => {
it('should merge rows when cache is before rows', () => {
const cacheInterval = createInterval(10, 20);
const rowsInterval = createInterval(15, 25);
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 15, 10)).toEqual({
skip: 10,
rows: [
...cache.slice(0, 5), ...rows,
],
});
});
it('should merge rows when rows are before cache', () => {
const cacheInterval = createInterval(15, 25);
const rowsInterval = createInterval(10, 20);
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 10, 15)).toEqual({
skip: 10,
rows: [
...rows, ...cache.slice(5),
],
});
});
it('should merge rows when cache contains rows', () => {
const cacheInterval = createInterval(10, 30);
const rowsInterval = createInterval(15, 25);
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 15, 10)).toEqual({
skip: 10,
rows: [
...cache.slice(0, 5), ...rows, ...cache.slice(15),
],
});
});
it('should merge rows when rows contain cache', () => {
const cacheInterval = createInterval(15, 25);
const rowsInterval = createInterval(10, 30);
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 10, 15)).toEqual({
skip: 10,
rows,
});
});
});
describe('empty interval', () => {
it('should merge rows when cache is empty', () => {
const cacheInterval = intervalUtil.empty;
const rowsInterval = createInterval(10, 20);
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 10, 15)).toEqual({
skip: 10,
rows,
});
});
it('should merge rows when rows are empty', () => {
const cacheInterval = createInterval(10, 20);
const rowsInterval = intervalUtil.empty;
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 15, 10)).toEqual({
skip: 10,
rows: cache,
});
});
it('should merge rows when both rows and cache are empty', () => {
const cacheInterval = intervalUtil.empty;
const rowsInterval = intervalUtil.empty;
const cache = generateRows(cacheInterval, 'cache');
const rows = generateRows(rowsInterval, 'rows');
expect(mergeRows(rowsInterval, cacheInterval, rows, cache, 15, 10)).toEqual({
skip: undefined,
rows: [],
});
});
});
describe('partial merge', () => {
it('should merge rows according to intervals', () => {
const fullCacheInterval = createInterval(0, 30);
const fullRowsInterval = createInterval(20, 50);
const cache = generateRows(fullCacheInterval, 'cache');
const rows = generateRows(fullRowsInterval, 'rows');
const visibleCacheInterval = createInterval(10, 30);
const visibleRowsInterval = createInterval(20, 40);
expect(mergeRows(visibleRowsInterval, visibleCacheInterval, rows, cache, 20, 0)).toEqual({
skip: 10,
rows: [
...cache.slice(10, 20), ...rows.slice(0, 20),
],
});
});
});
});
describe('#calculateRequestedRange', () => {
const pageSize = 100;
describe('simple cases', () => {
it('should caclulate requested range for next page', () => {
const loadedInterval = createInterval(100, 400);
const newInterval = createInterval(200, 500);
const virtualRows = createVirtualRows(loadedInterval);
expect(calculateRequestedRange(virtualRows, newInterval, pageSize))
.toEqual({ start: 400, end: 500 });
});
it('should caclulate requested range for previous page', () => {
const loadedInterval = createInterval(200, 500);
const newInterval = createInterval(100, 400);
const virtualRows = createVirtualRows(loadedInterval);
expect(calculateRequestedRange(virtualRows, newInterval, pageSize))
.toEqual({ start: 100, end: 200 });
});
it('should caclulate requested range for next 2 pages', () => {
const loadedInterval = createInterval(100, 400);
const newInterval = createInterval(400, 700);
const virtualRows = createVirtualRows(loadedInterval);
expect(calculateRequestedRange(virtualRows, newInterval, pageSize))
.toEqual({ start: 400, end: 700 });
});
it('should caclulate requested range for previous 2 pages', () => {
const loadedInterval = createInterval(300, 600);
const newInterval = createInterval(100, 400);
const virtualRows = createVirtualRows(loadedInterval);
expect(calculateRequestedRange(virtualRows, newInterval, pageSize))
.toEqual({ start: 100, end: 400 });
});
});
describe('edge cases', () => {
it('should correctly process start of page', () => {
const loadedInterval = createInterval(0, 200);
const newInterval = createInterval(200, 500);
const virtualRows = createVirtualRows(loadedInterval);
expect(calculateRequestedRange(virtualRows, newInterval, pageSize))
.toEqual({ start: 200, end: 500 });
});
it('should correctly process end of page', () => {
const loadedInterval = createInterval(0, 200);
const newInterval = createInterval(200, 500);
const virtualRows = createVirtualRows(loadedInterval);
expect(calculateRequestedRange(virtualRows, newInterval, pageSize))
.toEqual({ start: 200, end: 500 });
});
it('should correctly process the last page', () => {
const loadedInterval = createInterval(0, 200);
const newInterval = createInterval(1000, 1200);
const virtualRows = createVirtualRows(loadedInterval);
expect(calculateRequestedRange(virtualRows, newInterval, pageSize))
.toEqual({ start: 1000, end: 1200 });
});
});
describe('fast scroll', () => {
const loadedInterval = createInterval(200, 500);
const newInterval = createInterval(1000, 1300);
const virtualRows = createVirtualRows(loadedInterval);
it('should return prev, current and next pages', () => {
expect(calculateRequestedRange(virtualRows, newInterval, pageSize))
.toEqual({ start: 1000, end: 1300 });
});
});
describe('reference index', () => {
// tslint:disable-next-line: max-line-length
it('should caclulate correct if reference index more than the start of a calculated interval and less than half of page', () => {
const loadedInterval = createInterval(100, 400);
const newInterval = createInterval(200, 500);
const virtualRows = createVirtualRows(loadedInterval);
const referenceIndex = 440;
expect(calculateRequestedRange(virtualRows, newInterval, pageSize, referenceIndex))
.toEqual({ start: 400, end: 500 });
});
// tslint:disable-next-line: max-line-length
it('should caclulate correct if reference index less than the start of a calculated interval', () => {
const loadedInterval = createInterval(100, 400);
const newInterval = createInterval(200, 500);
const virtualRows = createVirtualRows(loadedInterval);
const referenceIndex = 360;
expect(calculateRequestedRange(virtualRows, newInterval, pageSize, referenceIndex))
.toEqual({ start: 400, end: 500 });
});
// tslint:disable-next-line: max-line-length
describe('reference index less than the start of a calculated interval and less than half of page', () => {
const loadedInterval = createInterval(100, 400);
const newInterval = createInterval(200, 500);
const virtualRows = createVirtualRows(loadedInterval);
const referenceIndex = 320;
it('should caclulate correct if infinite scrolling', () => {
expect(calculateRequestedRange(virtualRows, newInterval, pageSize, referenceIndex, true))
.toEqual({ start: 300, end: 400 });
});
it('should caclulate correct if non-infinite scrolling', () => {
expect(calculateRequestedRange(virtualRows, newInterval, pageSize, referenceIndex, false))
.toEqual({ start: 400, end: 500 });
});
// T937684
it('should calculate correctly if infinite scrolling is enabled and the end of the calculated interval is not divisible by the page size', () => {
expect(calculateRequestedRange(
createVirtualRows(createInterval(0, 100)),
createInterval(0, 137),
50,
51,
true))
.toEqual({ start: 50, end: 100 });
});
});
});
// tslint:disable-next-line: max-line-length
it('should caclulate correct in non-infinite scrolling', () => {
const loadedInterval = createInterval(100, 400);
const newInterval = createInterval(200, 500);
const virtualRows = createVirtualRows(loadedInterval);
const referenceIndex = 320;
expect(calculateRequestedRange(virtualRows, newInterval, pageSize, referenceIndex))
.toEqual({ start: 400, end: 500 });
});
});
describe('#rowToPageIndex', () => {
it('should return virtual page index', () => {
expect(rowToPageIndex(0, 100)).toBe(0);
expect(rowToPageIndex(50, 100)).toBe(0);
expect(rowToPageIndex(99, 100)).toBe(0);
expect(rowToPageIndex(100, 100)).toBe(1);
});
});
describe('#calculateBounds', () => {
it('should return boundaries from previous page start to next page end', () => {
expect(recalculateBounds(350, 100, 1000)).toEqual({
start: 200,
end: 500,
});
});
it('should correctly process start index of page', () => {
expect(recalculateBounds(300, 100, 1000)).toEqual({
start: 200,
end: 500,
});
});
it('should correctly process end index of page', () => {
expect(recalculateBounds(299, 100, 1000)).toEqual({
start: 100,
end: 400,
});
});
it('should be bounded below by 0', () => {
expect(recalculateBounds(30, 100, 1000)).toEqual({
start: 0,
end: 200,
});
});
it('should be bounded above by total rows count', () => {
expect(recalculateBounds(950, 100, 1000)).toEqual({
start: 800,
end: 1000,
});
});
});
describe('#trimRowsToInterval', () => {
it('should trim right side', () => {
const rowsInterval = createInterval(10, 20);
const targetInterval = createInterval(5, 15);
const virtualRows = createVirtualRows(rowsInterval);
expect(trimRowsToInterval(virtualRows, targetInterval)).toEqual({
skip: 10,
rows: [
...virtualRows.rows.slice(0, 5),
],
});
});
it('should trim left side', () => {
const rowsInterval = createInterval(10, 20);
const targetInterval = createInterval(15, 25);
const virtualRows = createVirtualRows(rowsInterval);
expect(trimRowsToInterval(virtualRows, targetInterval)).toEqual({
skip: 15,
rows: [
...virtualRows.rows.slice(5, 10),
],
});
});
it('should trim both sides', () => {
const rowsInterval = createInterval(10, 30);
const targetInterval = createInterval(15, 25);
const virtualRows = createVirtualRows(rowsInterval);
expect(trimRowsToInterval(virtualRows, targetInterval)).toEqual({
skip: 15,
rows: [
...virtualRows.rows.slice(5, 15),
],
});
});
it('should return empty if target interval does not contain rows', () => {
const rowsInterval = createInterval(10, 20);
const targetInterval = createInterval(25, 35);
const virtualRows = createVirtualRows(rowsInterval);
expect(trimRowsToInterval(virtualRows, targetInterval)).toEqual({
skip: Number.POSITIVE_INFINITY,
rows: [],
});
});
});
describe('#getAvailableRowCount', () => {
const totalRowCount = 1000;
it('should return totalCount when not infinite scrolling', () => {
const isInfniniteScroll = false;
const newRowCount = 200;
const lastRowCount = 100;
expect(getAvailableRowCount(
isInfniniteScroll,
newRowCount,
lastRowCount,
totalRowCount,
)).toEqual(totalRowCount);
});
describe('infinite scrolling mode', () => {
const isInfniniteScroll = true;
const newRowCount = 200;
it('should return newRowCount if it more than lastRowCount in infinite scrolling', () => {
const lastRowCount = 100;
expect(getAvailableRowCount(
isInfniniteScroll,
newRowCount,
lastRowCount,
totalRowCount,
)).toEqual(newRowCount);
});
it('should return lastRowCount if it more than newRowCount in infinite scrolling', () => {
const lastRowCount = 300;
expect(getAvailableRowCount(
isInfniniteScroll,
newRowCount,
lastRowCount,
totalRowCount,
)).toEqual(lastRowCount);
});
});
});
describe('#getForceReloadInterval', () => {
it('should return 2 pages if loaded interval is less than 2 pages', () => {
const virtualRows = createVirtualRows(createInterval(100, 200));
expect(getForceReloadInterval(virtualRows, 100, 1000)).toEqual({
start: 100,
end: 300,
});
});
it('should return loaded interval if it is more than 2 pages', () => {
const virtualRows = createVirtualRows(createInterval(100, 400));
expect(getForceReloadInterval(virtualRows, 100, 1000)).toEqual({
start: 100,
end: 400,
});
});
it('should return 2 pages if current total count is 0', () => {
const virtualRows = createVirtualRows(createInterval(0, 0));
expect(getForceReloadInterval(virtualRows, 100, 0)).toEqual({
start: 0,
end: 200,
});
});
});
describe('#needFetchMorePages', () => {
const virtualRows = createVirtualRows(createInterval(100, 400));
it('should return false when referenceIndex is inside of a middle page', () => {
expect(needFetchMorePages(virtualRows, 220, 100))
.toBeFalsy();
});
it('should return true when referenceIndex is inside of a top page', () => {
expect(needFetchMorePages(virtualRows, 150, 100))
.toBeTruthy();
});
it('should return true when referenceIndex is inside of a bottom page', () => {
expect(needFetchMorePages(virtualRows, 350, 100))
.toBeTruthy();
});
it('should return true when referenceIndex is outside of a loaded range', () => {
expect(needFetchMorePages(virtualRows, 500, 100))
.toBeTruthy();
});
});
describe('#shouldSendRequest', () => {
it('should return false if page is already requested', () => {
expect(shouldSendRequest({ start: 100, end: 200 }, 100))
.toBeFalsy();
});
it('should return true if page is not yet requested', () => {
expect(shouldSendRequest({ start: 100, end: 200 }, 400))
.toBeTruthy();
});
it('should return false if requested range is empty', () => {
expect(shouldSendRequest({ start: 100, end: 100 }, 400))
.toBeFalsy();
});
});
describe('#getRequestMeta', () => {
const virtualRows = createVirtualRows(createInterval(200, 500));
it('should work', () => {
expect(getRequestMeta(470, virtualRows, 100, 1000, false))
.toEqual({
actualBounds: { start: 300, end: 600 },
requestedRange: { start: 500, end: 600 },
});
});
it('should work with force reload', () => {
expect(getRequestMeta(370, virtualRows, 100, 1000, true))
.toEqual({
actualBounds: { start: 200, end: 500 },
requestedRange: { start: 200, end: 500 },
});
});
});
}); | the_stack |
export const enum InternalErrorCode {
ackTimeout = 'ackTimeout',
establishSecureChannelTimeout = 'establishSecureChannelTimeout',
parentVerifyTimeout = 'parentVerifyTimeout',
illegalStateError = 'illegalStateError',
providerInitializationFailed = 'providerInitializationFailed',
apiDisabled = 'apiDisabled',
untrustedOrigin = 'untrustedOrigin',
parentIsNotRoot = 'parentIsNotRoot',
userCanceled = 'userCanceled',
noCredentialsAvailable = 'noCredentialsAvailable',
operationCanceled = 'operationCanceled',
clientDisposed = 'clientDisposed',
requestFailed = 'requestFailed',
requestTimeout = 'requestTimeout',
illegalConcurrentRequest = 'illegalConcurrentRequest',
unknownRequest = 'unknownRequest',
browserWrappingRequired = 'browserWrappingRequired',
unsupportedBrowser = 'unsupportedBrowser',
unknownError = 'unknownError'
}
/* Exposed error types meant for apps to trigger different flows. */
export const enum OpenYoloErrorType {
initializationError = 'initializationError',
unsupportedBrowser = 'unsupportedBrowser',
configurationError = 'configurationError',
userCanceled = 'userCanceled',
noCredentialsAvailable = 'noCredentialsAvailable',
operationCanceled = 'operationCanceled',
clientDisposed = 'clientDisposed',
requestFailed = 'requestFailed',
illegalConcurrentRequest = 'illegalConcurrentRequest',
browserWrappingRequired = 'browserWrappingRequired',
unknownError = 'unknownError'
}
/**
* Data containing additional information on the error, used only in the
* provider frame.
*/
export interface OpenYoloErrorData {
/** Standardized error code. */
code: InternalErrorCode;
/** Type of the corresponding exposed error. */
exposedErrorType: OpenYoloErrorType;
/** Developer visible and non sensitive error message. */
message: string;
/** Additional, potentially sensitive, information. */
additionalInformation?: {[key in string]: string};
}
/**
* Data containing additional information on the error, stripped of potentially
* sensitive data. It is the interface of the object sent through the
* SecureChannel to the client.
*/
export interface OpenYoloExposedErrorData {
/** Standardized exposed error type. */
type: OpenYoloErrorType;
/**
* Developer visible and non sensitive error message. It will contain the
* InternalErrorCode for easier reference: `${code}: ${message}`.
*/
message: string;
}
/**
* It is not possible to subclass Error, Array, Map... in TS anymore. It is
* recommended to create our own Error classes.
* https://github.com/Microsoft/TypeScript/issues/13965
*/
export interface CustomError {
/** Name of the error. */
name: string;
/** Message of the error. */
message: string;
}
/**
* Internal error.
*/
export class OpenYoloInternalError implements CustomError {
name = 'OpenYoloInternalError';
message: string;
constructor(public data: OpenYoloErrorData) {
this.message = data.message;
}
/** Returns the client-side exposed error. */
toExposedError(): OpenYoloError {
return OpenYoloError.fromData(this.toExposedErrorData());
}
/** Returns the client-side exposed error data. */
private toExposedErrorData(): OpenYoloExposedErrorData {
return {
type: this.data.exposedErrorType,
message: `${this.data.code}: ${this.data.message}`
};
}
/* Initialization errors. */
static ackTimeout() {
return new OpenYoloInternalError({
code: InternalErrorCode.ackTimeout,
exposedErrorType: OpenYoloErrorType.initializationError,
message: 'A parent frame failed to acknowledge the handshake. This can ' +
'be due, in nested context, to the absence of the handshake ' +
'responder library.'
});
}
static establishSecureChannelTimeout() {
return new OpenYoloInternalError({
code: InternalErrorCode.establishSecureChannelTimeout,
exposedErrorType: OpenYoloErrorType.initializationError,
message: 'The Secure Channel failed to initialize in a timely manner. ' +
'This can be due to network latency or a wrong configuration.'
});
}
static parentVerifyTimeout() {
return new OpenYoloInternalError({
code: InternalErrorCode.parentVerifyTimeout,
exposedErrorType: OpenYoloErrorType.initializationError,
message: 'The credentials provider frame failed to verify the ancestor ' +
'frames in a timely manner.'
});
}
static illegalStateError(reason: string) {
return new OpenYoloInternalError({
code: InternalErrorCode.illegalStateError,
exposedErrorType: OpenYoloErrorType.initializationError,
message: `An internal error happened: ${reason}`
});
}
static providerInitializationFailed() {
return new OpenYoloInternalError({
code: InternalErrorCode.providerInitializationFailed,
exposedErrorType: OpenYoloErrorType.initializationError,
message: 'The credentials provider frame failed to initialize.'
});
}
static apiDisabled() {
return new OpenYoloInternalError({
code: InternalErrorCode.apiDisabled,
exposedErrorType: OpenYoloErrorType.initializationError,
message:
'The API has been disabled by the user’s preference or has not been' +
' enabled in the OpenYolo configuration.'
});
}
/* Configuration errors. */
static untrustedOrigin(origin: string) {
return new OpenYoloInternalError({
code: InternalErrorCode.untrustedOrigin,
exposedErrorType: OpenYoloErrorType.configurationError,
message: `A parent frame does not belong to an authorized origin. ` +
`Ensure the configuration of OpenYolo contains '${origin}'.`
});
}
static parentIsNotRoot() {
return new OpenYoloInternalError({
code: InternalErrorCode.parentIsNotRoot,
exposedErrorType: OpenYoloErrorType.configurationError,
message:
`The caller window is an IFrame which is not authorized in OpenYolo` +
`configuration.`
});
}
/* Flow errors. */
static userCanceled(message?: string) {
return new OpenYoloInternalError({
code: InternalErrorCode.userCanceled,
exposedErrorType: OpenYoloErrorType.userCanceled,
message: message || 'The user canceled the operation.'
});
}
static noCredentialsAvailable() {
return new OpenYoloInternalError({
code: InternalErrorCode.noCredentialsAvailable,
exposedErrorType: OpenYoloErrorType.noCredentialsAvailable,
message: 'No credential is available for the current user.'
});
}
static operationCanceled() {
return new OpenYoloInternalError({
code: InternalErrorCode.operationCanceled,
exposedErrorType: OpenYoloErrorType.operationCanceled,
message: 'The operation was canceled.'
});
}
static clientDisposed() {
return new OpenYoloInternalError({
code: InternalErrorCode.clientDisposed,
exposedErrorType: OpenYoloErrorType.clientDisposed,
message: 'The API has been disposed from the current context.'
});
}
/* Request errors. */
static requestFailed(message: string) {
return new OpenYoloInternalError({
code: InternalErrorCode.requestFailed,
exposedErrorType: OpenYoloErrorType.requestFailed,
message: `The API request failed to resolve: ${message}`
});
}
static requestTimeout() {
return new OpenYoloInternalError({
code: InternalErrorCode.requestTimeout,
exposedErrorType: OpenYoloErrorType.requestFailed,
message: 'The API request timed out.'
});
}
static requestTimeoutOnInitialization() {
return new OpenYoloInternalError({
code: InternalErrorCode.requestTimeout,
exposedErrorType: OpenYoloErrorType.requestFailed,
message: 'The API request timed out. This may occur when error is ' +
'returned upon initialization. If you are using Google Yolo, ' +
'this error could happen if you haven\'t registered the origin ' +
'with your OAuth client.'
});
}
static illegalConcurrentRequestError() {
return new OpenYoloInternalError({
code: InternalErrorCode.illegalConcurrentRequest,
exposedErrorType: OpenYoloErrorType.illegalConcurrentRequest,
message:
'The request could not be resolved because another operation is ' +
'currently pending.'
});
}
static unknownRequest(requestType: string) {
return new OpenYoloInternalError({
code: InternalErrorCode.unknownRequest,
exposedErrorType: OpenYoloErrorType.requestFailed,
message: `The '${requestType}' request sent could not be handled by the` +
` credentials provider.`
});
}
static browserWrappingRequired() {
return new OpenYoloInternalError({
code: InternalErrorCode.browserWrappingRequired,
exposedErrorType: OpenYoloErrorType.browserWrappingRequired,
message: 'The current request requires using navigator.credentials.'
});
}
static unsupportedBrowser() {
return new OpenYoloInternalError({
code: InternalErrorCode.unsupportedBrowser,
exposedErrorType: OpenYoloErrorType.unsupportedBrowser,
message: `Unsupported browser - API disabled`
});
}
static unknownError() {
return new OpenYoloInternalError({
code: InternalErrorCode.unknownError,
exposedErrorType: OpenYoloErrorType.unknownError,
message: `Unknown error.`
});
}
static errorIs(err: any, code: InternalErrorCode) {
// Force comparability for the purposes of this dynamic check.
if ('data' in err) {
return err['data']['code'] === code;
}
return false;
}
}
/**
* Client side exposed error type.
*/
export declare interface OpenYoloError extends CustomError {
/** Standardized error type. */
type: OpenYoloErrorType;
/**
* Developer visible and non sensitive error message. It will contain the
* InternalErrorCode for easier reference: `${code}: ${message}`.
*/
message: string;
}
export class OpenYoloError {
name = 'OpenYoloError';
message: string;
constructor(message: string, public type: OpenYoloErrorType) {
this.message = message;
}
toData(): OpenYoloExposedErrorData {
return {message: this.message, type: this.type};
}
static fromData(data: OpenYoloExposedErrorData): OpenYoloError {
return new OpenYoloError(data.message, data.type);
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.